ldap-test-server 0.1.2

Running isolated OpenLDAP servers in integration tests
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
use crate::LdapServerConn;
use rand::Rng;
use random_port::{PortPicker, Protocol};
use rcgen::{CertificateParams, KeyPair, SanType};
use std::net::{IpAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::str::FromStr;
use std::time::Duration;
use tempfile::tempdir;
use tokio::fs;
use tokio::io::AsyncBufReadExt;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::time::{sleep, timeout};
use tracing::debug;
use url::Url;

const INIT_LDIF: &str = include_str!("init.ldif");
const POSSIBLE_SCHEMA_DIR: &[&str] = &[
    "/etc/ldap/schema",
    "/usr/local/etc/openldap/schema",
    "/etc/openldap/schema/",
];

#[derive(Debug)]
enum LdapFile {
    SystemSchema(PathBuf),
    File { template: bool, file: PathBuf },
    Text { template: bool, content: String },
}

/// LDAP server builder
#[derive(Debug)]
pub struct LdapServerBuilder {
    base_dn: String,
    root_dn: String,
    root_pw: String,
    bind_addr: Option<String>,
    port: Option<u16>,
    ssl_port: Option<u16>,
    includes: Vec<(u8, LdapFile)>,
    ssl_cert_key: Option<(String, String)>,
}

impl LdapServerBuilder {
    /// Init empty builder
    pub fn empty(
        base_dn: impl Into<String>,
        root_dn: impl Into<String>,
        root_pw: impl Into<String>,
    ) -> Self {
        let base_dn = base_dn.into();
        let root_dn = root_dn.into();
        let root_pw = root_pw.into();

        Self {
            base_dn,
            root_dn,
            root_pw,
            bind_addr: None,
            port: None,
            ssl_port: None,
            includes: vec![],
            ssl_cert_key: None,
        }
    }

    /// Init builder with simple database
    pub fn new(base_dn: &str) -> Self {
        let root_dn = format!("cn=admin,{base_dn}");
        let root_pw = "secret".to_string();
        LdapServerBuilder::empty(base_dn, root_dn, root_pw).add_template(0, INIT_LDIF)
    }

    /// Use existing ssl certificate and key PEM
    pub fn ssl_certificates(mut self, certificate: String, key: String) -> Self {
        self.ssl_cert_key = Some((certificate, key));
        self
    }

    /// Listen address
    pub fn bind_addr(mut self, bind_addr: &str) -> Self {
        self.bind_addr = Some(bind_addr.to_string());
        self
    }

    /// Listen port
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Listen SSL port
    pub fn ssl_port(mut self, port: u16) -> Self {
        self.ssl_port = Some(port);
        self
    }

    /// Add system LDIF from schema dir installed by slapd (usually in /etc/ldap/schema directory)
    ///
    /// # Examples
    ///
    /// ```
    /// use ldap_test_server::LdapServerBuilder;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let server = LdapServerBuilder::new("dc=planetexpress,dc=com")
    ///     .add_system_file(0, "collective.ldif")
    ///     .run().await;
    /// # }
    /// ```
    pub fn add_system_file<P: AsRef<Path>>(mut self, dbnum: u8, file: P) -> Self {
        self.includes
            .push((dbnum, LdapFile::SystemSchema(file.as_ref().to_path_buf())));
        self
    }

    /// Add LDIF file with text content
    ///
    /// # Examples
    ///
    /// ```
    /// use ldap_test_server::LdapServerBuilder;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let server = LdapServerBuilder::new("dc=planetexpress,dc=com")
    ///     .add(0, "dn: cn=user,cn=schema,cn=config
    /// objectClass: olcSchemaConfig
    /// cn: user
    /// olcAttributeTypes: ( 1.2.840.113556.4.221
    ///   NAME 'sAMAccountName'
    ///   SYNTAX '1.3.6.1.4.1.1466.115.121.1.15'
    ///   EQUALITY caseIgnoreMatch
    ///   SUBSTR caseIgnoreSubstringsMatch
    ///   SINGLE-VALUE )
    /// olcObjectClasses: ( 1.2.840.113556.1.5.9
    ///   NAME 'user'
    ///   SUP top
    ///   AUXILIARY
    ///   MAY ( sAMAccountName ))")
    ///     .run().await;
    /// # }
    /// ```
    pub fn add(mut self, dbnum: u8, content: &str) -> Self {
        self.includes.push((
            dbnum,
            LdapFile::Text {
                template: false,
                content: content.to_string(),
            },
        ));
        self
    }

    /// Add LDIF file
    pub fn add_file<P: AsRef<Path>>(mut self, dbnum: u8, file: P) -> Self {
        self.includes.push((
            dbnum,
            LdapFile::File {
                template: true,
                file: file.as_ref().to_path_buf(),
            },
        ));
        self
    }

    /// Add LDIF file with text content as template
    ///
    /// # Examples
    ///
    /// ```
    /// use ldap_test_server::{LdapServerConn, LdapServerBuilder};
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let server: LdapServerConn = LdapServerBuilder::empty("dc=planetexpress,dc=com", "cn=admin,dc=planetexpress,dc=com", "secret")
    ///     .add_template(0, include_str!("init.ldif"))
    ///     .run().await;
    /// # }
    /// ```
    pub fn add_template(mut self, dbnum: u8, content: &str) -> Self {
        self.includes.push((
            dbnum,
            LdapFile::Text {
                template: true,
                content: content.to_string(),
            },
        ));
        self
    }

    /// Add LDIF file as template
    pub fn add_template_file<P: AsRef<Path>>(mut self, dbnum: u8, file: P) -> Self {
        self.includes.push((
            dbnum,
            LdapFile::File {
                template: true,
                file: file.as_ref().to_path_buf(),
            },
        ));
        self
    }

    async fn build_config(
        includes: Vec<(u8, LdapFile)>,
        work_dir: &Path,
        config_dir: &Path,
        system_schema_dir: &Path,
    ) {
        fs::create_dir(&config_dir)
            .await
            .expect("cannot create config dir");

        for (idx, (dbnum, include)) in includes.into_iter().enumerate() {
            let file = match include {
                LdapFile::SystemSchema(file) => system_schema_dir.join(file),
                LdapFile::File {
                    template: false,
                    file,
                } => file,
                LdapFile::Text {
                    template: false,
                    content,
                } => {
                    let tmp_ldif = work_dir.join(format!("tmp_{idx}.ldif"));
                    tokio::fs::write(&tmp_ldif, content).await.unwrap();
                    tmp_ldif
                }
                LdapFile::File { template: true, .. } | LdapFile::Text { template: true, .. } => {
                    panic!("Templates should be already built");
                }
            };

            LdapServerBuilder::load_ldif(config_dir, dbnum, file).await;
        }
    }

    async fn load_ldif(config_dir: &Path, dbnum: u8, file: PathBuf) {
        debug!("slapadd dbnum: {dbnum} file: {}", file.display());

        let db_number = dbnum.to_string();
        // load slapd configuration
        let output = Command::new("slapadd")
            .arg("-F")
            .arg(config_dir)
            .arg("-n")
            .arg(db_number)
            .arg("-l")
            .arg(&file)
            .output()
            .await
            .expect("failed to execute slapadd");

        if !output.status.success() {
            panic!(
                "slapadd command exited with error {}, stdout: {}, stderr: {} on file {}",
                output.status,
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
                file.display()
            );
        }
    }

    async fn build_templates(&mut self, system_schema_dir: &Path, work_dir: &Path) {
        let schema_dir_url = Url::from_file_path(system_schema_dir).unwrap();
        let work_dir_path = work_dir.display().to_string();

        for (_, include) in &mut self.includes {
            let content = match include {
                LdapFile::File {
                    template: true,
                    file,
                } => fs::read_to_string(file).await.unwrap(),
                LdapFile::Text {
                    template: true,
                    content,
                } => std::mem::take(content),
                _ => continue,
            };

            let new_content = content
                .replace("@SCHEMADIR@", schema_dir_url.as_ref())
                .replace("@WORKDIR@", &work_dir_path)
                .replace("@BASEDN@", &self.base_dn)
                .replace("@ROOTDN@", &self.root_dn)
                .replace("@ROOTPW@", &self.root_pw);

            *include = LdapFile::Text {
                template: false,
                content: new_content,
            };
        }
    }

    /// Create database and run LDAP server
    ///
    /// # Examples
    ///
    /// ```
    /// use ldap_test_server::{LdapServerConn, LdapServerBuilder};
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let server: LdapServerConn = LdapServerBuilder::new("dc=planetexpress,dc=com")
    ///     .run().await;
    /// # }
    /// ```
    pub async fn run(mut self) -> LdapServerConn {
        let schema_dir = find_slapd_schema_dir()
            .await
            .expect("no slapd schema directory found. Is openldap server installed?");
        let host = self
            .bind_addr
            .clone()
            .unwrap_or_else(|| "127.0.0.1".to_string());
        let port_picker = PortPicker::new()
            .host(host.clone())
            .protocol(Protocol::Tcp)
            .random(true);
        let port = self.port.unwrap_or_else(|| {
            port_picker.pick().unwrap_or_else(|_| {
                let mut rng = rand::thread_rng();
                rng.gen_range(15000..55000)
            })
        });

        let ssl_port = self.ssl_port.unwrap_or_else(|| {
            port_picker.pick().unwrap_or_else(|_| {
                let mut rng = rand::thread_rng();
                rng.gen_range(15000..55000)
            })
        });

        let url = format!("ldap://{host}:{port}");
        let ssl_url = format!("ldaps://{host}:{ssl_port}");
        let dir = tempdir().unwrap();

        let (ssl_cert_pem, ssl_key_pem) = if let Some(keys) = self.ssl_cert_key.clone() {
            keys
        } else {
            let params = if let Ok(addr) = IpAddr::from_str(&host) {
                let mut params = CertificateParams::new(vec![]).unwrap();
                params.subject_alt_names.push(SanType::IpAddress(addr));
                params
            } else {
                CertificateParams::new(vec![host.clone()]).unwrap()
            };

            let key_pair = KeyPair::generate().unwrap();
            let cert = params.self_signed(&key_pair).unwrap();
            let ssl_cert_pem = cert.pem();
            let ssl_key_pem = key_pair.serialize_pem();
            (ssl_cert_pem, ssl_key_pem)
        };

        let cert_pem = dir.path().join("cert.pem");
        fs::write(&cert_pem, &ssl_cert_pem).await.unwrap();

        let key_pem = dir.path().join("key.pem");
        fs::write(&key_pem, &ssl_key_pem).await.unwrap();

        self.build_templates(schema_dir, dir.path()).await;
        let config_dir = dir.path().join("config");
        LdapServerBuilder::build_config(self.includes, dir.path(), &config_dir, schema_dir).await;

        let urls = format!("{url} {ssl_url}");
        // launch slapd server
        let mut server = Command::new("slapd")
            .arg("-F")
            .arg(&config_dir)
            .arg("-d")
            .arg("2048")
            .arg("-h")
            .arg(&urls)
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();

        // wait until slapd server has started
        let stderr = server.stderr.take().unwrap();
        let mut lines = tokio::io::BufReader::new(stderr).lines();
        let timeouted = timeout(Duration::from_secs(60), async {
            while let Some(line) = lines.next_line().await.unwrap() {
                debug!("slapd: {line}");
                if line.ends_with("slapd starting") {
                    return true;
                }
            }
            false
        })
        .await;

        if timeouted.is_err() || timeouted == Ok(false) {
            let _ = server.kill().await;
            panic!("Failed to start slapd server: timeout");
        }

        let timeouted = timeout(Duration::from_secs(60), async {
            while !is_tcp_port_open(&host, port).await {
                debug!("tcp port {port} is not open yet, waiting...");
                sleep(Duration::from_micros(100)).await;
            }
        })
        .await;

        if timeouted.is_err() {
            let _ = server.kill().await;
            panic!("Failed to start slapd server, port {port} not open");
        }

        debug!("Started ldap server on {urls}");

        LdapServerConn {
            url,
            host,
            port,
            ssl_url,
            ssl_port,
            ssl_cert_pem,
            dir,
            base_dn: self.base_dn,
            root_dn: self.root_dn,
            root_pw: self.root_pw,
            server,
        }
    }
}

async fn find_slapd_schema_dir() -> Option<&'static Path> {
    for dir in POSSIBLE_SCHEMA_DIR {
        let dir: &Path = dir.as_ref();
        if tokio::fs::metadata(dir)
            .await
            .map(|m| m.is_dir())
            .unwrap_or(false)
        {
            return Some(dir);
        }
    }
    None
}

async fn is_tcp_port_open(host: &str, port: u16) -> bool {
    let addr = (host, port).to_socket_addrs().unwrap().next().unwrap();
    let Ok(sock) = timeout(Duration::from_secs(1), TcpStream::connect(&addr)).await else {
        return false;
    };
    sock.is_ok()
}