simple-ldap 9.0.0

A high-level LDAP client for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! # Test cases
//!
//! Integration test cases using a plain `LdapClient`,
//! or really something that dereferences into it.
//!
//! The functions in this file are basically test bodies, and cannot be run directly.
//! They should be called from other testing modules.
//! The point of this is to allow running the same test cases with and without pooling.
//!
//! **All the test cases in this file should be run with and without pooling!**
//! Pay attention to this especially when adding tests cases.
//!
//!
//! ## Idempotence
//!
//! Tests in this file should be **idempotent.**
//! I.e. running the test twice against the same LDAP server should yield identical test results.
//!
//! This is needed for the above mentioned running of same tests with and without pooling.
//!
//! It's enough to satisfy this requirement probabilistically e.g. by using random names
//! that are unlikely to collide.
//!
//!
//! ## Parallelism
//!
//! The tests need to be able run in parallel. This includes multiple instances of the same test.
//! This is required when running these with a pool.
//!
//! In practice this mostly follows from idempotency.
//!
//!
//! ## DerefMut
//!
//! The test case functions don't create LdapClients themselves, but take them from outside
//! as `DerefMut<Target = LdapClient>`. This way we can utilize the same test cases with
//! pooled and plain clients.
//!
//! When calling these with plain `LdapClient`, wrap it in a `Box`.

use anyhow::anyhow;
use futures::{StreamExt, TryStreamExt};
use itertools::Itertools;
use rand::RngExt;
use serde::Deserialize;
use std::{collections::HashSet, num::{NonZero, NonZeroU16}, ops::DerefMut, str::FromStr, sync::Once};
use tracing::Level;
use tracing_subscriber::fmt::format::FmtSpan;
use url::Url;
use uuid::Uuid;

use simple_ldap::{
    Error, LdapClient, LdapConfig, SimpleDN, SortBy,
    filter::{ContainsFilter, EqFilter},
    ldap3::{Mod, Scope},
};

pub async fn test_create_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let uid = random_uid();
    let data = vec![
        (
            "objectClass",
            HashSet::from(["organizationalPerson", "inetorgperson", "top", "person"]),
        ),
        ("uid", HashSet::from([uid.as_str()])),
        ("cn", HashSet::from(["Kasun"])),
        ("sn", HashSet::from(["Ranasingh"])),
    ];

    client
        .create(uid.as_str(), "ou=people,dc=example,dc=com", data)
        .await?;

    Ok(())
}

#[derive(Debug, Deserialize)]
pub struct User {
    pub dn: SimpleDN,
    pub uid: String,
    pub cn: String,
    pub sn: String,
}

#[derive(Deserialize)]
pub struct MultiValueUser {
    #[expect(dead_code, reason = "Having this here will still test the deserialization.")]
    pub dn: SimpleDN,
    #[serde(rename = "objectClass")]
    pub object_class: Vec<String>,
    pub uid: Vec<String>,
}

pub async fn test_search_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let name_filter = EqFilter::from("cn".to_string(), "Sam".to_string());
    let user: Result<User, Error> = client
        .search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            vec!["cn", "sn", "uid"],
        )
        .await;

    let user = user.unwrap();

    let dn =
        SimpleDN::from_str("uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com")?;

    assert_eq!(user.cn, "Sam");
    assert_eq!(user.sn, "Smith");
    assert_eq!(user.dn, dn);

    Ok(())
}

pub async fn test_search_multi_valued<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let filter = EqFilter::from(
        "uid".to_string(),
        "f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5".to_string(),
    );
    let attributes = vec!["objectClass", "uid"];
    let user: MultiValueUser = client
        .search_multi_valued(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &filter,
            &attributes,
        )
        .await?;

    assert_eq!(
        user.uid,
        vec![String::from("f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5")]
    );
    assert!(user.object_class.contains(&String::from("inetorgperson")));
    assert!(
        user.object_class
            .contains(&String::from("organizationalPerson"))
    );

    Ok(())
}

