kanidmd_lib/idm/
ldap.rs

1//! LDAP specific operations handling components. This is where LDAP operations
2//! are sent to for processing.
3
4use std::collections::BTreeSet;
5use std::iter;
6use std::str::FromStr;
7
8use compact_jwt::JwsCompact;
9use kanidm_proto::constants::*;
10use kanidm_proto::internal::{ApiToken, UserAuthToken};
11use ldap3_proto::simple::*;
12use regex::{Regex, RegexBuilder};
13use std::net::IpAddr;
14use tracing::trace;
15use uuid::Uuid;
16
17use crate::event::SearchEvent;
18use crate::idm::event::{LdapApplicationAuthEvent, LdapAuthEvent, LdapTokenAuthEvent};
19use crate::idm::server::{IdmServer, IdmServerAuthTransaction, IdmServerTransaction};
20use crate::prelude::*;
21
22// Clippy doesn't like Bind here. But proto needs unboxed ldapmsg,
23// and ldapboundtoken is moved. Really, it's not too bad, every message here is pretty sucky.
24#[allow(clippy::large_enum_variant)]
25pub enum LdapResponseState {
26    Unbind,
27    Disconnect(LdapMsg),
28    Bind(LdapBoundToken, LdapMsg),
29    Respond(LdapMsg),
30    MultiPartResponse(Vec<LdapMsg>),
31    BindMultiPartResponse(LdapBoundToken, Vec<LdapMsg>),
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum LdapSession {
36    // Maps through and provides anon read, but allows us to check the validity
37    // of the account still.
38    UnixBind(Uuid),
39    UserAuthToken(UserAuthToken),
40    ApiToken(ApiToken),
41    ApplicationPasswordBind(Uuid, Uuid),
42}
43
44#[derive(Debug, Clone)]
45pub struct LdapBoundToken {
46    // Used to help ID the user doing the action, makes logging nicer.
47    pub spn: String,
48    pub session_id: Uuid,
49    // This is the effective session permission. This is generated from either:
50    // * A valid anonymous bind
51    // * A valid unix pw bind
52    // * A valid ApiToken
53    // In a way, this is a stepping stone to an "ident" but allows us to check
54    // the session is still "valid" depending on it's origin.
55    pub effective_session: LdapSession,
56}
57
58pub struct LdapServer {
59    rootdse: LdapSearchResultEntry,
60    basedn: String,
61    dnre: Regex,
62    binddnre: Regex,
63    max_queryable_attrs: usize,
64}
65
66#[derive(Debug)]
67enum LdapBindTarget {
68    Account(Uuid),
69    ApiToken,
70    Application(String, Uuid),
71}
72
73impl LdapServer {
74    pub async fn new(idms: &IdmServer) -> Result<Self, OperationError> {
75        // let ct = duration_from_epoch_now();
76        let mut idms_prox_read = idms.proxy_read().await?;
77        // This is the rootdse path.
78        // get the domain_info item
79        let domain_entry = idms_prox_read
80            .qs_read
81            .internal_search_uuid(UUID_DOMAIN_INFO)?;
82
83        // Get the maximum number of queryable attributes from the domain entry
84        let max_queryable_attrs = domain_entry
85            .get_ava_single_uint32(Attribute::LdapMaxQueryableAttrs)
86            .map(|u| u as usize)
87            .unwrap_or(DEFAULT_LDAP_MAXIMUM_QUERYABLE_ATTRIBUTES);
88
89        let basedn = domain_entry
90            .get_ava_single_iutf8(Attribute::DomainLdapBasedn)
91            .map(|s| s.to_string())
92            .or_else(|| {
93                domain_entry
94                    .get_ava_single_iname(Attribute::DomainName)
95                    .map(ldap_domain_to_dc)
96            })
97            .ok_or(OperationError::InvalidEntryState)?;
98
99        // It is necessary to swap greed to avoid the first group "<attr>=<val>" matching the
100        // next group "app=<app>", son one can use "app=app1,dc=test,dc=net" as search base:
101        // Greedy (app=app1,dc=test,dc=net):
102        //     Match 1      - app=app1,dc=test,dc=net
103        //     Group 1      - app=app1,
104        //     Group <attr> - app
105        //     Group <val>  - app1
106        //     Group 6      - dc=test,dc=net
107        // Ungreedy (app=app1,dc=test,dc=net):
108        //     Match 1      - app=app1,dc=test,dc=net
109        //     Group 4      - app=app1,
110        //     Group <app>  - app1
111        //     Group 6      - dc=test,dc=net
112        let dnre = RegexBuilder::new(
113            format!("^((?P<attr>[^=,]+)=(?P<val>[^=,]+),)?(app=(?P<app>[^=,]+),)?({basedn})$")
114                .as_str(),
115        )
116        .swap_greed(true)
117        .build()
118        .map_err(|_| OperationError::InvalidEntryState)?;
119
120        let binddnre = Regex::new(
121            format!("^((([^=,]+)=)?(?P<val>[^=,]+))(,app=(?P<app>[^=,]+))?(,{basedn})?$").as_str(),
122        )
123        .map_err(|_| OperationError::InvalidEntryState)?;
124
125        let rootdse = LdapSearchResultEntry {
126            dn: "".to_string(),
127            attributes: vec![
128                LdapPartialAttribute {
129                    atype: ATTR_OBJECTCLASS.to_string(),
130                    vals: vec!["top".as_bytes().to_vec()],
131                },
132                LdapPartialAttribute {
133                    atype: "vendorname".to_string(),
134                    vals: vec!["Kanidm Project".as_bytes().to_vec()],
135                },
136                LdapPartialAttribute {
137                    atype: "vendorversion".to_string(),
138                    vals: vec![env!("CARGO_PKG_VERSION").as_bytes().to_vec()],
139                },
140                LdapPartialAttribute {
141                    atype: "supportedldapversion".to_string(),
142                    vals: vec!["3".as_bytes().to_vec()],
143                },
144                LdapPartialAttribute {
145                    atype: "supportedextension".to_string(),
146                    vals: vec!["1.3.6.1.4.1.4203.1.11.3".as_bytes().to_vec()],
147                },
148                LdapPartialAttribute {
149                    atype: "supportedfeatures".to_string(),
150                    vals: vec!["1.3.6.1.4.1.4203.1.5.1".as_bytes().to_vec()],
151                },
152                LdapPartialAttribute {
153                    atype: "defaultnamingcontext".to_string(),
154                    vals: vec![basedn.as_bytes().to_vec()],
155                },
156            ],
157        };
158
159        Ok(LdapServer {
160            rootdse,
161            basedn,
162            dnre,
163            binddnre,
164            max_queryable_attrs,
165        })
166    }
167
168    #[instrument(level = "debug", skip_all)]
169    async fn do_search(
170        &self,
171        idms: &IdmServer,
172        sr: &SearchRequest,
173        uat: &LdapBoundToken,
174        source: Source,
175        // eventid: &Uuid,
176    ) -> Result<Vec<LdapMsg>, OperationError> {
177        admin_info!("Attempt LDAP Search for {}", uat.spn);
178        // If the request is "", Base, Present(Attribute::ObjectClass.into()), [], then we want the rootdse.
179        if sr.base.is_empty() && sr.scope == LdapSearchScope::Base {
180            admin_info!("LDAP Search success - RootDSE");
181            Ok(vec![
182                sr.gen_result_entry(self.rootdse.clone()),
183                sr.gen_success(),
184            ])
185        } else {
186            // We want something else apparently. Need to do some more work ...
187            // Parse the operation and make sure it's sane before we start the txn.
188
189            // This scoping returns an extra filter component.
190
191            let (opt_attr, opt_value) = match self.dnre.captures(sr.base.as_str()) {
192                Some(caps) => (
193                    caps.name("attr").map(|v| v.as_str().to_string()),
194                    caps.name("val").map(|v| v.as_str().to_string()),
195                ),
196                None => {
197                    request_error!("LDAP Search failure - invalid basedn");
198                    return Err(OperationError::InvalidRequestState);
199                }
200            };
201
202            let req_dn = match (opt_attr, opt_value) {
203                (Some(a), Some(v)) => Some((a, v)),
204                (None, None) => None,
205                _ => {
206                    request_error!("LDAP Search failure - invalid rdn");
207                    return Err(OperationError::InvalidRequestState);
208                }
209            };
210
211            trace!(rdn = ?req_dn);
212
213            // Map the Some(a,v) to ...?
214
215            let ext_filter = match (&sr.scope, req_dn) {
216                // OneLevel and Child searches are **very** similar for us because child
217                // is a "subtree search excluding base". Because we don't have a tree structure at
218                // all, this is the same as a one level (all children of base excluding base).
219                (LdapSearchScope::Children, Some(_r)) | (LdapSearchScope::OneLevel, Some(_r)) => {
220                    return Ok(vec![sr.gen_success()])
221                }
222                (LdapSearchScope::Children, None) | (LdapSearchScope::OneLevel, None) => {
223                    // exclude domain_info
224                    Some(LdapFilter::Not(Box::new(LdapFilter::Equality(
225                        Attribute::Uuid.to_string(),
226                        STR_UUID_DOMAIN_INFO.to_string(),
227                    ))))
228                }
229                // because we request a specific DN, these are the same since we want the same
230                // entry.
231                (LdapSearchScope::Base, Some((a, v)))
232                | (LdapSearchScope::Subtree, Some((a, v))) => Some(LdapFilter::Equality(a, v)),
233                (LdapSearchScope::Base, None) => {
234                    // domain_info
235                    Some(LdapFilter::Equality(
236                        Attribute::Uuid.to_string(),
237                        STR_UUID_DOMAIN_INFO.to_string(),
238                    ))
239                }
240                (LdapSearchScope::Subtree, None) => {
241                    // No filter changes needed.
242                    None
243                }
244            };
245
246            let mut no_attrs = false;
247            let mut all_attrs = false;
248            let mut all_op_attrs = false;
249
250            let attrs_len = sr.attrs.len();
251            if sr.attrs.is_empty() {
252                // If [], then "all" attrs
253                all_attrs = true;
254            } else if attrs_len < self.max_queryable_attrs {
255                sr.attrs.iter().for_each(|a| {
256                    if a == "*" {
257                        all_attrs = true;
258                    } else if a == "+" {
259                        // This forces the BE to get all the attrs so we can
260                        // map all vattrs.
261                        all_attrs = true;
262                        all_op_attrs = true;
263                    } else if a == "1.1" {
264                        /*
265                         *  ref https://www.rfc-editor.org/rfc/rfc4511#section-4.5.1.8
266                         *
267                         *  A list containing only the OID "1.1" indicates that no
268                         *  attributes are to be returned. If "1.1" is provided with other
269                         *  attributeSelector values, the "1.1" attributeSelector is
270                         *  ignored. This OID was chosen because it does not (and can not)
271                         *  correspond to any attribute in use.
272                         */
273                        if sr.attrs.len() == 1 {
274                            no_attrs = true;
275                        }
276                    }
277                })
278            } else {
279                admin_error!(
280                    "Too many LDAP attributes requested. Maximum allowed is {}, while your search query had {}",
281                    self.max_queryable_attrs, attrs_len
282                );
283                return Err(OperationError::ResourceLimit);
284            }
285
286            // We need to retain this to know what the client requested.
287            let (k_attrs, l_attrs) = if no_attrs {
288                // Request no attributes and no mapped attributes.
289                (None, Vec::with_capacity(0))
290            } else if all_op_attrs {
291                // We need all attrs, and we do a full v_attr map.
292                (None, ldap_all_vattrs())
293            } else if all_attrs {
294                // We are already getting all attrs, but if there are any virtual attrs
295                // we need them in our request as well.
296                let req_attrs: Vec<String> = sr
297                    .attrs
298                    .iter()
299                    .filter_map(|a| {
300                        let a_lower = a.to_lowercase();
301
302                        if ldap_vattr_map(&a_lower).is_some() {
303                            Some(a_lower)
304                        } else {
305                            None
306                        }
307                    })
308                    .collect();
309
310                (None, req_attrs)
311            } else {
312                // What the client requested, in LDAP forms.
313                let req_attrs: Vec<String> = sr
314                    .attrs
315                    .iter()
316                    .filter_map(|a| {
317                        if a == "*" || a == "+" || a == "1.1" {
318                            None
319                        } else {
320                            Some(a.to_lowercase())
321                        }
322                    })
323                    .collect();
324                // This is what the client requested, but mapped to kanidm forms.
325                // NOTE: All req_attrs are lowercase at this point.
326                let mapped_attrs: BTreeSet<_> = req_attrs
327                    .iter()
328                    .map(|a| Attribute::from(ldap_vattr_map(a).unwrap_or(a)))
329                    .collect();
330
331                (Some(mapped_attrs), req_attrs)
332            };
333
334            admin_info!(attr = ?l_attrs, "LDAP Search Request LDAP Attrs");
335            admin_info!(attr = ?k_attrs, "LDAP Search Request Mapped Attrs");
336
337            let ct = duration_from_epoch_now();
338            let mut idm_read = idms.proxy_read().await?;
339            // Now start the txn - we need it for resolving filter components.
340
341            // join the filter, with ext_filter
342            let lfilter = match ext_filter {
343                Some(ext) => LdapFilter::And(vec![
344                    sr.filter.clone(),
345                    ext,
346                    LdapFilter::Not(Box::new(LdapFilter::Or(vec![
347                        LdapFilter::Equality(Attribute::Class.to_string(), "classtype".to_string()),
348                        LdapFilter::Equality(
349                            Attribute::Class.to_string(),
350                            "attributetype".to_string(),
351                        ),
352                        LdapFilter::Equality(
353                            Attribute::Class.to_string(),
354                            "access_control_profile".to_string(),
355                        ),
356                    ]))),
357                ]),
358                None => LdapFilter::And(vec![
359                    sr.filter.clone(),
360                    LdapFilter::Not(Box::new(LdapFilter::Or(vec![
361                        LdapFilter::Equality(Attribute::Class.to_string(), "classtype".to_string()),
362                        LdapFilter::Equality(
363                            Attribute::Class.to_string(),
364                            "attributetype".to_string(),
365                        ),
366                        LdapFilter::Equality(
367                            Attribute::Class.to_string(),
368                            "access_control_profile".to_string(),
369                        ),
370                    ]))),
371                ]),
372            };
373
374            admin_info!(filter = ?lfilter, "LDAP Search Filter");
375
376            // Build the event, with the permissions from effective_session
377            //
378            // ! Remember, searchEvent wraps to ignore hidden for us.
379            let ident = idm_read
380                .validate_ldap_session(&uat.effective_session, source, ct)
381                .map_err(|e| {
382                    admin_error!("Invalid identity: {:?}", e);
383                    e
384                })?;
385            let se = SearchEvent::new_ext_impersonate_uuid(
386                &mut idm_read.qs_read,
387                ident,
388                &lfilter,
389                k_attrs,
390            )
391            .map_err(|e| {
392                admin_error!("failed to create search event -> {:?}", e);
393                e
394            })?;
395
396            let res = idm_read.qs_read.search_ext(&se).map_err(|e| {
397                admin_error!("search failure {:?}", e);
398                e
399            })?;
400
401            // These have already been fully reduced (access controls applied),
402            // so we can just transform the values and open palm slam them into
403            // the result structure.
404            let lres: Result<Vec<_>, _> = res
405                .into_iter()
406                .map(|e| {
407                    e.to_ldap(
408                        &mut idm_read.qs_read,
409                        self.basedn.as_str(),
410                        all_attrs,
411                        &l_attrs,
412                    )
413                    // if okay, wrap in a ldap msg.
414                    .map(|r| sr.gen_result_entry(r))
415                })
416                .chain(iter::once(Ok(sr.gen_success())))
417                .collect();
418
419            let lres = lres.map_err(|e| {
420                admin_error!("entry resolve failure {:?}", e);
421                e
422            })?;
423
424            admin_info!(
425                nentries = %lres.len(),
426                "LDAP Search Success -> number of entries"
427            );
428
429            Ok(lres)
430        }
431    }
432
433    async fn do_bind(
434        &self,
435        idms: &IdmServer,
436        dn: &str,
437        pw: &str,
438    ) -> Result<Option<LdapBoundToken>, OperationError> {
439        security_info!(
440            "Attempt LDAP Bind for {}",
441            if dn.is_empty() { "(empty dn)" } else { dn }
442        );
443        let ct = duration_from_epoch_now();
444
445        let mut idm_auth = idms.auth().await?;
446        let target = self.bind_target_from_bind_dn(&mut idm_auth, dn, pw).await?;
447
448        let result = match target {
449            LdapBindTarget::Account(uuid) => {
450                let lae = LdapAuthEvent::from_parts(uuid, pw.to_string())?;
451                idm_auth.auth_ldap(&lae, ct).await?
452            }
453            LdapBindTarget::ApiToken => {
454                let jwsc = JwsCompact::from_str(pw).map_err(|err| {
455                    error!(?err, "Invalid JwsCompact supplied as authentication token.");
456                    OperationError::NotAuthenticated
457                })?;
458
459                let lae = LdapTokenAuthEvent::from_parts(jwsc)?;
460                idm_auth.token_auth_ldap(&lae, ct).await?
461            }
462            LdapBindTarget::Application(ref app_name, usr_uuid) => {
463                let lae =
464                    LdapApplicationAuthEvent::new(app_name.as_str(), usr_uuid, pw.to_string())?;
465                idm_auth.application_auth_ldap(&lae, ct).await?
466            }
467        };
468
469        idm_auth.commit()?;
470
471        if result.is_some() {
472            security_info!(
473                "✅ LDAP Bind success for {} -> {:?}",
474                if dn.is_empty() { "(empty dn)" } else { dn },
475                target
476            );
477        } else {
478            security_info!(
479                "❌ LDAP Bind failure for {} -> {:?}",
480                if dn.is_empty() { "(empty dn)" } else { dn },
481                target
482            );
483        }
484
485        Ok(result)
486    }
487
488    #[instrument(level = "debug", skip_all)]
489    async fn do_compare(
490        &self,
491        idms: &IdmServer,
492        cr: &CompareRequest,
493        uat: &LdapBoundToken,
494        source: Source,
495    ) -> Result<Vec<LdapMsg>, OperationError> {
496        admin_info!("Attempt LDAP CompareRequest for {}", uat.spn);
497
498        let (opt_attr, opt_value) = match self.dnre.captures(cr.entry.as_str()) {
499            Some(caps) => (
500                caps.name("attr").map(|v| v.as_str().to_string()),
501                caps.name("val").map(|v| v.as_str().to_string()),
502            ),
503            None => {
504                request_error!("LDAP Search failure - invalid basedn");
505                return Err(OperationError::InvalidRequestState);
506            }
507        };
508
509        let ext_filter = match (opt_attr, opt_value) {
510            (Some(a), Some(v)) => LdapFilter::Equality(a, v),
511            _ => {
512                request_error!("LDAP Search failure - invalid rdn");
513                return Err(OperationError::InvalidRequestState);
514            }
515        };
516
517        let ct = duration_from_epoch_now();
518        let mut idm_read = idms.proxy_read().await?;
519        // Now start the txn - we need it for resolving filter components.
520
521        // join the filter, with ext_filter
522        let lfilter = LdapFilter::And(vec![
523            ext_filter.clone(),
524            LdapFilter::Equality(cr.atype.clone(), cr.val.clone()),
525            LdapFilter::Not(Box::new(LdapFilter::Or(vec![
526                LdapFilter::Equality(Attribute::Class.to_string(), "classtype".to_string()),
527                LdapFilter::Equality(Attribute::Class.to_string(), "attributetype".to_string()),
528                LdapFilter::Equality(
529                    Attribute::Class.to_string(),
530                    "access_control_profile".to_string(),
531                ),
532            ]))),
533        ]);
534
535        admin_info!(filter = ?lfilter, "LDAP Compare Filter");
536
537        // Build the event, with the permissions from effective_session
538        let ident = idm_read
539            .validate_ldap_session(&uat.effective_session, source, ct)
540            .map_err(|e| {
541                admin_error!("Invalid identity: {:?}", e);
542                e
543            })?;
544
545        let f = Filter::from_ldap_ro(&ident, &lfilter, &mut idm_read.qs_read)?;
546        let filter_orig = f
547            .validate(idm_read.qs_read.get_schema())
548            .map_err(OperationError::SchemaViolation)?;
549        let filter = filter_orig.clone().into_ignore_hidden();
550
551        let ee = ExistsEvent {
552            ident: ident.clone(),
553            filter,
554            filter_orig,
555        };
556
557        let res = idm_read.qs_read.exists(&ee).map_err(|e| {
558            admin_error!("call to exists failure {:?}", e);
559            e
560        })?;
561
562        if res {
563            admin_info!("LDAP Compare -> True");
564            return Ok(vec![cr.gen_compare_true()]);
565        }
566
567        // we need to check if the entry exists at all (without the ava).
568        let lfilter = LdapFilter::And(vec![
569            ext_filter,
570            LdapFilter::Not(Box::new(LdapFilter::Or(vec![
571                LdapFilter::Equality(Attribute::Class.to_string(), "classtype".to_string()),
572                LdapFilter::Equality(Attribute::Class.to_string(), "attributetype".to_string()),
573                LdapFilter::Equality(
574                    Attribute::Class.to_string(),
575                    "access_control_profile".to_string(),
576                ),
577            ]))),
578        ]);
579        let f = Filter::from_ldap_ro(&ident, &lfilter, &mut idm_read.qs_read)?;
580        let filter_orig = f
581            .validate(idm_read.qs_read.get_schema())
582            .map_err(OperationError::SchemaViolation)?;
583        let filter = filter_orig.clone().into_ignore_hidden();
584        let ee = ExistsEvent {
585            ident,
586            filter,
587            filter_orig,
588        };
589
590        let res = idm_read.qs_read.exists(&ee).map_err(|e| {
591            admin_error!("call to exists failure {:?}", e);
592            e
593        })?;
594
595        if res {
596            admin_info!("LDAP Compare -> False");
597            return Ok(vec![cr.gen_compare_false()]);
598        }
599
600        Ok(vec![
601            cr.gen_error(LdapResultCode::NoSuchObject, "".to_string())
602        ])
603    }
604
605    pub async fn do_op(
606        &self,
607        idms: &IdmServer,
608        server_op: ServerOps,
609        uat: Option<LdapBoundToken>,
610        ip_addr: IpAddr,
611        eventid: Uuid,
612    ) -> Result<LdapResponseState, OperationError> {
613        let source = Source::Ldaps(ip_addr);
614
615        match server_op {
616            ServerOps::SimpleBind(sbr) => self
617                .do_bind(idms, sbr.dn.as_str(), sbr.pw.as_str())
618                .await
619                .map(|r| match r {
620                    Some(lbt) => LdapResponseState::Bind(lbt, sbr.gen_success()),
621                    None => LdapResponseState::Respond(sbr.gen_invalid_cred()),
622                })
623                .or_else(|e| {
624                    let (rc, msg) = operationerr_to_ldapresultcode(e);
625                    Ok(LdapResponseState::Respond(sbr.gen_error(rc, msg)))
626                }),
627            ServerOps::Search(sr) => match uat {
628                Some(u) => self
629                    .do_search(idms, &sr, &u, source)
630                    .await
631                    .map(LdapResponseState::MultiPartResponse)
632                    .or_else(|e| {
633                        let (rc, msg) = operationerr_to_ldapresultcode(e);
634                        Ok(LdapResponseState::Respond(sr.gen_error(rc, msg)))
635                    }),
636                None => {
637                    // Search can occur without a bind, so bind first.
638                    // This is per section 4 of RFC 4513 (https://www.rfc-editor.org/rfc/rfc4513#section-4).
639                    let lbt = match self.do_bind(idms, "", "").await {
640                        Ok(Some(lbt)) => lbt,
641                        Ok(None) => {
642                            return Ok(LdapResponseState::Respond(
643                                sr.gen_error(LdapResultCode::InvalidCredentials, "".to_string()),
644                            ))
645                        }
646                        Err(e) => {
647                            let (rc, msg) = operationerr_to_ldapresultcode(e);
648                            return Ok(LdapResponseState::Respond(sr.gen_error(rc, msg)));
649                        }
650                    };
651                    // If okay, do the search.
652                    self.do_search(idms, &sr, &lbt, Source::Internal)
653                        .await
654                        .map(|r| LdapResponseState::BindMultiPartResponse(lbt, r))
655                        .or_else(|e| {
656                            let (rc, msg) = operationerr_to_ldapresultcode(e);
657                            Ok(LdapResponseState::Respond(sr.gen_error(rc, msg)))
658                        })
659                }
660            },
661            ServerOps::Unbind(_) => {
662                // No need to notify on unbind (per rfc4511)
663                Ok(LdapResponseState::Unbind)
664            }
665            ServerOps::Compare(cr) => match uat {
666                Some(u) => self
667                    .do_compare(idms, &cr, &u, source)
668                    .await
669                    .map(LdapResponseState::MultiPartResponse)
670                    .or_else(|e| {
671                        let (rc, msg) = operationerr_to_ldapresultcode(e);
672                        Ok(LdapResponseState::Respond(cr.gen_error(rc, msg)))
673                    }),
674                None => {
675                    // Compare can occur without a bind, so bind first.
676                    // This is per section 4 of RFC 4513 (https://www.rfc-editor.org/rfc/rfc4513#section-4).
677                    let lbt = match self.do_bind(idms, "", "").await {
678                        Ok(Some(lbt)) => lbt,
679                        Ok(None) => {
680                            return Ok(LdapResponseState::Respond(
681                                cr.gen_error(LdapResultCode::InvalidCredentials, "".to_string()),
682                            ))
683                        }
684                        Err(e) => {
685                            let (rc, msg) = operationerr_to_ldapresultcode(e);
686                            return Ok(LdapResponseState::Respond(cr.gen_error(rc, msg)));
687                        }
688                    };
689                    // If okay, do the compare.
690                    self.do_compare(idms, &cr, &lbt, Source::Internal)
691                        .await
692                        .map(|r| LdapResponseState::BindMultiPartResponse(lbt, r))
693                        .or_else(|e| {
694                            let (rc, msg) = operationerr_to_ldapresultcode(e);
695                            Ok(LdapResponseState::Respond(cr.gen_error(rc, msg)))
696                        })
697                }
698            },
699            ServerOps::Whoami(wr) => match uat {
700                Some(u) => Ok(LdapResponseState::Respond(
701                    wr.gen_success(format!("u: {}", u.spn).as_str()),
702                )),
703                None => Ok(LdapResponseState::Respond(
704                    wr.gen_operror(format!("Unbound Connection {eventid}").as_str()),
705                )),
706            },
707        } // end match server op
708    }
709
710    async fn bind_target_from_bind_dn(
711        &self,
712        idm_auth: &mut IdmServerAuthTransaction<'_>,
713        dn: &str,
714        pw: &str,
715    ) -> Result<LdapBindTarget, OperationError> {
716        if dn.is_empty() {
717            if pw.is_empty() {
718                return Ok(LdapBindTarget::Account(UUID_ANONYMOUS));
719            } else {
720                // This is the path to access api-token logins.
721                return Ok(LdapBindTarget::ApiToken);
722            }
723        } else if dn == "dn=token" {
724            // Is the passed dn requesting token auth?
725            // We use dn= here since these are attr=value, and dn is a phantom so it will
726            // never be present or match a real value. We also make it an ava so that clients
727            // that over-zealously validate dn syntax are happy.
728            return Ok(LdapBindTarget::ApiToken);
729        }
730
731        if let Some(captures) = self.binddnre.captures(dn) {
732            if let Some(usr) = captures.name("val") {
733                let usr = usr.as_str();
734
735                if usr.is_empty() {
736                    error!("Failed to parse user name from bind DN, it is empty (capture group is {:#?})", captures.name("val"));
737                    return Err(OperationError::NoMatchingEntries);
738                }
739
740                let usr_uuid = idm_auth.qs_read.name_to_uuid(usr).map_err(|e| {
741                    error!(err = ?e, ?usr, "Error resolving rdn to target");
742                    e
743                })?;
744
745                if let Some(app) = captures.name("app") {
746                    let app = app.as_str();
747
748                    if app.is_empty() {
749                        error!("Failed to parse application name from bind DN, it is empty (capture group is {:#?})", captures.name("app"));
750                        return Err(OperationError::NoMatchingEntries);
751                    }
752
753                    return Ok(LdapBindTarget::Application(app.to_string(), usr_uuid));
754                }
755
756                return Ok(LdapBindTarget::Account(usr_uuid));
757            }
758        }
759
760        error!(
761            binddn = ?dn,
762            "Failed to parse bind DN - check the basedn and app attribute if present are correct. Examples: name=tobias,app=lounge,{} OR name=ellie,{} OR name=claire,app=table OR name=william ", self.basedn, self.basedn
763        );
764
765        Err(OperationError::NoMatchingEntries)
766    }
767}
768
769fn ldap_domain_to_dc(input: &str) -> String {
770    let mut output: String = String::new();
771    input.split('.').for_each(|dc| {
772        output.push_str("dc=");
773        output.push_str(dc);
774        #[allow(clippy::single_char_pattern, clippy::single_char_add_str)]
775        output.push_str(",");
776    });
777    // Remove the last ','
778    output.pop();
779    output
780}
781
782fn operationerr_to_ldapresultcode(e: OperationError) -> (LdapResultCode, String) {
783    match e {
784        OperationError::InvalidRequestState => {
785            (LdapResultCode::ConstraintViolation, "".to_string())
786        }
787        OperationError::InvalidAttributeName(s) | OperationError::InvalidAttribute(s) => {
788            (LdapResultCode::InvalidAttributeSyntax, s)
789        }
790        OperationError::SchemaViolation(se) => {
791            (LdapResultCode::UnwillingToPerform, format!("{se:?}"))
792        }
793        e => (LdapResultCode::Other, format!("{e:?}")),
794    }
795}
796
797#[inline]
798pub(crate) fn ldap_all_vattrs() -> Vec<String> {
799    vec![
800        ATTR_CN.to_string(),
801        ATTR_EMAIL.to_string(),
802        ATTR_LDAP_EMAIL_ADDRESS.to_string(),
803        LDAP_ATTR_DN.to_string(),
804        LDAP_ATTR_EMAIL_ALTERNATIVE.to_string(),
805        LDAP_ATTR_EMAIL_PRIMARY.to_string(),
806        LDAP_ATTR_ENTRYDN.to_string(),
807        LDAP_ATTR_ENTRYUUID.to_string(),
808        LDAP_ATTR_KEYS.to_string(),
809        LDAP_ATTR_MAIL_ALTERNATIVE.to_string(),
810        LDAP_ATTR_MAIL_PRIMARY.to_string(),
811        ATTR_OBJECTCLASS.to_string(),
812        ATTR_LDAP_SSHPUBLICKEY.to_string(),
813        ATTR_UIDNUMBER.to_string(),
814        ATTR_UID.to_string(),
815        ATTR_GECOS.to_string(),
816    ]
817}
818
819#[inline]
820pub(crate) fn ldap_vattr_map(input: &str) -> Option<&str> {
821    // ⚠️  WARNING ⚠️
822    // If you modify this list you MUST add these values to
823    // corresponding phantom attributes in the schema to prevent
824    // incorrect future or duplicate usage.
825    //
826    //   LDAP NAME     KANI ATTR SOURCE NAME
827    match input {
828        // EntryDN and DN have special handling in to_ldap in Entry. However, we
829        // need to map them to "name" so that if the user has requested dn/entrydn
830        // only, then we still requested at least one attribute from the backend
831        // allowing the access control tests to take place. Otherwise no entries
832        // would be returned.
833        ATTR_CN | ATTR_UID | LDAP_ATTR_ENTRYDN | LDAP_ATTR_DN => Some(ATTR_NAME),
834        ATTR_GECOS => Some(ATTR_DISPLAYNAME),
835        ATTR_EMAIL => Some(ATTR_MAIL),
836        ATTR_LDAP_EMAIL_ADDRESS => Some(ATTR_MAIL),
837        LDAP_ATTR_EMAIL_ALTERNATIVE => Some(ATTR_MAIL),
838        LDAP_ATTR_EMAIL_PRIMARY => Some(ATTR_MAIL),
839        LDAP_ATTR_ENTRYUUID => Some(ATTR_UUID),
840        LDAP_ATTR_KEYS => Some(ATTR_SSH_PUBLICKEY),
841        LDAP_ATTR_MAIL_ALTERNATIVE => Some(ATTR_MAIL),
842        LDAP_ATTR_MAIL_PRIMARY => Some(ATTR_MAIL),
843        ATTR_OBJECTCLASS => Some(ATTR_CLASS),
844        ATTR_LDAP_SSHPUBLICKEY => Some(ATTR_SSH_PUBLICKEY), // no-underscore -> underscore
845        ATTR_UIDNUMBER => Some(ATTR_GIDNUMBER),             // yes this is intentional
846        _ => None,
847    }
848}
849
850#[inline]
851pub(crate) fn ldap_attr_filter_map(input: &str) -> Attribute {
852    let a_lower = input.to_lowercase();
853    Attribute::from(ldap_vattr_map(&a_lower).unwrap_or(a_lower.as_str()))
854}
855
856#[cfg(test)]
857mod tests {
858    use crate::prelude::*;
859
860    use compact_jwt::{dangernoverify::JwsDangerReleaseWithoutVerify, JwsVerifier};
861    use hashbrown::HashSet;
862    use kanidm_proto::internal::ApiToken;
863    use ldap3_proto::proto::{
864        LdapFilter, LdapMsg, LdapOp, LdapResultCode, LdapSearchScope, LdapSubstringFilter,
865    };
866    use ldap3_proto::simple::*;
867
868    use super::{LdapServer, LdapSession};
869    use crate::idm::application::GenerateApplicationPasswordEvent;
870    use crate::idm::event::{LdapApplicationAuthEvent, UnixPasswordChangeEvent};
871    use crate::idm::serviceaccount::GenerateApiTokenEvent;
872
873    const TEST_PASSWORD: &str = "ntaoeuntnaoeuhraohuercahu😍";
874
875    #[idm_test]
876    async fn test_ldap_simple_bind(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
877        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
878
879        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
880        // make the admin a valid posix account
881        let me_posix = ModifyEvent::new_internal_invalid(
882            filter!(f_eq(Attribute::Name, PartialValue::new_iname("admin"))),
883            ModifyList::new_list(vec![
884                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
885                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
886            ]),
887        );
888        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
889
890        let pce = UnixPasswordChangeEvent::new_internal(UUID_ADMIN, TEST_PASSWORD);
891
892        assert!(idms_prox_write.set_unix_account_password(&pce).is_ok());
893        assert!(idms_prox_write.commit().is_ok()); // Committing all configs
894
895        // default UNIX_PW bind (default is set to true)
896        // Hence allows all unix binds
897        let admin_t = ldaps
898            .do_bind(idms, "admin", TEST_PASSWORD)
899            .await
900            .unwrap()
901            .unwrap();
902        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
903        let admin_t = ldaps
904            .do_bind(idms, "admin@example.com", TEST_PASSWORD)
905            .await
906            .unwrap()
907            .unwrap();
908        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
909
910        // Setting UNIX_PW_BIND flag to false:
911        // Hence all of the below authentication will fail (asserts are still satisfied)
912        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
913        let disallow_unix_pw_flag = ModifyEvent::new_internal_invalid(
914            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_DOMAIN_INFO))),
915            ModifyList::new_purge_and_set(Attribute::LdapAllowUnixPwBind, Value::Bool(false)),
916        );
917        assert!(idms_prox_write
918            .qs_write
919            .modify(&disallow_unix_pw_flag)
920            .is_ok());
921        assert!(idms_prox_write.commit().is_ok());
922        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
923        assert_eq!(
924            anon_t.effective_session,
925            LdapSession::UnixBind(UUID_ANONYMOUS)
926        );
927        assert!(
928            ldaps.do_bind(idms, "", "test").await.unwrap_err() == OperationError::NotAuthenticated
929        );
930        let admin_t = ldaps.do_bind(idms, "admin", TEST_PASSWORD).await.unwrap();
931        assert!(admin_t.is_none());
932
933        // Setting UNIX_PW_BIND flag to true :
934        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
935        let allow_unix_pw_flag = ModifyEvent::new_internal_invalid(
936            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_DOMAIN_INFO))),
937            ModifyList::new_purge_and_set(Attribute::LdapAllowUnixPwBind, Value::Bool(true)),
938        );
939        assert!(idms_prox_write.qs_write.modify(&allow_unix_pw_flag).is_ok());
940        assert!(idms_prox_write.commit().is_ok());
941
942        // Now test the admin and various DN's
943        let admin_t = ldaps
944            .do_bind(idms, "admin", TEST_PASSWORD)
945            .await
946            .unwrap()
947            .unwrap();
948        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
949        let admin_t = ldaps
950            .do_bind(idms, "admin@example.com", TEST_PASSWORD)
951            .await
952            .unwrap()
953            .unwrap();
954        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
955        let admin_t = ldaps
956            .do_bind(idms, STR_UUID_ADMIN, TEST_PASSWORD)
957            .await
958            .unwrap()
959            .unwrap();
960        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
961        let admin_t = ldaps
962            .do_bind(idms, "name=admin,dc=example,dc=com", TEST_PASSWORD)
963            .await
964            .unwrap()
965            .unwrap();
966        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
967        let admin_t = ldaps
968            .do_bind(
969                idms,
970                "spn=admin@example.com,dc=example,dc=com",
971                TEST_PASSWORD,
972            )
973            .await
974            .unwrap()
975            .unwrap();
976        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
977        let admin_t = ldaps
978            .do_bind(
979                idms,
980                format!("uuid={STR_UUID_ADMIN},dc=example,dc=com").as_str(),
981                TEST_PASSWORD,
982            )
983            .await
984            .unwrap()
985            .unwrap();
986        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
987
988        let admin_t = ldaps
989            .do_bind(idms, "name=admin", TEST_PASSWORD)
990            .await
991            .unwrap()
992            .unwrap();
993        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
994        let admin_t = ldaps
995            .do_bind(idms, "spn=admin@example.com", TEST_PASSWORD)
996            .await
997            .unwrap()
998            .unwrap();
999        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
1000        let admin_t = ldaps
1001            .do_bind(
1002                idms,
1003                format!("uuid={STR_UUID_ADMIN}").as_str(),
1004                TEST_PASSWORD,
1005            )
1006            .await
1007            .unwrap()
1008            .unwrap();
1009        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
1010
1011        let admin_t = ldaps
1012            .do_bind(idms, "admin,dc=example,dc=com", TEST_PASSWORD)
1013            .await
1014            .unwrap()
1015            .unwrap();
1016        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
1017        let admin_t = ldaps
1018            .do_bind(idms, "admin@example.com,dc=example,dc=com", TEST_PASSWORD)
1019            .await
1020            .unwrap()
1021            .unwrap();
1022        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
1023        let admin_t = ldaps
1024            .do_bind(
1025                idms,
1026                format!("{STR_UUID_ADMIN},dc=example,dc=com").as_str(),
1027                TEST_PASSWORD,
1028            )
1029            .await
1030            .unwrap()
1031            .unwrap();
1032        assert_eq!(admin_t.effective_session, LdapSession::UnixBind(UUID_ADMIN));
1033
1034        // Bad password, check last to prevent softlocking of the admin account.
1035        assert!(ldaps
1036            .do_bind(idms, "admin", "test")
1037            .await
1038            .unwrap()
1039            .is_none());
1040
1041        // Non-existent and invalid DNs
1042        assert!(ldaps
1043            .do_bind(
1044                idms,
1045                "spn=admin@example.com,dc=clownshoes,dc=example,dc=com",
1046                TEST_PASSWORD
1047            )
1048            .await
1049            .is_err());
1050        assert!(ldaps
1051            .do_bind(
1052                idms,
1053                "spn=claire@example.com,dc=example,dc=com",
1054                TEST_PASSWORD
1055            )
1056            .await
1057            .is_err());
1058        assert!(ldaps
1059            .do_bind(idms, ",dc=example,dc=com", TEST_PASSWORD)
1060            .await
1061            .is_err());
1062        assert!(ldaps
1063            .do_bind(idms, "dc=example,dc=com", TEST_PASSWORD)
1064            .await
1065            .is_err());
1066
1067        assert!(ldaps.do_bind(idms, "claire", "test").await.is_err());
1068    }
1069
1070    #[idm_test]
1071    async fn test_ldap_application_dnre(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
1072        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1073
1074        let testdn = format!("app=app1,{0}", ldaps.basedn);
1075        let captures = ldaps.dnre.captures(testdn.as_str()).unwrap();
1076        assert!(captures.name("app").is_some());
1077        assert!(captures.name("attr").is_none());
1078        assert!(captures.name("val").is_none());
1079
1080        let testdn = format!("uid=foo,app=app1,{0}", ldaps.basedn);
1081        let captures = ldaps.dnre.captures(testdn.as_str()).unwrap();
1082        assert!(captures.name("app").is_some());
1083        assert!(captures.name("attr").is_some());
1084        assert!(captures.name("val").is_some());
1085
1086        let testdn = format!("uid=foo,{0}", ldaps.basedn);
1087        let captures = ldaps.dnre.captures(testdn.as_str()).unwrap();
1088        assert!(captures.name("app").is_none());
1089        assert!(captures.name("attr").is_some());
1090        assert!(captures.name("val").is_some());
1091    }
1092
1093    #[idm_test]
1094    async fn test_ldap_application_search(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
1095        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1096
1097        let usr_uuid = Uuid::new_v4();
1098        let grp_uuid = Uuid::new_v4();
1099        let app_uuid = Uuid::new_v4();
1100        let app_name = "testapp1";
1101
1102        // Setup person, group and application
1103        {
1104            let e1 = entry_init!(
1105                (Attribute::Class, EntryClass::Object.to_value()),
1106                (Attribute::Class, EntryClass::Account.to_value()),
1107                (Attribute::Class, EntryClass::Person.to_value()),
1108                (Attribute::Name, Value::new_iname("testperson1")),
1109                (Attribute::Uuid, Value::Uuid(usr_uuid)),
1110                (Attribute::Description, Value::new_utf8s("testperson1")),
1111                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
1112            );
1113
1114            let e2 = entry_init!(
1115                (Attribute::Class, EntryClass::Object.to_value()),
1116                (Attribute::Class, EntryClass::Group.to_value()),
1117                (Attribute::Name, Value::new_iname("testgroup1")),
1118                (Attribute::Uuid, Value::Uuid(grp_uuid))
1119            );
1120
1121            let e3 = entry_init!(
1122                (Attribute::Class, EntryClass::Object.to_value()),
1123                (Attribute::Class, EntryClass::Account.to_value()),
1124                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1125                (Attribute::Class, EntryClass::Application.to_value()),
1126                (Attribute::DisplayName, Value::new_utf8s("Application")),
1127                (Attribute::Name, Value::new_iname(app_name)),
1128                (Attribute::Uuid, Value::Uuid(app_uuid)),
1129                (Attribute::LinkedGroup, Value::Refer(grp_uuid))
1130            );
1131
1132            let ct = duration_from_epoch_now();
1133            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1134            assert!(server_txn
1135                .qs_write
1136                .internal_create(vec![e1, e2, e3])
1137                .and_then(|_| server_txn.commit())
1138                .is_ok());
1139        }
1140
1141        // Setup the anonymous login
1142        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
1143        assert_eq!(
1144            anon_t.effective_session,
1145            LdapSession::UnixBind(UUID_ANONYMOUS)
1146        );
1147
1148        // Searches under application base DN must show same content
1149        let sr = SearchRequest {
1150            msgid: 1,
1151            base: format!("app={app_name},dc=example,dc=com"),
1152            scope: LdapSearchScope::Subtree,
1153            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
1154            attrs: vec!["*".to_string()],
1155        };
1156
1157        let r1 = ldaps
1158            .do_search(idms, &sr, &anon_t, Source::Internal)
1159            .await
1160            .unwrap();
1161
1162        let sr = SearchRequest {
1163            msgid: 1,
1164            base: "dc=example,dc=com".to_string(),
1165            scope: LdapSearchScope::Subtree,
1166            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
1167            attrs: vec!["*".to_string()],
1168        };
1169
1170        let r2 = ldaps
1171            .do_search(idms, &sr, &anon_t, Source::Internal)
1172            .await
1173            .unwrap();
1174        assert!(!r1.is_empty());
1175        assert_eq!(r1.len(), r2.len());
1176    }
1177
1178    #[idm_test]
1179    async fn test_ldap_spn_search(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
1180        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1181
1182        let usr_uuid = Uuid::new_v4();
1183        let usr_name = "panko";
1184
1185        // Setup person, group and application
1186        {
1187            let e1: Entry<EntryInit, EntryNew> = entry_init!(
1188                (Attribute::Class, EntryClass::Object.to_value()),
1189                (Attribute::Class, EntryClass::Account.to_value()),
1190                (Attribute::Class, EntryClass::Person.to_value()),
1191                (Attribute::Name, Value::new_iname(usr_name)),
1192                (Attribute::Uuid, Value::Uuid(usr_uuid)),
1193                (Attribute::DisplayName, Value::new_utf8s(usr_name))
1194            );
1195
1196            let ct = duration_from_epoch_now();
1197            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1198            assert!(server_txn
1199                .qs_write
1200                .internal_create(vec![e1])
1201                .and_then(|_| server_txn.commit())
1202                .is_ok());
1203        }
1204
1205        // Setup the anonymous login
1206        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
1207        assert_eq!(
1208            anon_t.effective_session,
1209            LdapSession::UnixBind(UUID_ANONYMOUS)
1210        );
1211
1212        // Searching a malformed spn shouldn't cause the query to fail
1213        let sr = SearchRequest {
1214            msgid: 1,
1215            base: "dc=example,dc=com".to_string(),
1216            scope: LdapSearchScope::Subtree,
1217            filter: LdapFilter::Or(vec![
1218                LdapFilter::Equality(Attribute::Name.to_string(), usr_name.to_string()),
1219                LdapFilter::Equality(Attribute::Spn.to_string(), usr_name.to_string()),
1220            ]),
1221            attrs: vec!["*".to_string()],
1222        };
1223
1224        let result = ldaps
1225            .do_search(idms, &sr, &anon_t, Source::Internal)
1226            .await
1227            .map(|r| {
1228                r.into_iter()
1229                    .filter(|r| matches!(r.op, LdapOp::SearchResultEntry(_)))
1230                    .collect::<Vec<_>>()
1231            })
1232            .unwrap();
1233
1234        assert!(!result.is_empty());
1235
1236        let sr = SearchRequest {
1237            msgid: 1,
1238            base: "dc=example,dc=com".to_string(),
1239            scope: LdapSearchScope::Subtree,
1240            filter: LdapFilter::And(vec![
1241                LdapFilter::Equality(Attribute::Name.to_string(), usr_name.to_string()),
1242                LdapFilter::Equality(Attribute::Spn.to_string(), usr_name.to_string()),
1243            ]),
1244            attrs: vec!["*".to_string()],
1245        };
1246
1247        let empty_result = ldaps
1248            .do_search(idms, &sr, &anon_t, Source::Internal)
1249            .await
1250            .map(|r| {
1251                r.into_iter()
1252                    .filter(|r| matches!(r.op, LdapOp::SearchResultEntry(_)))
1253                    .collect::<Vec<_>>()
1254            })
1255            .unwrap();
1256
1257        assert!(empty_result.is_empty());
1258    }
1259
1260    #[idm_test]
1261    async fn test_ldap_application_bind(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
1262        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1263
1264        let usr_uuid = Uuid::new_v4();
1265        let grp_uuid = Uuid::new_v4();
1266        let app_uuid = Uuid::new_v4();
1267
1268        // Setup person, group and application
1269        {
1270            let e1 = entry_init!(
1271                (Attribute::Class, EntryClass::Object.to_value()),
1272                (Attribute::Class, EntryClass::Account.to_value()),
1273                (Attribute::Class, EntryClass::Person.to_value()),
1274                (Attribute::Name, Value::new_iname("testperson1")),
1275                (Attribute::Uuid, Value::Uuid(usr_uuid)),
1276                (Attribute::Description, Value::new_utf8s("testperson1")),
1277                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
1278            );
1279
1280            let e2 = entry_init!(
1281                (Attribute::Class, EntryClass::Object.to_value()),
1282                (Attribute::Class, EntryClass::Group.to_value()),
1283                (Attribute::Name, Value::new_iname("testgroup1")),
1284                (Attribute::Uuid, Value::Uuid(grp_uuid))
1285            );
1286
1287            let e3 = entry_init!(
1288                (Attribute::Class, EntryClass::Object.to_value()),
1289                (Attribute::Class, EntryClass::Account.to_value()),
1290                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1291                (Attribute::Class, EntryClass::Application.to_value()),
1292                (Attribute::DisplayName, Value::new_utf8s("Application")),
1293                (Attribute::Name, Value::new_iname("testapp1")),
1294                (Attribute::Uuid, Value::Uuid(app_uuid)),
1295                (Attribute::LinkedGroup, Value::Refer(grp_uuid))
1296            );
1297
1298            let ct = duration_from_epoch_now();
1299            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1300            assert!(server_txn
1301                .qs_write
1302                .internal_create(vec![e1, e2, e3])
1303                .and_then(|_| server_txn.commit())
1304                .is_ok());
1305        }
1306
1307        // No session, user not member of linked group
1308        let res = ldaps
1309            .do_bind(idms, "spn=testperson1,app=testapp1,dc=example,dc=com", "")
1310            .await;
1311        assert!(res.is_ok());
1312        assert!(res.unwrap().is_none());
1313
1314        {
1315            let ml = ModifyList::new_append(Attribute::Member, Value::Refer(usr_uuid));
1316            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1317            assert!(idms_prox_write
1318                .qs_write
1319                .internal_modify_uuid(grp_uuid, &ml)
1320                .is_ok());
1321            assert!(idms_prox_write.commit().is_ok());
1322        }
1323
1324        // No session, user does not have app password for testapp1
1325        let res = ldaps
1326            .do_bind(idms, "spn=testperson1,app=testapp1,dc=example,dc=com", "")
1327            .await;
1328        assert!(res.is_ok());
1329        assert!(res.unwrap().is_none());
1330
1331        let pass1: String;
1332        let pass2: String;
1333        let pass3: String;
1334        {
1335            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1336
1337            let ev = GenerateApplicationPasswordEvent::new_internal(
1338                usr_uuid,
1339                app_uuid,
1340                "apppwd1".to_string(),
1341            );
1342            (pass1, _) = idms_prox_write
1343                .generate_application_password(&ev)
1344                .expect("Failed to generate application password");
1345
1346            let ev = GenerateApplicationPasswordEvent::new_internal(
1347                usr_uuid,
1348                app_uuid,
1349                "apppwd2".to_string(),
1350            );
1351            (pass2, _) = idms_prox_write
1352                .generate_application_password(&ev)
1353                .expect("Failed to generate application password");
1354
1355            assert!(idms_prox_write.commit().is_ok());
1356
1357            // Application password overwritten on duplicated label
1358            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1359            let ev = GenerateApplicationPasswordEvent::new_internal(
1360                usr_uuid,
1361                app_uuid,
1362                "apppwd2".to_string(),
1363            );
1364            (pass3, _) = idms_prox_write
1365                .generate_application_password(&ev)
1366                .expect("Failed to generate application password");
1367            assert!(idms_prox_write.commit().is_ok());
1368        }
1369
1370        // Got session, app password valid
1371        let res = ldaps
1372            .do_bind(
1373                idms,
1374                "spn=testperson1,app=testapp1,dc=example,dc=com",
1375                pass1.as_str(),
1376            )
1377            .await;
1378        assert!(res.is_ok());
1379        assert!(res.unwrap().is_some());
1380
1381        // No session, app password overwritten
1382        let res = ldaps
1383            .do_bind(
1384                idms,
1385                "spn=testperson1,app=testapp1,dc=example,dc=com",
1386                pass2.as_str(),
1387            )
1388            .await;
1389        assert!(res.is_ok());
1390        assert!(res.unwrap().is_none());
1391
1392        // Got session, app password overwritten
1393        let res = ldaps
1394            .do_bind(
1395                idms,
1396                "spn=testperson1,app=testapp1,dc=example,dc=com",
1397                pass3.as_str(),
1398            )
1399            .await;
1400        assert!(res.is_ok());
1401        assert!(res.unwrap().is_some());
1402
1403        // No session, invalid app password
1404        let res = ldaps
1405            .do_bind(
1406                idms,
1407                "spn=testperson1,app=testapp1,dc=example,dc=com",
1408                "FOO",
1409            )
1410            .await;
1411        assert!(res.is_ok());
1412        assert!(res.unwrap().is_none());
1413    }
1414
1415    #[idm_test]
1416    async fn test_ldap_application_linked_group(
1417        idms: &IdmServer,
1418        _idms_delayed: &IdmServerDelayed,
1419    ) {
1420        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1421
1422        let usr_uuid = Uuid::new_v4();
1423        let usr_name = "testuser1";
1424
1425        let grp1_uuid = Uuid::new_v4();
1426        let grp1_name = "testgroup1";
1427        let grp2_uuid = Uuid::new_v4();
1428        let grp2_name = "testgroup2";
1429
1430        let app1_uuid = Uuid::new_v4();
1431        let app1_name = "testapp1";
1432        let app2_uuid = Uuid::new_v4();
1433        let app2_name = "testapp2";
1434
1435        // Setup person, groups and applications
1436        {
1437            let e1 = entry_init!(
1438                (Attribute::Class, EntryClass::Object.to_value()),
1439                (Attribute::Class, EntryClass::Account.to_value()),
1440                (Attribute::Class, EntryClass::Person.to_value()),
1441                (Attribute::Name, Value::new_iname(usr_name)),
1442                (Attribute::Uuid, Value::Uuid(usr_uuid)),
1443                (Attribute::Description, Value::new_utf8s(usr_name)),
1444                (Attribute::DisplayName, Value::new_utf8s(usr_name))
1445            );
1446
1447            let e2 = entry_init!(
1448                (Attribute::Class, EntryClass::Object.to_value()),
1449                (Attribute::Class, EntryClass::Group.to_value()),
1450                (Attribute::Name, Value::new_iname(grp1_name)),
1451                (Attribute::Uuid, Value::Uuid(grp1_uuid)),
1452                (Attribute::Member, Value::Refer(usr_uuid))
1453            );
1454
1455            let e3 = entry_init!(
1456                (Attribute::Class, EntryClass::Object.to_value()),
1457                (Attribute::Class, EntryClass::Group.to_value()),
1458                (Attribute::Name, Value::new_iname(grp2_name)),
1459                (Attribute::Uuid, Value::Uuid(grp2_uuid))
1460            );
1461
1462            let e4 = entry_init!(
1463                (Attribute::Class, EntryClass::Object.to_value()),
1464                (Attribute::Class, EntryClass::Account.to_value()),
1465                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1466                (Attribute::Class, EntryClass::Application.to_value()),
1467                (Attribute::DisplayName, Value::new_utf8s("Application")),
1468                (Attribute::Name, Value::new_iname(app1_name)),
1469                (Attribute::Uuid, Value::Uuid(app1_uuid)),
1470                (Attribute::LinkedGroup, Value::Refer(grp1_uuid))
1471            );
1472
1473            let e5 = entry_init!(
1474                (Attribute::Class, EntryClass::Object.to_value()),
1475                (Attribute::Class, EntryClass::Account.to_value()),
1476                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1477                (Attribute::Class, EntryClass::Application.to_value()),
1478                (Attribute::DisplayName, Value::new_utf8s("Application")),
1479                (Attribute::Name, Value::new_iname(app2_name)),
1480                (Attribute::Uuid, Value::Uuid(app2_uuid)),
1481                (Attribute::LinkedGroup, Value::Refer(grp2_uuid))
1482            );
1483
1484            let ct = duration_from_epoch_now();
1485            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1486            assert!(server_txn
1487                .qs_write
1488                .internal_create(vec![e1, e2, e3, e4, e5])
1489                .and_then(|_| server_txn.commit())
1490                .is_ok());
1491        }
1492
1493        let pass_app1: String;
1494        let pass_app2: String;
1495        {
1496            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1497
1498            let ev = GenerateApplicationPasswordEvent::new_internal(
1499                usr_uuid,
1500                app1_uuid,
1501                "label".to_string(),
1502            );
1503            (pass_app1, _) = idms_prox_write
1504                .generate_application_password(&ev)
1505                .expect("Failed to generate application password");
1506
1507            // It is possible to generate an application password even if the
1508            // user is not member of the linked group
1509            let ev = GenerateApplicationPasswordEvent::new_internal(
1510                usr_uuid,
1511                app2_uuid,
1512                "label".to_string(),
1513            );
1514            (pass_app2, _) = idms_prox_write
1515                .generate_application_password(&ev)
1516                .expect("Failed to generate application password");
1517
1518            assert!(idms_prox_write.commit().is_ok());
1519        }
1520
1521        // Got session, app password valid
1522        let res = ldaps
1523            .do_bind(
1524                idms,
1525                format!("spn={usr_name},app={app1_name},dc=example,dc=com").as_str(),
1526                pass_app1.as_str(),
1527            )
1528            .await;
1529        assert!(res.is_ok());
1530        assert!(res.unwrap().is_some());
1531
1532        // No session, not member
1533        let res = ldaps
1534            .do_bind(
1535                idms,
1536                format!("spn={usr_name},app={app2_name},dc=example,dc=com").as_str(),
1537                pass_app2.as_str(),
1538            )
1539            .await;
1540        assert!(res.is_ok());
1541        assert!(res.unwrap().is_none());
1542
1543        // Add user to grp2
1544        {
1545            let ml = ModifyList::new_append(Attribute::Member, Value::Refer(usr_uuid));
1546            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1547            assert!(idms_prox_write
1548                .qs_write
1549                .internal_modify_uuid(grp2_uuid, &ml)
1550                .is_ok());
1551            assert!(idms_prox_write.commit().is_ok());
1552        }
1553
1554        // Got session, app password valid
1555        let res = ldaps
1556            .do_bind(
1557                idms,
1558                format!("spn={usr_name},app={app2_name},dc=example,dc=com").as_str(),
1559                pass_app2.as_str(),
1560            )
1561            .await;
1562        assert!(res.is_ok());
1563        assert!(res.unwrap().is_some());
1564
1565        // No session, wrong app
1566        let res = ldaps
1567            .do_bind(
1568                idms,
1569                format!("spn={usr_name},app={app1_name},dc=example,dc=com").as_str(),
1570                pass_app2.as_str(),
1571            )
1572            .await;
1573        assert!(res.is_ok());
1574        assert!(res.unwrap().is_none());
1575
1576        // Bind error, app not exists
1577        {
1578            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1579            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
1580                Attribute::Uuid,
1581                PartialValue::Uuid(app2_uuid)
1582            )));
1583            assert!(idms_prox_write.qs_write.delete(&de).is_ok());
1584            assert!(idms_prox_write.commit().is_ok());
1585        }
1586
1587        let res = ldaps
1588            .do_bind(
1589                idms,
1590                format!("spn={usr_name},app={app2_name},dc=example,dc=com").as_str(),
1591                pass_app2.as_str(),
1592            )
1593            .await;
1594        assert!(res.is_err());
1595    }
1596
1597    // For testing the timeouts
1598    // We need times on this scale
1599    //    not yet valid <-> valid from time <-> current_time <-> expire time <-> expired
1600    const TEST_CURRENT_TIME: u64 = 6000;
1601    const TEST_NOT_YET_VALID_TIME: u64 = TEST_CURRENT_TIME - 240;
1602    const TEST_VALID_FROM_TIME: u64 = TEST_CURRENT_TIME - 120;
1603    const TEST_EXPIRE_TIME: u64 = TEST_CURRENT_TIME + 120;
1604    const TEST_AFTER_EXPIRY: u64 = TEST_CURRENT_TIME + 240;
1605
1606    async fn set_account_valid_time(idms: &IdmServer, acct: Uuid) {
1607        let mut idms_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1608
1609        let v_valid_from = Value::new_datetime_epoch(Duration::from_secs(TEST_VALID_FROM_TIME));
1610        let v_expire = Value::new_datetime_epoch(Duration::from_secs(TEST_EXPIRE_TIME));
1611
1612        let me = ModifyEvent::new_internal_invalid(
1613            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(acct))),
1614            ModifyList::new_list(vec![
1615                Modify::Present(Attribute::AccountExpire, v_expire),
1616                Modify::Present(Attribute::AccountValidFrom, v_valid_from),
1617            ]),
1618        );
1619        assert!(idms_write.qs_write.modify(&me).is_ok());
1620        idms_write.commit().expect("Must not fail");
1621    }
1622
1623    #[idm_test]
1624    async fn test_ldap_application_valid_from_expire(
1625        idms: &IdmServer,
1626        _idms_delayed: &IdmServerDelayed,
1627    ) {
1628        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1629
1630        let usr_uuid = Uuid::new_v4();
1631        let usr_name = "testuser1";
1632
1633        let grp1_uuid = Uuid::new_v4();
1634        let grp1_name = "testgroup1";
1635
1636        let app1_uuid = Uuid::new_v4();
1637        let app1_name = "testapp1";
1638
1639        let pass_app1: String;
1640
1641        // Setup person, group, application and app password
1642        {
1643            let e1 = entry_init!(
1644                (Attribute::Class, EntryClass::Object.to_value()),
1645                (Attribute::Class, EntryClass::Account.to_value()),
1646                (Attribute::Class, EntryClass::Person.to_value()),
1647                (Attribute::Name, Value::new_iname(usr_name)),
1648                (Attribute::Uuid, Value::Uuid(usr_uuid)),
1649                (Attribute::Description, Value::new_utf8s(usr_name)),
1650                (Attribute::DisplayName, Value::new_utf8s(usr_name))
1651            );
1652
1653            let e2 = entry_init!(
1654                (Attribute::Class, EntryClass::Object.to_value()),
1655                (Attribute::Class, EntryClass::Group.to_value()),
1656                (Attribute::Name, Value::new_iname(grp1_name)),
1657                (Attribute::Uuid, Value::Uuid(grp1_uuid)),
1658                (Attribute::Member, Value::Refer(usr_uuid))
1659            );
1660
1661            let e3 = entry_init!(
1662                (Attribute::Class, EntryClass::Object.to_value()),
1663                (Attribute::Class, EntryClass::Account.to_value()),
1664                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1665                (Attribute::Class, EntryClass::Application.to_value()),
1666                (Attribute::DisplayName, Value::new_utf8s("Application")),
1667                (Attribute::Name, Value::new_iname(app1_name)),
1668                (Attribute::Uuid, Value::Uuid(app1_uuid)),
1669                (Attribute::LinkedGroup, Value::Refer(grp1_uuid))
1670            );
1671
1672            let ct = duration_from_epoch_now();
1673            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1674            assert!(server_txn
1675                .qs_write
1676                .internal_create(vec![e1, e2, e3])
1677                .and_then(|_| server_txn.commit())
1678                .is_ok());
1679
1680            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1681
1682            let ev = GenerateApplicationPasswordEvent::new_internal(
1683                usr_uuid,
1684                app1_uuid,
1685                "label".to_string(),
1686            );
1687            (pass_app1, _) = idms_prox_write
1688                .generate_application_password(&ev)
1689                .expect("Failed to generate application password");
1690
1691            assert!(idms_prox_write.commit().is_ok());
1692        }
1693
1694        // Got session, app password valid
1695        let res = ldaps
1696            .do_bind(
1697                idms,
1698                format!("spn={usr_name},app={app1_name},dc=example,dc=com").as_str(),
1699                pass_app1.as_str(),
1700            )
1701            .await;
1702        assert!(res.is_ok());
1703        assert!(res.unwrap().is_some());
1704
1705        // Any account that is not yet valid / expired can't auth.
1706        // Set the valid bounds high/low
1707        // TEST_VALID_FROM_TIME/TEST_EXPIRE_TIME
1708        set_account_valid_time(idms, usr_uuid).await;
1709
1710        let time_low = Duration::from_secs(TEST_NOT_YET_VALID_TIME);
1711        let time = Duration::from_secs(TEST_CURRENT_TIME);
1712        let time_high = Duration::from_secs(TEST_AFTER_EXPIRY);
1713
1714        let mut idms_auth = idms.auth().await.unwrap();
1715        let lae = LdapApplicationAuthEvent::new(app1_name, usr_uuid, pass_app1)
1716            .expect("Failed to build auth event");
1717
1718        let r1 = idms_auth
1719            .application_auth_ldap(&lae, time_low)
1720            .await
1721            .expect_err("Authentication succeeded");
1722        assert_eq!(r1, OperationError::SessionExpired);
1723
1724        let r1 = idms_auth
1725            .application_auth_ldap(&lae, time)
1726            .await
1727            .expect("Failed auth");
1728        assert!(r1.is_some());
1729
1730        let r1 = idms_auth
1731            .application_auth_ldap(&lae, time_high)
1732            .await
1733            .expect_err("Authentication succeeded");
1734        assert_eq!(r1, OperationError::SessionExpired);
1735    }
1736
1737    macro_rules! assert_entry_contains {
1738        (
1739            $entry:expr,
1740            $dn:expr,
1741            $($item:expr),*
1742        ) => {{
1743            assert_eq!($entry.dn, $dn);
1744            // Build a set from the attrs.
1745            let mut attrs = HashSet::new();
1746            for a in $entry.attributes.iter() {
1747                for v in a.vals.iter() {
1748                    attrs.insert((a.atype.as_str(), v.as_slice()));
1749                }
1750            };
1751            info!(?attrs);
1752            $(
1753                warn!("{}", $item.0);
1754                assert!(attrs.contains(&(
1755                    $item.0.as_ref(), $item.1.as_bytes()
1756                )));
1757            )*
1758
1759        }};
1760    }
1761
1762    #[idm_test]
1763    async fn test_ldap_virtual_attribute_generation(
1764        idms: &IdmServer,
1765        _idms_delayed: &IdmServerDelayed,
1766    ) {
1767        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1768
1769        let ssh_ed25519 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAeGW1P6Pc2rPq0XqbRaDKBcXZUPRklo0L1EyR30CwoP william@amethyst";
1770
1771        // Setup a user we want to check.
1772        {
1773            let e1 = entry_init!(
1774                (Attribute::Class, EntryClass::Object.to_value()),
1775                (Attribute::Class, EntryClass::Person.to_value()),
1776                (Attribute::Class, EntryClass::Account.to_value()),
1777                (Attribute::Class, EntryClass::PosixAccount.to_value()),
1778                (Attribute::Name, Value::new_iname("testperson1")),
1779                (
1780                    Attribute::Uuid,
1781                    Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1782                ),
1783                (Attribute::Description, Value::new_utf8s("testperson1")),
1784                (Attribute::DisplayName, Value::new_utf8s("testperson1")),
1785                (Attribute::GidNumber, Value::new_uint32(12345)),
1786                (Attribute::LoginShell, Value::new_iutf8("/bin/zsh")),
1787                (
1788                    Attribute::SshPublicKey,
1789                    Value::new_sshkey_str("test", ssh_ed25519).expect("Invalid ssh key")
1790                )
1791            );
1792
1793            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
1794            let ce = CreateEvent::new_internal(vec![e1]);
1795            assert!(server_txn
1796                .qs_write
1797                .create(&ce)
1798                .and_then(|_| server_txn.commit())
1799                .is_ok());
1800        }
1801
1802        // Setup the anonymous login.
1803        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
1804        assert_eq!(
1805            anon_t.effective_session,
1806            LdapSession::UnixBind(UUID_ANONYMOUS)
1807        );
1808
1809        // Check that when we request *, we get default list.
1810        let sr = SearchRequest {
1811            msgid: 1,
1812            base: "dc=example,dc=com".to_string(),
1813            scope: LdapSearchScope::Subtree,
1814            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
1815            attrs: vec!["*".to_string()],
1816        };
1817        let r1 = ldaps
1818            .do_search(idms, &sr, &anon_t, Source::Internal)
1819            .await
1820            .unwrap();
1821
1822        // The result, and the ldap proto success msg.
1823        assert_eq!(r1.len(), 2);
1824        match &r1[0].op {
1825            LdapOp::SearchResultEntry(lsre) => {
1826                assert_entry_contains!(
1827                    lsre,
1828                    "spn=testperson1@example.com,dc=example,dc=com",
1829                    (Attribute::Class, EntryClass::Object.to_string()),
1830                    (Attribute::Class, EntryClass::Person.to_string()),
1831                    (Attribute::Class, EntryClass::Account.to_string()),
1832                    (Attribute::Class, EntryClass::PosixAccount.to_string()),
1833                    (Attribute::DisplayName, "testperson1"),
1834                    (Attribute::Name, "testperson1"),
1835                    (Attribute::GidNumber, "12345"),
1836                    (Attribute::LoginShell, "/bin/zsh"),
1837                    (Attribute::SshPublicKey, ssh_ed25519),
1838                    (Attribute::Uuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930")
1839                );
1840            }
1841            _ => panic!("Oh no"),
1842        };
1843
1844        // Check that when we request +, we get all attrs and the vattrs
1845        let sr = SearchRequest {
1846            msgid: 1,
1847            base: "dc=example,dc=com".to_string(),
1848            scope: LdapSearchScope::Subtree,
1849            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
1850            attrs: vec!["+".to_string()],
1851        };
1852        let r1 = ldaps
1853            .do_search(idms, &sr, &anon_t, Source::Internal)
1854            .await
1855            .unwrap();
1856
1857        // The result, and the ldap proto success msg.
1858        assert_eq!(r1.len(), 2);
1859        match &r1[0].op {
1860            LdapOp::SearchResultEntry(lsre) => {
1861                assert_entry_contains!(
1862                    lsre,
1863                    "spn=testperson1@example.com,dc=example,dc=com",
1864                    (Attribute::ObjectClass, EntryClass::Object.as_ref()),
1865                    (Attribute::ObjectClass, EntryClass::Person.as_ref()),
1866                    (Attribute::ObjectClass, EntryClass::Account.as_ref()),
1867                    (Attribute::ObjectClass, EntryClass::PosixAccount.as_ref()),
1868                    (Attribute::DisplayName, "testperson1"),
1869                    (Attribute::Name, "testperson1"),
1870                    (Attribute::GidNumber, "12345"),
1871                    (Attribute::LoginShell, "/bin/zsh"),
1872                    (Attribute::SshPublicKey, ssh_ed25519),
1873                    (Attribute::EntryUuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930"),
1874                    (
1875                        Attribute::EntryDn,
1876                        "spn=testperson1@example.com,dc=example,dc=com"
1877                    ),
1878                    (Attribute::UidNumber, "12345"),
1879                    (Attribute::Cn, "testperson1"),
1880                    (Attribute::LdapKeys, ssh_ed25519)
1881                );
1882            }
1883            _ => panic!("Oh no"),
1884        };
1885
1886        // Check that when we request an attr by name, we get all of them correctly.
1887        let sr = SearchRequest {
1888            msgid: 1,
1889            base: "dc=example,dc=com".to_string(),
1890            scope: LdapSearchScope::Subtree,
1891            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
1892            attrs: vec![
1893                LDAP_ATTR_NAME.to_string(),
1894                Attribute::EntryDn.to_string(),
1895                ATTR_LDAP_KEYS.to_string(),
1896                Attribute::UidNumber.to_string(),
1897            ],
1898        };
1899        let r1 = ldaps
1900            .do_search(idms, &sr, &anon_t, Source::Internal)
1901            .await
1902            .unwrap();
1903
1904        // The result, and the ldap proto success msg.
1905        assert_eq!(r1.len(), 2);
1906        match &r1[0].op {
1907            LdapOp::SearchResultEntry(lsre) => {
1908                assert_entry_contains!(
1909                    lsre,
1910                    "spn=testperson1@example.com,dc=example,dc=com",
1911                    (Attribute::Name, "testperson1"),
1912                    (
1913                        Attribute::EntryDn,
1914                        "spn=testperson1@example.com,dc=example,dc=com"
1915                    ),
1916                    (Attribute::UidNumber, "12345"),
1917                    (Attribute::LdapKeys, ssh_ed25519)
1918                );
1919            }
1920            _ => panic!("Oh no"),
1921        };
1922    }
1923
1924    #[idm_test]
1925    async fn test_ldap_token_privilege_granting(
1926        idms: &IdmServer,
1927        _idms_delayed: &IdmServerDelayed,
1928    ) {
1929        // Setup the ldap server
1930        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
1931
1932        // Prebuild the search req we'll be using this test.
1933        let sr = SearchRequest {
1934            msgid: 1,
1935            base: "dc=example,dc=com".to_string(),
1936            scope: LdapSearchScope::Subtree,
1937            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
1938            attrs: vec![
1939                LDAP_ATTR_NAME,
1940                LDAP_ATTR_MAIL,
1941                LDAP_ATTR_MAIL_PRIMARY,
1942                LDAP_ATTR_MAIL_ALTERNATIVE,
1943                LDAP_ATTR_EMAIL_PRIMARY,
1944                LDAP_ATTR_EMAIL_ALTERNATIVE,
1945            ]
1946            .into_iter()
1947            .map(|s| s.to_string())
1948            .collect(),
1949        };
1950
1951        let sa_uuid = uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
1952
1953        // Configure the user account that will have the tokens issued.
1954        // Should be a SERVICE account.
1955        let apitoken = {
1956            // Create a service account,
1957
1958            let e1 = entry_init!(
1959                (Attribute::Class, EntryClass::Object.to_value()),
1960                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
1961                (Attribute::Class, EntryClass::Account.to_value()),
1962                (Attribute::Uuid, Value::Uuid(sa_uuid)),
1963                (Attribute::Name, Value::new_iname("service_permission_test")),
1964                (
1965                    Attribute::DisplayName,
1966                    Value::new_utf8s("service_permission_test")
1967                )
1968            );
1969
1970            // Setup a person with an email
1971            let e2 = entry_init!(
1972                (Attribute::Class, EntryClass::Object.to_value()),
1973                (Attribute::Class, EntryClass::Person.to_value()),
1974                (Attribute::Class, EntryClass::Account.to_value()),
1975                (Attribute::Class, EntryClass::PosixAccount.to_value()),
1976                (Attribute::Name, Value::new_iname("testperson1")),
1977                (
1978                    Attribute::Mail,
1979                    Value::EmailAddress("testperson1@example.com".to_string(), true)
1980                ),
1981                (
1982                    Attribute::Mail,
1983                    Value::EmailAddress("testperson1.alternative@example.com".to_string(), false)
1984                ),
1985                (Attribute::Description, Value::new_utf8s("testperson1")),
1986                (Attribute::DisplayName, Value::new_utf8s("testperson1")),
1987                (Attribute::GidNumber, Value::new_uint32(12345)),
1988                (Attribute::LoginShell, Value::new_iutf8("/bin/zsh"))
1989            );
1990
1991            // Setup an access control for the service account to view mail attrs.
1992
1993            let ct = duration_from_epoch_now();
1994
1995            let mut server_txn = idms.proxy_write(ct).await.unwrap();
1996            let ce = CreateEvent::new_internal(vec![e1, e2]);
1997            assert!(server_txn.qs_write.create(&ce).is_ok());
1998
1999            // idm_people_read_priv
2000            let me = ModifyEvent::new_internal_invalid(
2001                filter!(f_eq(
2002                    Attribute::Name,
2003                    PartialValue::new_iname("idm_people_pii_read")
2004                )),
2005                ModifyList::new_list(vec![Modify::Present(
2006                    Attribute::Member,
2007                    Value::Refer(sa_uuid),
2008                )]),
2009            );
2010            assert!(server_txn.qs_write.modify(&me).is_ok());
2011
2012            // Issue a token
2013            // make it purpose = ldap <- currently purpose isn't supported,
2014            // it's an idea for future.
2015            let gte = GenerateApiTokenEvent::new_internal(sa_uuid, "TestToken", None);
2016
2017            let apitoken = server_txn
2018                .service_account_generate_api_token(&gte, ct)
2019                .expect("Failed to create new apitoken");
2020
2021            assert!(server_txn.commit().is_ok());
2022
2023            apitoken
2024        };
2025
2026        // assert the token fails on non-ldap events token-xchg <- currently
2027        // we don't have purpose so this isn't tested.
2028
2029        // Bind with anonymous, search and show mail attr isn't accessible.
2030        let anon_lbt = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2031        assert_eq!(
2032            anon_lbt.effective_session,
2033            LdapSession::UnixBind(UUID_ANONYMOUS)
2034        );
2035
2036        let r1 = ldaps
2037            .do_search(idms, &sr, &anon_lbt, Source::Internal)
2038            .await
2039            .unwrap();
2040        assert_eq!(r1.len(), 2);
2041        match &r1[0].op {
2042            LdapOp::SearchResultEntry(lsre) => {
2043                assert_entry_contains!(
2044                    lsre,
2045                    "spn=testperson1@example.com,dc=example,dc=com",
2046                    (Attribute::Name, "testperson1")
2047                );
2048            }
2049            _ => panic!("Oh no"),
2050        };
2051
2052        // Inspect the token to get its uuid out.
2053        let jws_verifier = JwsDangerReleaseWithoutVerify::default();
2054
2055        let apitoken_inner = jws_verifier
2056            .verify(&apitoken)
2057            .unwrap()
2058            .from_json::<ApiToken>()
2059            .unwrap();
2060
2061        // Bind using the token as a DN
2062        let sa_lbt = ldaps
2063            .do_bind(idms, "dn=token", &apitoken.to_string())
2064            .await
2065            .unwrap()
2066            .unwrap();
2067        assert_eq!(
2068            sa_lbt.effective_session,
2069            LdapSession::ApiToken(apitoken_inner.clone())
2070        );
2071
2072        // Bind using the token as a pw
2073        let sa_lbt = ldaps
2074            .do_bind(idms, "", &apitoken.to_string())
2075            .await
2076            .unwrap()
2077            .unwrap();
2078        assert_eq!(
2079            sa_lbt.effective_session,
2080            LdapSession::ApiToken(apitoken_inner)
2081        );
2082
2083        // Search and retrieve mail that's now accessible.
2084        let r1 = ldaps
2085            .do_search(idms, &sr, &sa_lbt, Source::Internal)
2086            .await
2087            .unwrap();
2088        assert_eq!(r1.len(), 2);
2089        match &r1[0].op {
2090            LdapOp::SearchResultEntry(lsre) => {
2091                assert_entry_contains!(
2092                    lsre,
2093                    "spn=testperson1@example.com,dc=example,dc=com",
2094                    (Attribute::Name, "testperson1"),
2095                    (Attribute::Mail, "testperson1@example.com"),
2096                    (Attribute::Mail, "testperson1.alternative@example.com"),
2097                    (LDAP_ATTR_MAIL_PRIMARY, "testperson1@example.com"),
2098                    (
2099                        LDAP_ATTR_MAIL_ALTERNATIVE,
2100                        "testperson1.alternative@example.com"
2101                    ),
2102                    (LDAP_ATTR_EMAIL_PRIMARY, "testperson1@example.com"),
2103                    (
2104                        LDAP_ATTR_EMAIL_ALTERNATIVE,
2105                        "testperson1.alternative@example.com"
2106                    )
2107                );
2108            }
2109            _ => panic!("Oh no"),
2110        };
2111
2112        // ======= test with a substring search
2113
2114        let sr = SearchRequest {
2115            msgid: 2,
2116            base: "dc=example,dc=com".to_string(),
2117            scope: LdapSearchScope::Subtree,
2118            filter: LdapFilter::And(vec![
2119                LdapFilter::Equality(Attribute::Class.to_string(), "posixAccount".to_string()),
2120                LdapFilter::Substring(
2121                    LDAP_ATTR_MAIL.to_string(),
2122                    LdapSubstringFilter {
2123                        initial: None,
2124                        any: vec![],
2125                        final_: Some("@example.com".to_string()),
2126                    },
2127                ),
2128            ]),
2129            attrs: vec![
2130                LDAP_ATTR_NAME,
2131                LDAP_ATTR_MAIL,
2132                LDAP_ATTR_MAIL_PRIMARY,
2133                LDAP_ATTR_MAIL_ALTERNATIVE,
2134            ]
2135            .into_iter()
2136            .map(|s| s.to_string())
2137            .collect(),
2138        };
2139
2140        let r1 = ldaps
2141            .do_search(idms, &sr, &sa_lbt, Source::Internal)
2142            .await
2143            .unwrap();
2144
2145        assert_eq!(r1.len(), 2);
2146        match &r1[0].op {
2147            LdapOp::SearchResultEntry(lsre) => {
2148                assert_entry_contains!(
2149                    lsre,
2150                    "spn=testperson1@example.com,dc=example,dc=com",
2151                    (Attribute::Name, "testperson1"),
2152                    (Attribute::Mail, "testperson1@example.com"),
2153                    (Attribute::Mail, "testperson1.alternative@example.com"),
2154                    (LDAP_ATTR_MAIL_PRIMARY, "testperson1@example.com"),
2155                    (
2156                        LDAP_ATTR_MAIL_ALTERNATIVE,
2157                        "testperson1.alternative@example.com"
2158                    )
2159                );
2160            }
2161            _ => panic!("Oh no"),
2162        };
2163    }
2164
2165    #[idm_test]
2166    async fn test_ldap_virtual_attribute_with_all_attr_search(
2167        idms: &IdmServer,
2168        _idms_delayed: &IdmServerDelayed,
2169    ) {
2170        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2171
2172        let acct_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
2173
2174        // Setup a user we want to check.
2175        {
2176            let e1 = entry_init!(
2177                (Attribute::Class, EntryClass::Person.to_value()),
2178                (Attribute::Class, EntryClass::Account.to_value()),
2179                (Attribute::Name, Value::new_iname("testperson1")),
2180                (Attribute::Uuid, Value::Uuid(acct_uuid)),
2181                (Attribute::Description, Value::new_utf8s("testperson1")),
2182                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2183            );
2184
2185            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2186            assert!(server_txn
2187                .qs_write
2188                .internal_create(vec![e1])
2189                .and_then(|_| server_txn.commit())
2190                .is_ok());
2191        }
2192
2193        // Setup the anonymous login.
2194        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2195        assert_eq!(
2196            anon_t.effective_session,
2197            LdapSession::UnixBind(UUID_ANONYMOUS)
2198        );
2199
2200        // Check that when we request a virtual attr by name *and* all_attrs we get all the requested values.
2201        let sr = SearchRequest {
2202            msgid: 1,
2203            base: "dc=example,dc=com".to_string(),
2204            scope: LdapSearchScope::Subtree,
2205            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
2206            attrs: vec![
2207                "*".to_string(),
2208                // Already being returned
2209                LDAP_ATTR_NAME.to_string(),
2210                // This is a virtual attribute
2211                Attribute::EntryUuid.to_string(),
2212            ],
2213        };
2214        let r1 = ldaps
2215            .do_search(idms, &sr, &anon_t, Source::Internal)
2216            .await
2217            .unwrap();
2218
2219        // The result, and the ldap proto success msg.
2220        assert_eq!(r1.len(), 2);
2221        match &r1[0].op {
2222            LdapOp::SearchResultEntry(lsre) => {
2223                assert_entry_contains!(
2224                    lsre,
2225                    "spn=testperson1@example.com,dc=example,dc=com",
2226                    (Attribute::Name, "testperson1"),
2227                    (Attribute::DisplayName, "testperson1"),
2228                    (Attribute::Uuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930"),
2229                    (Attribute::EntryUuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930")
2230                );
2231            }
2232            _ => panic!("Oh no"),
2233        };
2234    }
2235
2236    // Test behaviour of the 1.1 attribute.
2237    #[idm_test]
2238    async fn test_ldap_one_dot_one_attribute(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2239        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2240
2241        let acct_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
2242
2243        // Setup a user we want to check.
2244        {
2245            let e1 = entry_init!(
2246                (Attribute::Class, EntryClass::Person.to_value()),
2247                (Attribute::Class, EntryClass::Account.to_value()),
2248                (Attribute::Name, Value::new_iname("testperson1")),
2249                (Attribute::Uuid, Value::Uuid(acct_uuid)),
2250                (Attribute::Description, Value::new_utf8s("testperson1")),
2251                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2252            );
2253
2254            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2255            assert!(server_txn
2256                .qs_write
2257                .internal_create(vec![e1])
2258                .and_then(|_| server_txn.commit())
2259                .is_ok());
2260        }
2261
2262        // Setup the anonymous login.
2263        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2264        assert_eq!(
2265            anon_t.effective_session,
2266            LdapSession::UnixBind(UUID_ANONYMOUS)
2267        );
2268
2269        // If we request only 1.1, we get no attributes.
2270        let sr = SearchRequest {
2271            msgid: 1,
2272            base: "dc=example,dc=com".to_string(),
2273            scope: LdapSearchScope::Subtree,
2274            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
2275            attrs: vec!["1.1".to_string()],
2276        };
2277        let r1 = ldaps
2278            .do_search(idms, &sr, &anon_t, Source::Internal)
2279            .await
2280            .unwrap();
2281
2282        // The result, and the ldap proto success msg.
2283        assert_eq!(r1.len(), 2);
2284        match &r1[0].op {
2285            LdapOp::SearchResultEntry(lsre) => {
2286                assert_eq!(
2287                    lsre.dn.as_str(),
2288                    "spn=testperson1@example.com,dc=example,dc=com"
2289                );
2290                assert!(lsre.attributes.is_empty());
2291            }
2292            _ => panic!("Oh no"),
2293        };
2294
2295        // If we request 1.1 and another attr, 1.1 is IGNORED.
2296        let sr = SearchRequest {
2297            msgid: 1,
2298            base: "dc=example,dc=com".to_string(),
2299            scope: LdapSearchScope::Subtree,
2300            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
2301            attrs: vec![
2302                "1.1".to_string(),
2303                // This should be present.
2304                Attribute::EntryUuid.to_string(),
2305            ],
2306        };
2307        let r1 = ldaps
2308            .do_search(idms, &sr, &anon_t, Source::Internal)
2309            .await
2310            .unwrap();
2311
2312        // The result, and the ldap proto success msg.
2313        assert_eq!(r1.len(), 2);
2314        match &r1[0].op {
2315            LdapOp::SearchResultEntry(lsre) => {
2316                assert_entry_contains!(
2317                    lsre,
2318                    "spn=testperson1@example.com,dc=example,dc=com",
2319                    (Attribute::EntryUuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930")
2320                );
2321            }
2322            _ => panic!("Oh no"),
2323        };
2324    }
2325
2326    #[idm_test]
2327    async fn test_ldap_rootdse_basedn_change(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2328        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2329
2330        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2331        assert_eq!(
2332            anon_t.effective_session,
2333            LdapSession::UnixBind(UUID_ANONYMOUS)
2334        );
2335
2336        let sr = SearchRequest {
2337            msgid: 1,
2338            base: "".to_string(),
2339            scope: LdapSearchScope::Base,
2340            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
2341            attrs: vec!["*".to_string()],
2342        };
2343        let r1 = ldaps
2344            .do_search(idms, &sr, &anon_t, Source::Internal)
2345            .await
2346            .unwrap();
2347
2348        trace!(?r1);
2349
2350        // The result, and the ldap proto success msg.
2351        assert_eq!(r1.len(), 2);
2352        match &r1[0].op {
2353            LdapOp::SearchResultEntry(lsre) => {
2354                assert_entry_contains!(
2355                    lsre,
2356                    "",
2357                    (Attribute::ObjectClass, "top"),
2358                    ("vendorname", "Kanidm Project"),
2359                    ("supportedldapversion", "3"),
2360                    ("defaultnamingcontext", "dc=example,dc=com")
2361                );
2362            }
2363            _ => panic!("Oh no"),
2364        };
2365
2366        drop(ldaps);
2367
2368        // Change the domain basedn
2369
2370        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2371        // make the admin a valid posix account
2372        let me_posix = ModifyEvent::new_internal_invalid(
2373            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_DOMAIN_INFO))),
2374            ModifyList::new_purge_and_set(
2375                Attribute::DomainLdapBasedn,
2376                Value::new_iutf8("o=kanidmproject"),
2377            ),
2378        );
2379        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
2380
2381        assert!(idms_prox_write.commit().is_ok());
2382
2383        // Now re-test
2384        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2385
2386        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2387        assert_eq!(
2388            anon_t.effective_session,
2389            LdapSession::UnixBind(UUID_ANONYMOUS)
2390        );
2391
2392        let sr = SearchRequest {
2393            msgid: 1,
2394            base: "".to_string(),
2395            scope: LdapSearchScope::Base,
2396            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
2397            attrs: vec!["*".to_string()],
2398        };
2399        let r1 = ldaps
2400            .do_search(idms, &sr, &anon_t, Source::Internal)
2401            .await
2402            .unwrap();
2403
2404        trace!(?r1);
2405
2406        // The result, and the ldap proto success msg.
2407        assert_eq!(r1.len(), 2);
2408        match &r1[0].op {
2409            LdapOp::SearchResultEntry(lsre) => {
2410                assert_entry_contains!(
2411                    lsre,
2412                    "",
2413                    (Attribute::ObjectClass, "top"),
2414                    ("vendorname", "Kanidm Project"),
2415                    ("supportedldapversion", "3"),
2416                    ("defaultnamingcontext", "o=kanidmproject")
2417                );
2418            }
2419            _ => panic!("Oh no"),
2420        };
2421    }
2422
2423    #[idm_test]
2424    async fn test_ldap_sssd_compat(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2425        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2426
2427        let acct_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
2428
2429        // Setup a user we want to check.
2430        {
2431            let e1 = entry_init!(
2432                (Attribute::Class, EntryClass::Person.to_value()),
2433                (Attribute::Class, EntryClass::Account.to_value()),
2434                (Attribute::Class, EntryClass::PosixAccount.to_value()),
2435                (Attribute::Name, Value::new_iname("testperson1")),
2436                (Attribute::Uuid, Value::Uuid(acct_uuid)),
2437                (Attribute::GidNumber, Value::Uint32(12345)),
2438                (Attribute::Description, Value::new_utf8s("testperson1")),
2439                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2440            );
2441
2442            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2443            assert!(server_txn
2444                .qs_write
2445                .internal_create(vec![e1])
2446                .and_then(|_| server_txn.commit())
2447                .is_ok());
2448        }
2449
2450        // Setup the anonymous login.
2451        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2452        assert_eq!(
2453            anon_t.effective_session,
2454            LdapSession::UnixBind(UUID_ANONYMOUS)
2455        );
2456
2457        // SSSD tries to just search for silly attrs all the time. We ignore them.
2458        let sr = SearchRequest {
2459            msgid: 1,
2460            base: "dc=example,dc=com".to_string(),
2461            scope: LdapSearchScope::Subtree,
2462            filter: LdapFilter::And(vec![
2463                LdapFilter::Equality(Attribute::Class.to_string(), "sudohost".to_string()),
2464                LdapFilter::Substring(
2465                    Attribute::SudoHost.to_string(),
2466                    LdapSubstringFilter {
2467                        initial: Some("a".to_string()),
2468                        any: vec!["x".to_string()],
2469                        final_: Some("z".to_string()),
2470                    },
2471                ),
2472            ]),
2473            attrs: vec![
2474                "*".to_string(),
2475                // Already being returned
2476                LDAP_ATTR_NAME.to_string(),
2477                // This is a virtual attribute
2478                Attribute::EntryUuid.to_string(),
2479            ],
2480        };
2481        let r1 = ldaps
2482            .do_search(idms, &sr, &anon_t, Source::Internal)
2483            .await
2484            .unwrap();
2485
2486        // Empty results and ldap proto success msg.
2487        assert_eq!(r1.len(), 1);
2488
2489        // Second search
2490
2491        let sr = SearchRequest {
2492            msgid: 1,
2493            base: "dc=example,dc=com".to_string(),
2494            scope: LdapSearchScope::Subtree,
2495            filter: LdapFilter::Equality(Attribute::Name.to_string(), "testperson1".to_string()),
2496            attrs: vec![
2497                "uid".to_string(),
2498                "uidNumber".to_string(),
2499                "gidNumber".to_string(),
2500                "gecos".to_string(),
2501                "cn".to_string(),
2502                "entryuuid".to_string(),
2503            ],
2504        };
2505        let r1 = ldaps
2506            .do_search(idms, &sr, &anon_t, Source::Internal)
2507            .await
2508            .unwrap();
2509
2510        trace!(?r1);
2511
2512        // The result, and the ldap proto success msg.
2513        assert_eq!(r1.len(), 2);
2514        match &r1[0].op {
2515            LdapOp::SearchResultEntry(lsre) => {
2516                assert_entry_contains!(
2517                    lsre,
2518                    "spn=testperson1@example.com,dc=example,dc=com",
2519                    (Attribute::Uid, "testperson1"),
2520                    (Attribute::Cn, "testperson1"),
2521                    (Attribute::Gecos, "testperson1"),
2522                    (Attribute::UidNumber, "12345"),
2523                    (Attribute::GidNumber, "12345"),
2524                    (Attribute::EntryUuid, "cc8e95b4-c24f-4d68-ba54-8bed76f63930")
2525                );
2526            }
2527            _ => panic!("Oh no"),
2528        };
2529    }
2530
2531    #[idm_test]
2532    async fn test_ldap_compare_request(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2533        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2534
2535        // Setup a user we want to check.
2536        {
2537            let acct_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
2538
2539            let e1 = entry_init!(
2540                (Attribute::Class, EntryClass::Person.to_value()),
2541                (Attribute::Class, EntryClass::Account.to_value()),
2542                (Attribute::Class, EntryClass::PosixAccount.to_value()),
2543                (Attribute::Name, Value::new_iname("testperson1")),
2544                (Attribute::Uuid, Value::Uuid(acct_uuid)),
2545                (Attribute::GidNumber, Value::Uint32(12345)),
2546                (Attribute::Description, Value::new_utf8s("testperson1")),
2547                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2548            );
2549
2550            let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2551            assert!(server_txn
2552                .qs_write
2553                .internal_create(vec![e1])
2554                .and_then(|_| server_txn.commit())
2555                .is_ok());
2556        }
2557
2558        // Setup the anonymous login.
2559        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2560        assert_eq!(
2561            anon_t.effective_session,
2562            LdapSession::UnixBind(UUID_ANONYMOUS)
2563        );
2564
2565        #[track_caller]
2566        fn assert_compare_result(r: &[LdapMsg], code: &LdapResultCode) {
2567            assert_eq!(r.len(), 1);
2568            match &r[0].op {
2569                LdapOp::CompareResult(lcr) => {
2570                    assert_eq!(&lcr.code, code);
2571                }
2572                _ => panic!("Oh no"),
2573            };
2574        }
2575
2576        let cr = CompareRequest {
2577            msgid: 1,
2578            entry: "name=testperson1,dc=example,dc=com".to_string(),
2579            atype: Attribute::Name.to_string(),
2580            val: "testperson1".to_string(),
2581        };
2582
2583        assert_compare_result(
2584            &ldaps
2585                .do_compare(idms, &cr, &anon_t, Source::Internal)
2586                .await
2587                .unwrap(),
2588            &LdapResultCode::CompareTrue,
2589        );
2590
2591        let cr = CompareRequest {
2592            msgid: 1,
2593            entry: "name=testperson1,dc=example,dc=com".to_string(),
2594            atype: Attribute::GidNumber.to_string(),
2595            val: "12345".to_string(),
2596        };
2597
2598        assert_compare_result(
2599            &ldaps
2600                .do_compare(idms, &cr, &anon_t, Source::Internal)
2601                .await
2602                .unwrap(),
2603            &LdapResultCode::CompareTrue,
2604        );
2605
2606        let cr = CompareRequest {
2607            msgid: 1,
2608            entry: "name=testperson1,dc=example,dc=com".to_string(),
2609            atype: Attribute::Name.to_string(),
2610            val: "other".to_string(),
2611        };
2612        assert_compare_result(
2613            &ldaps
2614                .do_compare(idms, &cr, &anon_t, Source::Internal)
2615                .await
2616                .unwrap(),
2617            &LdapResultCode::CompareFalse,
2618        );
2619
2620        let cr = CompareRequest {
2621            msgid: 1,
2622            entry: "name=other,dc=example,dc=com".to_string(),
2623            atype: Attribute::Name.to_string(),
2624            val: "other".to_string(),
2625        };
2626        assert_compare_result(
2627            &ldaps
2628                .do_compare(idms, &cr, &anon_t, Source::Internal)
2629                .await
2630                .unwrap(),
2631            &LdapResultCode::NoSuchObject,
2632        );
2633
2634        let cr = CompareRequest {
2635            msgid: 1,
2636            entry: "invalidentry".to_string(),
2637            atype: Attribute::Name.to_string(),
2638            val: "other".to_string(),
2639        };
2640        assert!(&ldaps
2641            .do_compare(idms, &cr, &anon_t, Source::Internal)
2642            .await
2643            .is_err());
2644
2645        let cr = CompareRequest {
2646            msgid: 1,
2647            entry: "name=other,dc=example,dc=com".to_string(),
2648            atype: "invalid".to_string(),
2649            val: "other".to_string(),
2650        };
2651        assert_eq!(
2652            &ldaps
2653                .do_compare(idms, &cr, &anon_t, Source::Internal)
2654                .await
2655                .unwrap_err(),
2656            &OperationError::InvalidAttributeName("invalid".to_string()),
2657        );
2658    }
2659
2660    #[idm_test]
2661    async fn test_ldap_maximum_queryable_attributes(
2662        idms: &IdmServer,
2663        _idms_delayed: &IdmServerDelayed,
2664    ) {
2665        // Set the max queryable attrs to 2
2666
2667        let mut server_txn = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2668
2669        let set_ldap_maximum_queryable_attrs = ModifyEvent::new_internal_invalid(
2670            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_DOMAIN_INFO))),
2671            ModifyList::new_purge_and_set(Attribute::LdapMaxQueryableAttrs, Value::Uint32(2)),
2672        );
2673        assert!(server_txn
2674            .qs_write
2675            .modify(&set_ldap_maximum_queryable_attrs)
2676            .and_then(|_| server_txn.commit())
2677            .is_ok());
2678
2679        let ldaps = LdapServer::new(idms).await.expect("failed to start ldap");
2680
2681        let usr_uuid = Uuid::new_v4();
2682        let grp_uuid = Uuid::new_v4();
2683        let app_uuid = Uuid::new_v4();
2684        let app_name = "testapp1";
2685
2686        // Setup person, group and application
2687        {
2688            let e1 = entry_init!(
2689                (Attribute::Class, EntryClass::Object.to_value()),
2690                (Attribute::Class, EntryClass::Account.to_value()),
2691                (Attribute::Class, EntryClass::Person.to_value()),
2692                (Attribute::Name, Value::new_iname("testperson1")),
2693                (Attribute::Uuid, Value::Uuid(usr_uuid)),
2694                (Attribute::Description, Value::new_utf8s("testperson1")),
2695                (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2696            );
2697
2698            let e2 = entry_init!(
2699                (Attribute::Class, EntryClass::Object.to_value()),
2700                (Attribute::Class, EntryClass::Group.to_value()),
2701                (Attribute::Name, Value::new_iname("testgroup1")),
2702                (Attribute::Uuid, Value::Uuid(grp_uuid))
2703            );
2704
2705            let e3 = entry_init!(
2706                (Attribute::Class, EntryClass::Object.to_value()),
2707                (Attribute::Class, EntryClass::Account.to_value()),
2708                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
2709                (Attribute::Class, EntryClass::Application.to_value()),
2710                (Attribute::DisplayName, Value::new_utf8s("Application")),
2711                (Attribute::Name, Value::new_iname(app_name)),
2712                (Attribute::Uuid, Value::Uuid(app_uuid)),
2713                (Attribute::LinkedGroup, Value::Refer(grp_uuid))
2714            );
2715
2716            let ct = duration_from_epoch_now();
2717            let mut server_txn = idms.proxy_write(ct).await.unwrap();
2718            assert!(server_txn
2719                .qs_write
2720                .internal_create(vec![e1, e2, e3])
2721                .and_then(|_| server_txn.commit())
2722                .is_ok());
2723        }
2724
2725        // Setup the anonymous login
2726        let anon_t = ldaps.do_bind(idms, "", "").await.unwrap().unwrap();
2727        assert_eq!(
2728            anon_t.effective_session,
2729            LdapSession::UnixBind(UUID_ANONYMOUS)
2730        );
2731
2732        let invalid_search = SearchRequest {
2733            msgid: 1,
2734            base: "dc=example,dc=com".to_string(),
2735            scope: LdapSearchScope::Subtree,
2736            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
2737            attrs: vec![
2738                "objectClass".to_string(),
2739                "cn".to_string(),
2740                "givenName".to_string(),
2741            ],
2742        };
2743
2744        let valid_search = SearchRequest {
2745            msgid: 1,
2746            base: "dc=example,dc=com".to_string(),
2747            scope: LdapSearchScope::Subtree,
2748            filter: LdapFilter::Present(Attribute::ObjectClass.to_string()),
2749            attrs: vec!["objectClass: person".to_string()],
2750        };
2751
2752        let invalid_res: Result<Vec<LdapMsg>, OperationError> = ldaps
2753            .do_search(idms, &invalid_search, &anon_t, Source::Internal)
2754            .await;
2755
2756        let valid_res: Result<Vec<LdapMsg>, OperationError> = ldaps
2757            .do_search(idms, &valid_search, &anon_t, Source::Internal)
2758            .await;
2759
2760        assert_eq!(invalid_res, Err(OperationError::ResourceLimit));
2761        assert!(valid_res.is_ok());
2762    }
2763}