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
//! A type representing a simple Distinguished Name.
//!
//! E.g. "CN=Tea,OU=Leaves,OU=Are,DC=Great,DC=Org"
//!
//! The LDAP spec formally allows you to include almost anything in a DN, but these features are
//! rarely used. This simple DN representation covers the common cases, and is easy to work with.
//!

use chumsky::{
    IterParser, Parser,
    error::Rich,
    extra,
    prelude::{any, just, none_of, one_of},
};
use itertools::{EitherOrBoth, Itertools};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::{cmp::Ordering, fmt::Display, str::FromStr};
use thiserror::Error;

/// LDAP Distinguished Name
///
/// Only deals with the common DNs of the form:
/// "CN=Tea,OU=Leaves,OU=Are,DC=Great,DC=Org"
///
/// Multivalued relative DNs and unprintable characters are not supported,
/// and neither is the empty DN.
///
/// ```
/// use simple_ldap::SimpleDN;
/// use std::str::FromStr;
///
/// // Create a new DN from a string slice
/// let dn = SimpleDN::from_str("CN=hong,OU=cha,DC=tea").unwrap();
/// ```
///
/// If you do need to handle more exotic DNs, have a look at the crate [`ldap_types`](https://docs.rs/ldap-types/latest/ldap_types/basic/struct.DistinguishedName.html).
#[derive(Debug, DeserializeFromStr, SerializeDisplay, Clone, PartialEq, Eq)]
pub struct SimpleDN {
    /// The relative distinguished names of this DN.
    /// I.e. the individual key-value pairs.
    ///
    /// The ordering is that of the print representation.
    /// I.e. the leftmost element gets index 0.
    ///
    /// **Invariant: This is never empty.**
    rdns: Vec<SimpleRDN>,
}

impl Display for SimpleDN {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Just interspacing formatted rdns with commas.
        write!(f, "{}", self.rdns.iter().format(","))
    }
}

impl FromStr for SimpleDN {
    type Err = SimpleDnParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match simple_dn_parser().parse(s).into_result() {
            Ok(simple_rdn) => Ok(simple_rdn),
            Err(rich_errors) => Err(SimpleDnParseError {
                errors: rich_errors
                    .into_iter()
                    // This step gets rid of the lifetime parameters.
                    .map(|rich_err| ToString::to_string(&rich_err))
                    .collect(),
            }),
        }
    }
}

/// Partial ordering is implemented according to DN ancestry.
/// I.e. A DN being "bigger" than another means that it is the ancestor of the other.
impl PartialOrd for SimpleDN {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        let most_significant_differing_rdn = self
            .rdns
            .iter()
            .rev()
            .zip_longest(other.rdns.iter().rev())
            .find(
                |maybe_both| !matches!(maybe_both, EitherOrBoth::Both(this, that) if this == that),
            );

        match most_significant_differing_rdn {
            // There were no differences.
            None => Some(Ordering::Equal),
            Some(maybe_both) => match maybe_both {
                // DNs branch, and aren't comparable.
                EitherOrBoth::Both(_, _) => None,
                // DNs are equal, except this one is longer.
                // Thus this is a child of the other.
                EitherOrBoth::Left(_) => Some(Ordering::Less),
                EitherOrBoth::Right(_) => Some(Ordering::Greater),
            },
        }
    }
}

/// Find the "maximal" common ancestor of two DNs, if any.
/// Maximal here means that the returned DN is as long as possible.
pub fn common_ancestor(left: &SimpleDN, right: &SimpleDN) -> Option<SimpleDN> {
    let mut common_rdns = left
        .rdns
        .iter()
        .rev()
        .zip(right.rdns.iter().rev())
        .take_while(|(left, right)| left == right)
        // Doesn't matter which one we take here as they are the same.
        .map(|(left, _)| left.clone())
        .collect_vec();

    // Flip back to correct order.
    // There would probably be a way to avoid this call, but it's not that expensive.
    common_rdns.reverse();

    if common_rdns.is_empty() {
        // No common ancestry at all.
        None
    } else {
        Some(SimpleDN { rdns: common_rdns })
    }
}