pub async fn test_search_no_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let name_filter = EqFilter::from("cn".to_string(), "SamX".to_string());
    let user: Result<User, Error> = client
        .search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &vec!["cn", "sn", "uid"],
        )
        .await;
    assert!(user.is_err());
    let er = user.err().unwrap();
    match er {
        Error::NotFound(_) => Ok(()),
        _ => Err(anyhow!("Unexpected error")),
    }
}

pub async fn test_search_multiple_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let name_filter = EqFilter::from("cn".to_string(), "James".to_string());
    let user: Result<User, Error> = client
        .search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &vec!["cn", "sn", "uid"],
        )
        .await;
    assert!(user.is_err());
    let er = user.err().unwrap();
    match er {
        Error::MultipleResults(_) => Ok(()),
        _ => Err(anyhow!("Unexpected error")),
    }
}

pub async fn test_update_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let data = vec![
        Mod::Replace("cn", HashSet::from(["Jhon_Update"])),
        Mod::Replace("sn", HashSet::from(["Eliet_Update"])),
    ];
    client
        .update(
            "e219fbc0-6df5-4bc3-a6ee-986843bb157e",
            "ou=people,dc=example,dc=com",
            data,
            Option::None,
        )
        .await?;

    Ok(())
}

pub async fn test_update_no_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let data = vec![
        Mod::Replace("cn", HashSet::from(["Jhon_Update"])),
        Mod::Replace("sn", HashSet::from(["Eliet_Update"])),
    ];
    let result = client
        .update(
            "032a26b4-9f00-4a29-99c8-15d463a29290",
            "ou=people,dc=example,dc=com",
            data,
            Option::None,
        )
        .await;
    assert!(result.is_err());
    let er = result.err().unwrap();
    match er {
        Error::NotFound(_) => Ok(()),
        _ => Err(anyhow!("Unexpected error")),
    }
}

pub async fn test_update_uid_record<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // First create a user to update.
    // A create_user method would be nice.. 🤔
    let original_uid = random_uid();
    let data = vec![
        (
            "objectClass",
            HashSet::from(["organizationalPerson", "inetorgperson", "top", "person"]),
        ),
        ("uid", HashSet::from([original_uid.as_str()])),
        ("cn", HashSet::from(["Update"])),
        ("sn", HashSet::from(["Me"])),
    ];

    let base = String::from("ou=people,dc=example,dc=com");

    client
        .create(original_uid.as_str(), base.as_str(), data)
        .await?;

    let new_cn = "I'm";
    let new_sn = "Updated";

    let data = vec![
        Mod::Replace("cn", HashSet::from([new_cn])),
        Mod::Replace("sn", HashSet::from([new_sn])),
    ];
    let new_uid = random_uid();

    // This is the call we're testing.
    client
        .update(
            original_uid.as_str(),
            base.as_str(),
            data,
            Option::Some(new_uid.as_str()),
        )
        .await?;

    let name_filter = EqFilter::from("uid".to_string(), new_uid);
    let user: User = client
        .search(
            base.as_str(),
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &vec!["cn", "sn", "uid"],
        )
        .await?;

    assert_eq!(user.cn, new_cn);
    assert_eq!(user.sn, new_sn);

    Ok(())
}

pub async fn streaming_search<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let name_filter = EqFilter::from("cn".to_string(), "James".to_string());
    let attra = vec!["cn", "sn", "uid"];
    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attra,
            None,
            Vec::new()
        )
        .await?;

    let mut pinned_stream = Box::pin(stream);

    let mut count = 0;
    while let Some(record) = pinned_stream.next().await {
        match record {
            Ok(record) => {
                let _ = record.to_record::<User>().unwrap();
                count += 1;
            }
            Err(_) => {
                break;
            }
        }
    }

    assert!(count == 2);

    Ok(())
}

// Can be used as an example value where one is needed.
// Shouldn't be too big so that the searches actually get more than one page.
const PAGE_SIZE: NonZeroU16 = NonZero::new(2).unwrap();

