1mod operation;
4mod search;
5mod session;
6
7use std::num::NonZeroU32;
8use std::sync::Arc;
9use std::time::Duration;
10
11use rustls::ClientConfig;
12use secrecy::{ExposeSecret, SecretString};
13use tokio::sync::Mutex;
14use tracing::debug;
15use zeroize::Zeroizing;
16
17use ldap_client_proto::{
18 AddRequest, BindAuthentication, BindRequest, CompareRequest, Control, ExtendedRequest,
19 ExtendedResponse, Filter, HasLdapResult, LdapScheme, LdapUrl, ModifyDnRequest, ModifyRequest,
20 ProtoError, STARTTLS_OID, SearchResultEntry, SearchScope, WHO_AM_I_OID,
21};
22
23use crate::Error;
24use crate::tls_config::default_client_config;
25use operation::{Delete, Operation};
26pub use search::{PagedSearch, SearchParams};
27use session::{ConnectParams, Security, Session, TransportError};
28
29const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
30const DEFAULT_MAX_MESSAGE_SIZE: u32 = 10 * 1024 * 1024;
31const MAX_SEARCH_ENTRIES: usize = 500_000;
32const SEARCH_ONE_SIZE_LIMIT: NonZeroU32 = NonZeroU32::new(2).unwrap();
33
34pub type UnsolicitedHandler = Arc<dyn Fn(&ExtendedResponse) + Send + Sync>;
36
37fn default_unsolicited_handler() -> UnsolicitedHandler {
38 Arc::new(|resp| {
39 tracing::debug!(
40 oid = resp.oid.as_deref().unwrap_or("<none>"),
41 "received unsolicited notification from server"
42 );
43 })
44}
45
46#[derive(Debug, Clone)]
47pub struct SearchResult {
48 pub entries: Vec<SearchResultEntry>,
49 pub referrals: Vec<String>,
50 pub controls: Vec<Control>,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum Transport {
55 Plain,
56 Tls,
57 StartTls,
58}
59
60impl Transport {
61 pub const fn default_port(self) -> u16 {
63 match self {
64 Self::Plain | Self::StartTls => LdapScheme::Ldap.default_port(),
65 Self::Tls => LdapScheme::Ldaps.default_port(),
66 }
67 }
68}
69
70impl From<LdapScheme> for Transport {
71 fn from(scheme: LdapScheme) -> Self {
72 match scheme {
73 LdapScheme::Ldap => Self::Plain,
74 LdapScheme::Ldaps => Self::Tls,
75 }
76 }
77}
78
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub enum ReferralPolicy {
88 #[default]
90 Ignore,
91 Return,
93 Follow { hop_limit: u8 },
95}
96
97impl ReferralPolicy {
98 pub fn follow() -> Self {
100 Self::Follow { hop_limit: 10 }
101 }
102}
103
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
106#[non_exhaustive]
107pub enum ReferralCredentials {
108 #[default]
110 Anonymous,
111 ServiceAccount,
114}
115
116pub enum BindCredentials<'a> {
118 Simple {
120 dn: &'a str,
121 password: &'a SecretString,
122 },
123 ServiceAccount,
125 SaslExternal,
127}
128
129#[derive(Clone)]
130struct ServiceAccount {
131 dn: String,
132 password: SecretString,
133}
134
135struct Settings {
137 base_dn: Option<String>,
138 service_account: Option<ServiceAccount>,
139 referral_policy: ReferralPolicy,
140 referral_credentials: ReferralCredentials,
141 unsolicited_handler: UnsolicitedHandler,
142}
143
144pub struct ClientBuilder {
145 host: String,
146 port: u16,
147 transport: Transport,
148 tls_config: Option<Arc<ClientConfig>>,
149 connect_timeout: Duration,
150 request_timeout: Duration,
151 max_message_size: u32,
152 settings: Settings,
153}
154
155impl ClientBuilder {
156 pub fn new(host: impl Into<String>, port: u16) -> Self {
157 Self {
158 host: host.into(),
159 port,
160 transport: Transport::Plain,
161 tls_config: None,
162 connect_timeout: DEFAULT_TIMEOUT,
163 request_timeout: DEFAULT_TIMEOUT,
164 max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
165 settings: Settings {
166 base_dn: None,
167 service_account: None,
168 referral_policy: ReferralPolicy::default(),
169 referral_credentials: ReferralCredentials::default(),
170 unsolicited_handler: default_unsolicited_handler(),
171 },
172 }
173 }
174
175 pub fn from_url(url: &str) -> Result<Self, Error> {
176 let parsed = LdapUrl::parse(url).map_err(|e| Error::InvalidUrl(format!("{e}")))?;
177
178 let port = parsed.effective_port();
179 let mut builder = Self::new(parsed.host, port).transport(Transport::from(parsed.scheme));
180 builder.settings.base_dn = parsed.base_dn;
181 Ok(builder)
182 }
183
184 pub fn transport(mut self, transport: Transport) -> Self {
185 self.transport = transport;
186 self
187 }
188
189 pub fn tls_config(mut self, config: Arc<ClientConfig>) -> Self {
193 self.tls_config = Some(config);
194 self
195 }
196
197 pub fn tls(mut self, config: crate::tls_config::TlsConfig) -> Result<Self, Error> {
201 self.tls_config = Some(config.build()?);
202 Ok(self)
203 }
204
205 pub fn timeout(mut self, timeout: Duration) -> Self {
207 self.connect_timeout = timeout;
208 self.request_timeout = timeout;
209 self
210 }
211
212 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
213 self.connect_timeout = timeout;
214 self
215 }
216
217 pub fn request_timeout(mut self, timeout: Duration) -> Self {
218 self.request_timeout = timeout;
219 self
220 }
221
222 pub fn base_dn(mut self, base_dn: impl Into<String>) -> Self {
223 self.settings.base_dn = Some(base_dn.into());
224 self
225 }
226
227 pub fn service_account(mut self, dn: impl Into<String>, password: SecretString) -> Self {
231 self.settings.service_account = Some(ServiceAccount {
232 dn: dn.into(),
233 password,
234 });
235 self
236 }
237
238 pub fn referral_policy(mut self, policy: ReferralPolicy) -> Self {
239 self.settings.referral_policy = policy;
240 self
241 }
242
243 pub fn referral_credentials(mut self, credentials: ReferralCredentials) -> Self {
246 self.settings.referral_credentials = credentials;
247 self
248 }
249
250 pub fn max_message_size(mut self, max: u32) -> Self {
252 self.max_message_size = max;
253 self
254 }
255
256 pub fn on_unsolicited_notification(
260 mut self,
261 handler: impl Fn(&ExtendedResponse) + Send + Sync + 'static,
262 ) -> Self {
263 self.settings.unsolicited_handler = Arc::new(handler);
264 self
265 }
266
267 pub async fn connect(self) -> Result<Client, Error> {
268 if let Some(account) = &self.settings.service_account {
269 simple_bind_request(account.dn.clone(), &account.password)?;
270 }
271
272 let params = ConnectParams {
273 security: Security::new(self.transport, &self.host)?,
274 host: self.host,
275 port: self.port,
276 tls_config: self
277 .tls_config
278 .unwrap_or_else(|| Arc::new(default_client_config())),
279 connect_timeout: self.connect_timeout,
280 request_timeout: self.request_timeout,
281 max_message_size: self.max_message_size,
282 };
283 let session = Session::open(¶ms, &self.settings.unsolicited_handler).await?;
284 Ok(Client::new(session, params, self.settings))
285 }
286}
287
288const MIN_RECONNECT_INTERVAL: Duration = Duration::from_secs(1);
289
290pub struct Client {
291 session: Mutex<Option<Session>>,
294 params: ConnectParams,
295 settings: Settings,
296 last_reconnect: Mutex<Option<tokio::time::Instant>>,
297}
298
299fn simple_bind_request(dn: String, password: &SecretString) -> Result<BindRequest, Error> {
300 if !dn.is_empty() && password.expose_secret().is_empty() {
301 return Err(Error::UnauthenticatedBind);
302 }
303 Ok(BindRequest {
304 version: 3,
305 name: dn,
306 authentication: BindAuthentication::Simple(Zeroizing::new(
307 password.expose_secret().as_bytes().to_vec(),
308 )),
309 })
310}
311
312impl Client {
313 fn new(session: Session, params: ConnectParams, settings: Settings) -> Self {
314 Self {
315 session: Mutex::new(Some(session)),
316 params,
317 settings,
318 last_reconnect: Mutex::new(None),
319 }
320 }
321
322 async fn with_session<T>(
327 &self,
328 run: impl AsyncFnOnce(&mut Session) -> Result<T, TransportError>,
329 ) -> Result<T, Error> {
330 let mut slot = self.session.lock().await;
331 let mut session = slot.take().ok_or(Error::ConnectionClosed)?;
332 let value = run(&mut session).await?;
333 *slot = Some(session);
334 Ok(value)
335 }
336
337 async fn exchange<O: Operation>(
338 &self,
339 operation: &O,
340 controls: Vec<Control>,
341 ) -> Result<O::Output, Error> {
342 let response = self
343 .with_session(async |session| {
344 let id = session.send(operation.to_protocol(), controls).await?;
345 let message = session.receive(id).await?;
346 O::response(message.operation).ok_or_else(|| {
347 ProtoError::Protocol(format!("unexpected response, expected {}", O::RESPONSE))
348 .into()
349 })
350 })
351 .await?;
352 O::output(response).map_err(|response| Error::from_failed_result(response.result()))
353 }
354
355 async fn execute<O: Operation>(
359 &self,
360 operation: O,
361 controls: Vec<Control>,
362 ) -> Result<O::Output, Error> {
363 let ReferralPolicy::Follow { hop_limit } = self.settings.referral_policy else {
364 return self.exchange(&operation, controls).await;
365 };
366
367 let mut hops = 0;
368 let mut referred: Option<Client> = None;
369 loop {
370 let client = referred.as_ref().unwrap_or(self);
371 match client.exchange(&operation, controls.clone()).await {
372 Err(Error::Referral { urls, .. }) => {
373 if hops >= hop_limit {
374 return Err(Error::ReferralHopLimitExceeded);
375 }
376 hops += 1;
377 referred = Some(self.connect_referral(&urls).await?);
378 }
379 other => return other,
380 }
381 }
382 }
383
384 pub fn is_connected(&self) -> bool {
385 self.session
386 .try_lock()
387 .map_or(true, |session| session.is_some())
388 }
389
390 pub async fn reconnect(&self) -> Result<(), Error> {
394 {
395 let mut last = self.last_reconnect.lock().await;
396 if let Some(prev) = *last {
397 let elapsed = prev.elapsed();
398 if elapsed < MIN_RECONNECT_INTERVAL {
399 tokio::time::sleep(MIN_RECONNECT_INTERVAL - elapsed).await;
400 }
401 }
402 *last = Some(tokio::time::Instant::now());
403 }
404
405 let session = Session::open(&self.params, &self.settings.unsolicited_handler).await?;
406 *self.session.lock().await = Some(session);
407
408 if self.settings.service_account.is_some()
409 && let Err(e) = self.rebind_service_account().await
410 {
411 self.session.lock().await.take();
412 return Err(e);
413 }
414 Ok(())
415 }
416
417 pub async fn rebind_service_account(&self) -> Result<(), Error> {
418 let account = self.settings.service_account.as_ref().ok_or_else(|| {
419 Error::Proto(ProtoError::Protocol("no service account configured".into()))
420 })?;
421 self.simple_bind(&account.dn, &account.password).await
422 }
423
424 pub async fn simple_bind(
425 &self,
426 dn: impl Into<String>,
427 password: &SecretString,
428 ) -> Result<(), Error> {
429 let request = simple_bind_request(dn.into(), password)?;
430 if self.params.security.transport() == Transport::Plain {
431 tracing::warn!(
432 "simple bind over plain (unencrypted) connection; credentials are sent in cleartext"
433 );
434 }
435 self.exchange(&request, Vec::new()).await
436 }
437
438 pub async fn sasl_external_bind(&self) -> Result<(), Error> {
439 let request = BindRequest {
440 version: 3,
441 name: String::new(),
442 authentication: BindAuthentication::Sasl {
443 mechanism: "EXTERNAL".into(),
444 credentials: None,
445 },
446 };
447 self.exchange(&request, Vec::new()).await
448 }
449
450 pub async fn bind(&self, credentials: BindCredentials<'_>) -> Result<(), Error> {
452 match credentials {
453 BindCredentials::Simple { dn, password } => self.simple_bind(dn, password).await,
454 BindCredentials::ServiceAccount => self.rebind_service_account().await,
455 BindCredentials::SaslExternal => self.sasl_external_bind().await,
456 }
457 }
458
459 pub async fn unbind(&self) -> Result<(), Error> {
461 let mut slot = self.session.lock().await;
462 let mut session = slot.take().ok_or(Error::ConnectionClosed)?;
463 session
464 .send(ldap_client_proto::LdapOperation::UnbindRequest, Vec::new())
465 .await?;
466 Ok(())
467 }
468
469 pub async fn search(
471 &self,
472 base_dn: impl Into<String>,
473 scope: SearchScope,
474 filter: Filter,
475 attrs: Vec<String>,
476 ) -> Result<Vec<SearchResultEntry>, Error> {
477 let params = SearchParams::from_legacy(base_dn.into(), scope, filter, attrs);
478 Ok(self.search_with(params).await?.entries)
479 }
480
481 pub async fn search_with_controls(
482 &self,
483 base_dn: impl Into<String>,
484 scope: SearchScope,
485 filter: Filter,
486 attrs: Vec<String>,
487 controls: Vec<Control>,
488 ) -> Result<(Vec<SearchResultEntry>, Vec<Control>), Error> {
489 let result = self
490 .search_full(base_dn, scope, filter, attrs, controls)
491 .await?;
492 Ok((result.entries, result.controls))
493 }
494
495 pub async fn search_full(
496 &self,
497 base_dn: impl Into<String>,
498 scope: SearchScope,
499 filter: Filter,
500 attrs: Vec<String>,
501 controls: Vec<Control>,
502 ) -> Result<SearchResult, Error> {
503 let params =
504 SearchParams::from_legacy(base_dn.into(), scope, filter, attrs).controls(controls);
505 self.search_with(params).await
506 }
507
508 pub async fn search_paged(
509 &self,
510 base_dn: &str,
511 scope: SearchScope,
512 filter: Filter,
513 attrs: Vec<String>,
514 page_size: i32,
515 ) -> Result<Vec<SearchResultEntry>, Error> {
516 let mut pages = self.search_paged_stream(base_dn, scope, filter, attrs, page_size);
517 let mut entries = Vec::new();
518 while let Some(page) = pages.next_page().await? {
519 entries.extend(page);
520 if entries.len() > MAX_SEARCH_ENTRIES {
521 return Err(Error::SearchEntryLimitExceeded(MAX_SEARCH_ENTRIES));
522 }
523 }
524 Ok(entries)
525 }
526
527 pub fn search_paged_stream(
528 &self,
529 base_dn: &str,
530 scope: SearchScope,
531 filter: Filter,
532 attrs: Vec<String>,
533 page_size: i32,
534 ) -> PagedSearch<'_> {
535 let params = SearchParams::from_legacy(base_dn.to_owned(), scope, filter, attrs);
536 PagedSearch::new(self, params, page_size)
537 }
538
539 pub async fn search_one(
540 &self,
541 base_dn: impl Into<String>,
542 scope: SearchScope,
543 filter: Filter,
544 attrs: Vec<String>,
545 ) -> Result<Option<SearchResultEntry>, Error> {
546 let params = SearchParams::from_legacy(base_dn.into(), scope, filter, attrs)
547 .size_limit(SEARCH_ONE_SIZE_LIMIT)
548 .time_limit(self.params.request_timeout);
549
550 let entries = match self.search_with(params).await {
553 Ok(result) => result.entries,
554 Err(Error::Ldap {
555 code: ldap_client_proto::ResultCode::SizeLimitExceeded,
556 ..
557 }) => {
558 return Err(Error::MultipleResults);
559 }
560 Err(e) => return Err(e),
561 };
562
563 let mut entries = entries.into_iter();
564 match (entries.next(), entries.next()) {
565 (None, _) => Ok(None),
566 (Some(entry), None) => Ok(Some(entry)),
567 (Some(_), Some(_)) => Err(Error::MultipleResults),
568 }
569 }
570
571 pub async fn root_dse(&self) -> Result<SearchResultEntry, Error> {
572 let params = SearchParams::new("", SearchScope::BaseObject, Filter::present("objectClass"))
573 .attributes(["*", "+"]);
574 let result = self.search_with(params).await?;
575 result
576 .entries
577 .into_iter()
578 .next()
579 .ok_or_else(|| Error::Proto(ProtoError::Protocol("root DSE not found".into())))
580 }
581
582 pub async fn search_range(
589 &self,
590 base_dn: &str,
591 filter: Filter,
592 attr: &str,
593 ) -> Result<Vec<Vec<u8>>, Error> {
594 const MAX_RANGE_ROUNDS: usize = 100_000;
595 let mut all_values: Vec<Vec<u8>> = Vec::new();
596 let mut range_start: u32 = 0;
597
598 for _ in 0..MAX_RANGE_ROUNDS {
599 let range_attr = format!("{attr};range={range_start}-*");
600 let entries = self
601 .search(
602 base_dn,
603 SearchScope::BaseObject,
604 filter.clone(),
605 vec![range_attr],
606 )
607 .await?;
608
609 let entry = match entries.into_iter().next() {
610 Some(e) => e,
611 None => break,
612 };
613
614 let mut found = false;
616 for pa in &entry.attributes {
617 if let Some((base, _start, end)) = parse_range_option(&pa.name)
618 && base.eq_ignore_ascii_case(attr)
619 {
620 all_values.extend(pa.values.iter().cloned());
621 found = true;
622 match end {
623 None => {
624 return Ok(all_values);
626 }
627 Some(e) => {
628 let next = e.saturating_add(1);
629 if next <= range_start {
630 return Ok(all_values);
632 }
633 range_start = next;
634 }
635 }
636 }
637 }
638 if !found {
639 for pa in entry.attributes {
642 let base = pa.name.split(';').next().unwrap_or(&pa.name);
643 if base.eq_ignore_ascii_case(attr) {
644 all_values.extend(pa.values);
645 }
646 }
647 break;
648 }
649 }
650
651 Ok(all_values)
652 }
653
654 pub async fn add(
655 &self,
656 dn: impl Into<String>,
657 attrs: Vec<ldap_client_proto::PartialAttribute>,
658 ) -> Result<(), Error> {
659 let request = AddRequest {
660 dn: dn.into(),
661 attributes: attrs,
662 };
663 self.execute(request, Vec::new()).await
664 }
665
666 pub async fn modify(
667 &self,
668 dn: impl Into<String>,
669 changes: Vec<ldap_client_proto::Modification>,
670 ) -> Result<(), Error> {
671 let request = ModifyRequest {
672 dn: dn.into(),
673 changes,
674 };
675 self.execute(request, Vec::new()).await
676 }
677
678 pub async fn delete(&self, dn: impl Into<String>) -> Result<(), Error> {
679 self.execute(Delete(dn.into()), Vec::new()).await
680 }
681
682 pub async fn compare(
683 &self,
684 dn: impl Into<String>,
685 attr: impl Into<String>,
686 value: impl AsRef<[u8]>,
687 ) -> Result<bool, Error> {
688 let request = CompareRequest {
689 dn: dn.into(),
690 attr: attr.into(),
691 value: value.as_ref().to_vec(),
692 };
693 self.execute(request, Vec::new()).await
694 }
695
696 pub async fn modify_dn(
697 &self,
698 dn: impl Into<String>,
699 new_rdn: impl Into<String>,
700 delete_old_rdn: bool,
701 new_superior: Option<String>,
702 ) -> Result<(), Error> {
703 let request = ModifyDnRequest {
704 dn: dn.into(),
705 new_rdn: new_rdn.into(),
706 delete_old_rdn,
707 new_superior,
708 };
709 self.execute(request, Vec::new()).await
710 }
711
712 pub async fn extended(
715 &self,
716 oid: impl Into<String>,
717 value: Option<Vec<u8>>,
718 ) -> Result<ExtendedResponse, Error> {
719 let oid = oid.into();
720 if oid == STARTTLS_OID {
721 return Err(Error::StartTls(
722 "StartTLS is negotiated at connect time; use Transport::StartTls".into(),
723 ));
724 }
725 self.execute(ExtendedRequest { oid, value }, Vec::new())
726 .await
727 }
728
729 pub async fn who_am_i(&self) -> Result<Option<String>, Error> {
730 let resp = self.extended(WHO_AM_I_OID, None).await?;
731 Ok(resp.value.map(|v| String::from_utf8_lossy(&v).into_owned()))
732 }
733
734 async fn connect_referral(&self, urls: &[String]) -> Result<Client, Error> {
741 let mut last_err = None;
742 for raw_url in urls {
743 let Ok(url) = LdapUrl::parse(raw_url) else {
744 continue;
745 };
746 let transport = Transport::from(url.scheme);
747 if self.params.security.transport() != Transport::Plain && transport == Transport::Plain
748 {
749 debug!(url = %raw_url, "skipping referral that would downgrade from TLS to plain");
750 continue;
751 }
752 match self.open_referral(&url, transport).await {
753 Ok(client) => return Ok(client),
754 Err(e) => last_err = Some(e),
755 }
756 }
757
758 Err(last_err.unwrap_or(Error::InvalidUrl("no valid referral URLs".into())))
759 }
760
761 async fn open_referral(&self, url: &LdapUrl, transport: Transport) -> Result<Client, Error> {
762 let params = ConnectParams {
763 host: url.host.clone(),
764 port: url.effective_port(),
765 security: Security::new(transport, &url.host)?,
766 ..self.params.clone()
767 };
768 let session = Session::open(¶ms, &self.settings.unsolicited_handler).await?;
769 let settings = Settings {
770 base_dn: None,
771 service_account: match self.settings.referral_credentials {
772 ReferralCredentials::ServiceAccount => self.settings.service_account.clone(),
773 ReferralCredentials::Anonymous => None,
774 },
775 referral_policy: ReferralPolicy::Return,
776 referral_credentials: ReferralCredentials::Anonymous,
777 unsolicited_handler: self.settings.unsolicited_handler.clone(),
778 };
779 let client = Client::new(session, params, settings);
780 if client.settings.service_account.is_some() {
781 client.rebind_service_account().await?;
782 }
783 Ok(client)
784 }
785}
786
787pub fn parse_range_option(attr_name: &str) -> Option<(&str, u32, Option<u32>)> {
792 let base = attr_name.split(';').next().unwrap_or(attr_name);
793 let range_part = attr_name
794 .split(';')
795 .find_map(|part| part.strip_prefix("range="))?;
796 let (start_s, end_s) = range_part.split_once('-')?;
797 let start: u32 = start_s.parse().ok()?;
798 let end = if end_s == "*" {
799 None
800 } else {
801 Some(end_s.parse().ok()?)
802 };
803 Some((base, start, end))
804}