fn simple_dn_parser<'src>() -> impl Parser<'src, &'src str, SimpleDN, extra::Err<Rich<'src, char>>>
{
    simple_rdn_parser()
        // Just parsing a list of RDNs.
        .separated_by(just(','))
        .collect::<Vec<SimpleRDN>>()
        .map(|rdns| SimpleDN { rdns })
}

/// Convenience operations for DNs.
impl SimpleDN {
    /// Get the value of the first occurrance of the argument RDN key.
    ///
    /// E.g. Getting "OU" from "CN=Teas,OU=Are,OU=Really,DC=Awesome" results in "Are".
    ///
    /// Probably this only makes sense in keys like "CN" that are expected to be unique.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.rdns
            .iter()
            .find(|rdn| rdn.key == key)
            .map(|rdn| rdn.value.as_str())
    }

    /// Like `get()` but returns all the RDNs starting from the asked key.
    pub fn get_starting_from(&self, key: &str) -> Option<SimpleDN> {
        self.rdns
            .iter()
            .position(|rdn| rdn.key == key)
            .map(|position| {
                let (_, tail) = self.rdns.as_slice().split_at(position);

                SimpleDN {
                    rdns: tail.to_owned(),
                }
            })
    }

    /// Get the type of this DN.
    /// The kind of object it denominates.
    /// I.e. the key of the first RDN.
    ///
    /// E.g. the type of "OU=Tea,DC=Drinker" is "OU".
    ///
    /// If you want the value too, you can follow this up with `get()`.
    pub fn get_type(&self) -> &str {
        #[allow(clippy::expect_used, reason = "Relying on struct invariant.")]
        &self
            .rdns
            .first()
            .expect("Invariant violation. SimpleDN should never be empty.")
            .key
    }

    /// Get the parent DN of this one, if there is one.
    ///
    /// E.g. The parent "OU=Puerh,DC=Tea" is "DC=Tea".
    pub fn parent(&self) -> Option<SimpleDN> {
        match self.rdns.as_slice() {
            [_, rest @ ..] if !rest.is_empty() => Some(SimpleDN {
                rdns: rest.to_owned(),
            }),
            _ => None,
        }
    }
}

/// LDAP Relative Distinguished Name
///
/// I.e. a single key-value pair like "OU=Matcha" in DN "CN=Whisk,OU=Matcha,DC=Tea".
///
/// Only deals with RDN's with a single printable key-value pair.
///
/// <https://ldapwiki.com/wiki/Wiki.jsp?page=Relative%20Distinguished%20Name>
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[display("{key}={value}")]
struct SimpleRDN {
    /// Common examples include: CN, OU, DC
    ///
    /// OIDs are not supported here.
    //  (Though we arent' doing anything to prevent them either.)
    pub key: String,
    pub value: String,
}

/// Parse a single RDN.
/// This isn't a faithfull reproduction of the LDAP spec,
/// just dealing with the common case like this:
///
/// "CN=Tea Drinker"
fn simple_rdn_parser<'src>() -> impl Parser<'src, &'src str, SimpleRDN, extra::Err<Rich<'src, char>>>
{
    let rdn_key = any()
        // This probably doesn't quite conform to the spec.
        .filter(|c: &char| c.is_ascii_alphanumeric())
        .repeated()
        .at_least(1)
        .collect::<String>()
        // Consume the delimiting equals here too.
        .then_ignore(just('='));

    // Special characters that must be escaped in DN values:
    // https://ldapwiki.com/wiki/Wiki.jsp?page=DN%20Escape%20Values
    //
    // TODO: Leading and trailing spaces also should be escaped, but they cannot be experessed here.
    let special = r##",\#+<>;"="##;

    // Escaped special character.
    // This correctly rejects escaped non-special characters, which is not allowed in LDAP.
    //
    // This does not remove the escape characters.
    // That could be a feature worth investigating, but we would need to implement
    // value escaping then too.
    // For now this at least rejects unsound escapes.
    let escaped = just('\\')
        .then(one_of(special))
        // This is needed to consolidate the different lengths of "tokens" here.
        // This parser would output tuples of charts, where as we normally output single chars.
        .to_slice();

    // Just making sure that this is not a multivalued rdn.
    // These we don't support.
    let rdn_value = none_of(special)
        // Making this char a slice too to make the or() outputs agree.
        .to_slice()
        .or(escaped)
        .repeated()
        .at_least(1)
        .to_slice()
        .map(ToString::to_string);

    // Finally combine the RDN
    rdn_key
        .then(rdn_value)
        .map(|(key, value)| SimpleRDN { key, value })
}