pub async fn streaming_search_paged<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // enable_tracing_subscriber();

    let name_filter = ContainsFilter::from("cn".to_string(), "J".to_string());
    let attributes = vec!["cn", "sn", "uid"];
    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            // Testing with a pagesize smaller than the result set so that we actually see
            // multiple pages.
            Some(PAGE_SIZE),
            Vec::new(),
        )
        .await?;

    let count = stream
        .and_then(async |record| record.to_record())
        .try_fold(0, async |sum, _: User| Ok(sum + 1))
        .await?;

    assert_eq!(count, 3);

    Ok(())
}

pub async fn sorted_paged_search<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // enable_tracing_subscriber();

    // Getting all the users.
    let name_filter = EqFilter::from("objectClass".to_string(), "person".to_string());
    let attributes = vec!["cn", "sn", "uid"];
    let cn_sort = vec![SortBy {
        attribute: "cn".to_owned(),
        reverse: false,
    }];

    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            // Testing with a pagesize smaller than the result set so that we actually see
            // multiple pages.
            Some(PAGE_SIZE),
            cn_sort,
        )
        .await?;

    let results: Vec<User> = stream
        .and_then(async |record| record.to_record())
        .try_collect()
        .await?;

    // Just a bit of debugging.
    println!(
        "Results sorted by CN: {:?}",
        results.iter().map(|User { cn, .. }| cn).format(", ")
    );

    assert!(!results.is_empty());
    assert!(results.is_sorted_by_key(|User { cn, .. }| cn.to_owned()));

    // And then another sort attribute just to rule out chance.

    let sn_sort = vec![SortBy {
        attribute: "sn".to_owned(),
        reverse: false,
    }];

    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            // Testing with a pagesize smaller than the result set so that we actually see
            // multiple pages.
            Some(PAGE_SIZE),
            sn_sort,
        )
        .await?;

    let results: Vec<User> = stream
        .and_then(async |record| record.to_record())
        .try_collect()
        .await?;

    // Just a bit of debugging.
    println!(
        "Results sorted by SN: {:?}",
        results.iter().map(|User { sn, .. }| sn).format(", ")
    );

    assert!(!results.is_empty());
    assert!(results.is_sorted_by_key(|User { sn, .. }| sn.to_owned()));

    Ok(())
}

pub async fn sorted_paged_search_reverse<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // enable_tracing_subscriber();

    // Getting all the users.
    let name_filter = EqFilter::from("objectClass".to_string(), "person".to_string());
    let attributes = vec!["cn", "sn", "uid"];
    let sort = vec![SortBy {
        attribute: "cn".to_owned(),
        // This is the key bit in this test.
        reverse: true,
    }];

    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            // Testing with a pagesize smaller than the result set so that we actually see
            // multiple pages.
            Some(PAGE_SIZE),
            sort,
        )
        .await?;

    let results: Vec<User> = stream
        .and_then(async |record| record.to_record())
        .try_collect()
        .await?;

    // Just a bit of debugging.
    println!(
        "Results: {:?}",
        results.iter().map(|User { cn, .. }| cn).format(", ")
    );

    assert!(!results.is_empty());

    let reversed_results = results.into_iter().rev();
    assert!(reversed_results.is_sorted_by_key(|User { cn, .. }| cn.to_owned()));

    Ok(())
}

pub async fn test_search_stream_drop<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // Here we always want to trace.
    // enable_tracing_subscriber();

    let name_filter = ContainsFilter::from("cn".to_string(), "J".to_string());
    let attributes = vec!["cn", "sn", "uid"];
    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            // Testing with a pagesize smaller than the result set so that we actually see
            // multiple pages. Expecting 3 in total.
            Some(PAGE_SIZE),
            Vec::new(),
        )
        .await?;

    let mut pinned_stream = Box::pin(stream);

    // Get one element from the stream.
    pinned_stream.try_next().await?;

    // Then just let it drop.
    // This won't actually ever fail, but you can see the tracing log that no errors occurred.
    Ok(())
}

