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