#[derive(Error, Debug)]
#[error("Couldn't parse DN: {:?}", self.errors)]
pub struct SimpleDnParseError {
    // Have to store these here as strings, because the actuly `Rich`
    // type has a lifetime parameter, which we don't want to propagate upwards.
    errors: Vec<String>,
}

#[cfg(test)]
mod tests {

    use super::*;
    use serde::{Deserialize, Serialize};

    static EXAMPLE_DN: &str = "CN=Yabukita,OU=Green,OU=Tea,DC=Japan";

    static EXAMPLE_DN_QUOTED: &str = "\"CN=Yabukita,OU=Green,OU=Tea,DC=Japan\"";

    /// Get a SimpleDN corresponding to `EXAMPLE_DN` above.
    fn example_simple_dn() -> SimpleDN {
        SimpleDN {
            rdns: vec![
                SimpleRDN {
                    key: String::from("CN"),
                    value: String::from("Yabukita"),
                },
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Green"),
                },
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Tea"),
                },
                SimpleRDN {
                    key: String::from("DC"),
                    value: String::from("Japan"),
                },
            ],
        }
    }

    #[test]
    fn parse_simple_rdn_ok() {
        let key = "CN";
        let value = "Tea Drinker";

        let unstructured = String::new() + key + "=" + value;

        let rdn = simple_rdn_parser()
            .parse(&unstructured)
            .into_result()
            .unwrap();

        assert_eq!(key, rdn.key);
        assert_eq!(value, rdn.value);
    }

    #[test]
    fn parse_simple_rdn_fail() {
        let key = "CN";
        let value = "Tea Drinker";

        let unstructured = String::new() + key + "=" + value + "+ANOTHER=5";

        let parse_result = simple_rdn_parser().parse(&unstructured).into_result();

        let errors = parse_result.unwrap_err();

        println!("{errors:#?}");
    }

    #[test]
    fn parse_sipmle_dn_ok() {
        let parsed_dn = simple_dn_parser().parse(EXAMPLE_DN).into_result().unwrap();

        assert_eq!(parsed_dn, example_simple_dn());
    }

    #[test]
    fn parse_complex_dn() {
        "CN=one+OTHER=two,OU=some,DC=thing"
            .parse::<SimpleDN>()
            .expect_err("Multivalued DN should be rejected.");
    }

    #[test]
    fn parse_dn_escapes() -> anyhow::Result<()> {
        let parsed = SimpleDN::from_str(r"CN=tea \+ milk \= milktea,OU=mixes,DC=odd\,domain")?;

        let expected = SimpleDN {
            rdns: vec![
                SimpleRDN {
                    key: String::from("CN"),
                    value: String::from("tea \\+ milk \\= milktea"),
                },
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("mixes"),
                },
                SimpleRDN {
                    key: String::from("DC"),
                    value: String::from("odd\\,domain"),
                },
            ],
        };

        assert_eq!(parsed, expected);

        Ok(())
    }

    #[test]
    fn dispaly_simple_dn() {
        let displayed = example_simple_dn().to_string();
        assert_eq!(displayed, EXAMPLE_DN);
    }

    /// For testing serde implementations.
    #[derive(Debug, Deserialize, Serialize)]
    #[serde(transparent)]
    struct DnStruct {
        pub dn: SimpleDN,
    }

    impl DnStruct {
        fn example() -> Self {
            DnStruct {
                dn: example_simple_dn(),
            }
        }
    }

    #[test]
    fn serialize() -> anyhow::Result<()> {
        let serialized = serde_json::to_string(&DnStruct::example())?;
        assert_eq!(serialized, EXAMPLE_DN_QUOTED);
        Ok(())
    }

    #[test]
    fn deserialize() -> anyhow::Result<()> {
        let deserialized: DnStruct = serde_json::from_str(EXAMPLE_DN_QUOTED)?;
        assert_eq!(deserialized.dn, DnStruct::example().dn);
        Ok(())
    }

    #[test]
    fn get() {
        let example_dn = example_simple_dn();

        assert_eq!(example_dn.get("OU"), Some("Green"));
        assert_eq!(example_dn.get("CN"), Some("Yabukita"));
        assert_eq!(example_dn.get("Nonsense"), None);
    }

    #[test]
    fn get_type() {
        assert_eq!(example_simple_dn().get_type(), "CN");
    }

    #[test]
    fn get_parent() {
        let parent = example_simple_dn().parent();
        let correct_parent = SimpleDN {
            rdns: vec![
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Green"),
                },
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Tea"),
                },
                SimpleRDN {
                    key: String::from("DC"),
                    value: String::from("Japan"),
                },
            ],
        };

        assert_eq!(parent, Some(correct_parent.clone()));

        let no_parents = SimpleDN {
            rdns: vec![SimpleRDN {
                key: String::from("DC"),
                value: String::from("Tea"),
            }],
        };

        assert_eq!(no_parents.parent(), None);
    }

    #[test]
    fn get_starting_from() {
        let example_dn = example_simple_dn();

        let got = example_dn.get_starting_from("OU");
        let correct = example_dn.parent();

        assert!(got.is_some());
        assert_eq!(got, correct);

        let non_existent = example_dn.get_starting_from("Coffee");
        assert_eq!(non_existent, None);
    }

    #[test]
    fn get_type_starting_from() {
        let example_dn = example_simple_dn();

        let dn_type = example_dn.get_type();
        let starting_from = example_dn.get_starting_from(dn_type);

        // This should always be true.
        assert_eq!(starting_from, Some(example_dn));
    }

    #[test]
    fn partial_compare() {
        let reflexivity = example_simple_dn().partial_cmp(&example_simple_dn());
        assert_eq!(reflexivity, Some(Ordering::Equal));

        let great = SimpleDN {
            rdns: vec![SimpleRDN {
                key: String::from("DC"),
                value: String::from("Big"),
            }],
        };

        let lesser = SimpleDN {
            rdns: vec![
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Medium"),
                },
                SimpleRDN {
                    key: String::from("DC"),
                    value: String::from("Big"),
                },
            ],
        };

        assert_eq!(great.partial_cmp(&lesser), Some(Ordering::Greater));
        assert_eq!(lesser.partial_cmp(&great), Some(Ordering::Less));

        // To lesser
        let incomparable = SimpleDN {
            rdns: vec![
                SimpleRDN {
                    key: String::from("OU"),
                    value: String::from("Else"),
                },
                SimpleRDN {
                    key: String::from("DC"),
                    value: String::from("Big"),
                },
            ],
        };

        assert!(lesser.partial_cmp(&incomparable).is_none());
        assert!(incomparable.partial_cmp(&lesser).is_none());
    }

    #[test]
    fn test_common_ancestor() -> anyhow::Result<()> {
        let left = SimpleDN::from_str("CN=puerh,OU=post-fermented,DC=tea")?;
        let right = SimpleDN::from_str("CN=liu an,OU=post-fermented,DC=tea")?;
        let correct_ancestor = SimpleDN::from_str("OU=post-fermented,DC=tea")?;

        let found_ancestor = common_ancestor(&left, &right);

        assert_eq!(found_ancestor, Some(correct_ancestor));

        Ok(())
    }
}