pub async fn test_streaming_search_no_records<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    enable_tracing_subscriber();

    let name_filter = EqFilter::from("cn".to_string(), "JamesX".to_string());
    let attributes = vec!["cn", "sn", "uid"];
    let stream = client
        .streaming_search(
            "ou=people,dc=example,dc=com",
            simple_ldap::ldap3::Scope::OneLevel,
            &name_filter,
            &attributes,
            None,
            Vec::new()
        )
        .await?;

    let count = stream
        .and_then(async |record| record.to_record())
        .try_fold(0, async |sum, _: User| Ok(sum + 1))
        .await?;

    assert_eq!(count, 0);

    Ok(())
}

pub async fn test_delete<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // First create a user to delete.
    // A create_user method would be nice.. 🤔
    let uid = random_uid();
    let data = vec![
        (
            "objectClass",
            HashSet::from(["organizationalPerson", "inetorgperson", "top", "person"]),
        ),
        ("uid", HashSet::from([uid.as_str()])),
        ("cn", HashSet::from(["Delete"])),
        ("sn", HashSet::from(["Me"])),
    ];

    let base = String::from("ou=people,dc=example,dc=com");

    client.create(uid.as_str(), base.as_str(), data).await?;

    // This is what we are really testing.
    client.delete(uid.as_str(), base.as_str()).await?;

    Ok(())
}

pub async fn test_no_record_delete<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let result = client
        .delete(
            "4d9b08fe-9a14-4df0-9831-ea9992837f0x",
            "ou=people,dc=example,dc=com",
        )
        .await;
    assert!(result.is_err());
    let er = result.err().unwrap();
    match er {
        Error::NotFound(_) => Ok(()),
        _ => Err(anyhow!("Unknown error")),
    }
}

pub async fn test_create_group<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let name = append_random_id("test_group");
    client
        .create_group(name.as_str(), "dc=example,dc=com", "Some Description")
        .await?;

    Ok(())
}

pub async fn test_add_users_to_group<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let group_name = append_random_id("user_add_test_group");
    let group_dn = format!("cn={group_name},dc=example,dc=com");

    client
        .create_group(group_name.as_str(), "dc=example,dc=com", "Some Decription")
        .await?;

    client
        .add_users_to_group(
            vec![
                "uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
                "uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
            ],
            group_dn.as_str(),
        )
        .await?;

    // Could check here that they are actually in the group.

    Ok(())
}

pub async fn test_get_members<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // Let's first prepare a group.

    let group_name = append_random_id("get_members_group");
    let group_ou = String::from("dc=example,dc=com");
    let group_dn = format!("cn={group_name},{group_ou}");

    client
        .create_group(group_name.as_str(), group_ou.as_str(), "Some Decription 2")
        .await?;

    client
        .add_users_to_group(
            vec![
                "uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
                "uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
            ],
            group_dn.as_str(),
        )
        .await?;

    // This is what we are testing.
    let users: Vec<User> = client
        .get_members(
            group_dn.as_str(),
            group_ou.as_str(),
            Scope::Subtree,
            &vec!["cn", "sn", "uid"],
        )
        .await?;

    assert_eq!(users.len(), 2);
    let user_count = users
        .iter()
        .filter(|user| {
            user.uid == "f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5"
                || user.uid == "e219fbc0-6df5-4bc3-a6ee-986843bb157e"
        })
        .count();
    assert_eq!(user_count, 2);

    Ok(())
}

pub async fn test_remove_users_from_group<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    // Let's first prepare a group.

    let group_name = append_random_id("get_members_group");
    let group_ou = String::from("dc=example,dc=com");
    let group_dn = format!("cn={group_name},{group_ou}");

    client
        .create_group(group_name.as_str(), group_ou.as_str(), "Some Decription 2")
        .await?;

    client
        .add_users_to_group(
            vec![
                "uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
                "uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
            ],
            group_dn.as_str(),
        )
        .await?;

    // This is what we are testing here.
    client
        .remove_users_from_group(
            group_dn.as_str(),
            vec![
                "uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
                "uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
            ],
        )
        .await?;

    // Currently the library doesn't seem to able to handle empty groups so the
    // verification below is commented out.

    // let users = client
    //     .get_members::<User>(
    //         group_dn.as_str(),
    //         group_ou.as_str(),
    //         Scope::Subtree,
    //         &vec!["cn", "sn", "uid"],
    //     )
    //     .await?;

    // assert!(users.is_empty(), "The users weren't removed from the group.");

    Ok(())
}

pub async fn test_associated_groups<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let result = client
        .get_associtated_groups(
            "ou=group,dc=example,dc=com",
            "uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
        )
        .await?;

    assert_eq!(result.len(), 2);

    Ok(())
}

pub async fn test_authenticate_success<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let uid = random_uid();
    let password = format!("secret-{uid}");
    let base = "ou=people,dc=example,dc=com";

    let data = vec![
        (
            "objectClass",
            HashSet::from(["organizationalPerson", "inetorgperson", "top", "person"]),
        ),
        ("uid", HashSet::from([uid.as_str()])),
        ("cn", HashSet::from(["Auth"])),
        ("sn", HashSet::from(["Tester"])),
        ("userPassword", HashSet::from([password.as_str()])),
    ];

    client.create(uid.as_str(), base, data).await?;

    let filter = EqFilter::from("uid".to_string(), uid.clone());
    let auth_result = client
        .authenticate(base, uid.as_str(), password.as_str(), Box::new(filter))
        .await;

    client.delete(uid.as_str(), base).await?;

    auth_result?;

    Ok(())
}

pub async fn test_authenticate_wrong_password<Client: DerefMut<Target = LdapClient>>(
    mut client: Client,
) -> anyhow::Result<()> {
    let uid = random_uid();
    let password = format!("secret-{uid}");
    let base = "ou=people,dc=example,dc=com";

    let data = vec![
        (
            "objectClass",
            HashSet::from(["organizationalPerson", "inetorgperson", "top", "person"]),
        ),
        ("uid", HashSet::from([uid.as_str()])),
        ("cn", HashSet::from(["Auth"])),
        ("sn", HashSet::from(["Tester"])),
        ("userPassword", HashSet::from([password.as_str()])),
    ];

    client.create(uid.as_str(), base, data).await?;

    let filter = EqFilter::from("uid".to_string(), uid.clone());
    let auth_result = client
        .authenticate(base, uid.as_str(), "definitely-wrong", Box::new(filter))
        .await;

    client.delete(uid.as_str(), base).await?;

    match auth_result {
        Err(Error::AuthenticationFailed(_)) => Ok(()),
        Err(other) => Err(anyhow!("Unexpected error: {other:?}")),
        Ok(_) => Err(anyhow!("Authentication succeeded unexpectedly")),
    }
}

/***************
 *  Utilities  *
 ***************/

// Some of these utilities are even public because of cargo's test module limitations.

/// Can be used to generate random names for things to avoid clashes.
fn append_random_id(beginning: &str) -> String {
    let mut rng = rand::rng();
    // A few in milliard are plenty unlikely to collide.
    let random_id: u32 = rng.random_range(0..1000000000);
    format!("{beginning} {random_id}")
}

/// Generate a random LDAP compatible uid and return it's string representation.
fn random_uid() -> String {
    // v4 is random.
    Uuid::new_v4()
        .as_hyphenated()
        // No idea whether LDAP actually cares about the case?
        .encode_lower(&mut Uuid::encode_buffer())
        .to_owned()
}

/// Get ldap configuration for conneting to the test server.
pub fn ldap_config() -> anyhow::Result<LdapConfig> {
    let config = LdapConfig {
        bind_dn: String::from("cn=manager"),
        bind_password: String::from("password"),
        ldap_url: Url::parse("ldap://localhost:1389/dc=example,dc=com")?,
        dn_attribute: None,
        connection_settings: None,
    };

    Ok(config)
}

/// Print out traces in tests.
///
/// It's perhaps best not to overuse this, as it's quite verbose.
/// You can add it to the start of test you wish to investigate.
fn enable_tracing_subscriber() {
    static ONCE: Once = Once::new();

    // Tests are run in parallel and might try to set the subscriber multiple times.
    ONCE.call_once(|| {
        tracing_subscriber::fmt()
            .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
            .with_max_level(Level::TRACE)
            .init();
    });
}