libkrimes 0.2.0

A pure rust, minimal kerberos library
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
use pest::Parser;
use pest::iterators::Pair;
use pest_derive::Parser;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, error, trace};

#[derive(Parser)]
#[grammar = "client/krb5.pest"]
pub struct KerberosConfigParser;

#[derive(Debug)]
pub enum KerberosConfigError {
    NoConfigFile,
    IoError(std::io::Error),
    ParseError,
}

#[derive(Debug, PartialEq, Default)]
pub struct KerberosConfig {
    pub sections: HashMap<String, Section>,
}

#[derive(Debug, PartialEq, Default)]
pub struct Section {
    pub name: String,
    pub settled: bool,
    pub relations: HashMap<String, Relation>,
}

#[derive(Debug, PartialEq)]
pub struct Relation {
    pub tag: String,
    pub settled: bool,
    pub value: Value,
}

#[derive(Debug, PartialEq)]
pub enum Value {
    // Last value is the latest read
    String(Vec<String>),
    Section(Section),
}

impl KerberosConfig {
    fn subsection(
        relation: &mut Relation,
        pair: Pair<'_, Rule>,
    ) -> Result<(), KerberosConfigError> {
        let section = match &mut relation.value {
            Value::String(_) => return Err(KerberosConfigError::ParseError),
            Value::Section(s) => s,
        };

        for relation_part in pair.into_inner() {
            match relation_part.as_rule() {
                Rule::relation => Self::relation(section, relation_part)?,
                Rule::comment => {}
                Rule::final_mark => {
                    relation.settled = true;
                }
                x => {
                    error!("Unexpected rule {:#?}", x);
                    unreachable!();
                }
            }
        }
        Ok(())
    }

    fn relation(section: &mut Section, pair: Pair<'_, Rule>) -> Result<(), KerberosConfigError> {
        let mut tag = String::new();
        for relation_part in pair.into_inner() {
            match relation_part.as_rule() {
                Rule::tag => {
                    tag = relation_part.as_str().to_string();
                    // If the tag does not exist, insert. If already exists
                    // and is settled ignore this relation completely
                    if section
                        .relations
                        .entry(tag.clone())
                        .or_insert(Relation {
                            tag: tag.clone(),
                            settled: false,
                            value: Value::String(vec![]),
                        })
                        .settled
                    {
                        return Ok(());
                    }
                }
                Rule::final_mark => {
                    section
                        .relations
                        .get_mut(&tag)
                        .ok_or(KerberosConfigError::ParseError)?
                        .settled = true;
                }
                Rule::value => {
                    let v = relation_part.as_str().to_string();
                    match &mut section
                        .relations
                        .get_mut(&tag)
                        .ok_or(KerberosConfigError::ParseError)?
                        .value
                    {
                        Value::String(items) => items.push(v),
                        Value::Section(_) => return Err(KerberosConfigError::ParseError),
                    };
                }
                Rule::subsection => {
                    // When the relation is created and inserver into section's relation
                    // after initial tag rule match, the value is created as an empty
                    // string vector. Reassign now the value as a subsection
                    let current = section
                        .relations
                        .get_mut(&tag)
                        .ok_or(KerberosConfigError::ParseError)?;

                    match &current.value {
                        Value::String(items) => {
                            if !items.is_empty() {
                                return Err(KerberosConfigError::ParseError);
                            }
                            current.value = Value::Section(Section {
                                name: tag.clone(),
                                settled: current.settled,
                                relations: HashMap::new(),
                            });
                        }
                        Value::Section(_) => {}
                    };

                    Self::subsection(
                        section
                            .relations
                            .get_mut(&tag)
                            .ok_or(KerberosConfigError::ParseError)?,
                        relation_part,
                    )?
                }
                x => {
                    error!("Unexpected rule {:#?}", x);
                    unreachable!();
                }
            }
        }
        Ok(())
    }

    fn section(
        config: &mut KerberosConfig,
        pair: Pair<'_, Rule>,
    ) -> Result<(), KerberosConfigError> {
        let mut name = String::new();
        for section_part in pair.into_inner() {
            match section_part.as_rule() {
                Rule::section_name => {
                    name = section_part.as_str().to_string();
                    // If the section does not exist, insert. If already exists
                    // and is settled return and ignore this section completely
                    if config
                        .sections
                        .entry(name.clone())
                        .or_insert(Section {
                            name: name.clone(),
                            settled: false,
                            relations: HashMap::new(),
                        })
                        .settled
                    {
                        return Ok(());
                    }
                }
                Rule::relation => Self::relation(
                    config
                        .sections
                        .get_mut(&name)
                        .ok_or(KerberosConfigError::ParseError)?,
                    section_part,
                )?,
                Rule::final_mark => {
                    config
                        .sections
                        .get_mut(&name)
                        .ok_or(KerberosConfigError::ParseError)?
                        .settled = true;
                }
                Rule::comment => {}
                x => {
                    error!("Unexpected rule {:#?}", x);
                    unreachable!();
                }
            }
        }
        Ok(())
    }

    /// Parse the content of a `krb5.conf` file from a &str
    pub fn parse(input: &str, config: &mut KerberosConfig) -> Result<(), KerberosConfigError> {
        let parsed = KerberosConfigParser::parse(Rule::file, input)
            .map_err(|_| KerberosConfigError::ParseError)?
            .next()
            .ok_or(KerberosConfigError::ParseError)?;

        for file_part in parsed.into_inner() {
            match file_part.as_rule() {
                Rule::section => Self::section(config, file_part),
                Rule::include_file => {
                    let mut include_parts = file_part.into_inner();
                    let path = include_parts
                        .next()
                        .ok_or(KerberosConfigError::ParseError)?
                        .as_str()
                        .to_string();
                    let path = PathBuf::from(path);
                    Self::include_file(&path, config)
                }
                Rule::include_dir => {
                    let mut include_parts = file_part.into_inner();
                    let path = include_parts
                        .next()
                        .ok_or(KerberosConfigError::ParseError)?
                        .as_str()
                        .to_string();
                    let path = PathBuf::from(path);
                    Self::include_dir(&path, config)
                }
                Rule::EOI => Ok(()),
                Rule::comment => Ok(()),
                x => {
                    error!("Unexpected rule {:#?}", x);
                    unreachable!();
                }
            }?
        }
        Ok(())
    }

    fn include_file(
        path: &PathBuf,
        config: &mut KerberosConfig,
    ) -> Result<(), KerberosConfigError> {
        let unparsed = fs::read_to_string(path.as_path()).map_err(|e| {
            debug!("Failed to read file {path:?}: {e}");
            KerberosConfigError::IoError(e)
        })?;
        Self::parse(&unparsed, config)
    }
    fn include_dir(path: &PathBuf, config: &mut KerberosConfig) -> Result<(), KerberosConfigError> {
        let mut files: Vec<PathBuf> = fs::read_dir(path)
            .map_err(|e| {
                error!("Failed to read directory {path:?}: {e}");
                KerberosConfigError::IoError(e)
            })?
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path())
            .filter(|path| {
                let file_name = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
                // Only include files with alphanumeric names, dashes, or underscores
                let valid_name = file_name
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '-' || c == '_');
                // Also include ".conf" files, as long as they do not start with '.'
                valid_name || (file_name.ends_with(".conf") && !file_name.starts_with('.'))
            })
            .collect();

        // Process files in alphanumeric order
        files.sort();

        for file in files {
            Self::include_file(&file, config)?;
        }
        Ok(())
    }

    fn from_usr_etc() -> Result<KerberosConfig, KerberosConfigError> {
        let mut config = KerberosConfig::default();

        // TODO To build time option
        let user_cfg_path = PathBuf::from("/etc/krb5.conf");
        if user_cfg_path.exists() {
            trace!(?user_cfg_path, "Load user config");
            let unparsed = fs::read_to_string(&user_cfg_path).map_err(|e| {
                error!("Failed to read file {user_cfg_path:?}: {e}");
                KerberosConfigError::IoError(e)
            })?;
            Self::parse(&unparsed, &mut config)?;
        } else {
            let distro_cfg_path = PathBuf::from("/usr/etc/krb5.conf");
            if distro_cfg_path.exists() {
                trace!(?distro_cfg_path, "Load distro config");
                let unparsed = fs::read_to_string(&distro_cfg_path).map_err(|e| {
                    error!("Failed to read file {distro_cfg_path:?}: {e}");
                    KerberosConfigError::IoError(e)
                })?;
                Self::parse(&unparsed, &mut config)?;
            } else {
                return Err(KerberosConfigError::NoConfigFile);
            }
        }

        Ok(config)
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<KerberosConfig, KerberosConfigError> {
        let unparsed = fs::read_to_string(path).map_err(|e| {
            debug!("Failed to read file: {e}");
            KerberosConfigError::IoError(e)
        })?;
        let mut config = KerberosConfig::default();
        Self::parse(&unparsed, &mut config)?;
        Ok(config)
    }

    pub fn from_defaults() -> Result<KerberosConfig, KerberosConfigError> {
        let path = match env::var("KRB5_CONFIG") {
            Ok(v) => PathBuf::from(v),
            Err(_) => return Self::from_usr_etc(),
        };
        let unparsed = fs::read_to_string(path.as_path()).map_err(|e| {
            debug!("Failed to read file {path:?}: {e}");
            KerberosConfigError::IoError(e)
        })?;
        let mut config = KerberosConfig::default();
        Self::parse(&unparsed, &mut config)?;
        Ok(config)
    }

    pub fn libdefaults(&self, tag: &str) -> Option<String> {
        self.sections
            .get("libdefaults")
            .and_then(|s| s.relations.get(tag))
            .map(|r| match &r.value {
                Value::String(v) => v.last().cloned(),
                Value::Section(_) => None,
            })?
    }

    pub fn realms(&self, realm: &str, tag: &str) -> Option<String> {
        self.sections
            .get("realms")
            .and_then(|s| s.relations.get(realm))
            .map(|r| match &r.value {
                Value::String(_) => None,
                Value::Section(r) => r.relations.get(tag).and_then(|r| match &r.value {
                    Value::String(v) => v.last().cloned(),
                    Value::Section(_) => None,
                }),
            })?
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::NamedTempFile;
    use tempfile::tempdir;

    #[test]
    fn test_config_basic_section_parsing() {
        let input = r#"
            # abar
            [libdefaults]*
            default_realm = EXAMPLE.COM
            ticket_lifetime* = 24h
            ticket_lifetime = 1h

            [libdefaults]
            default_realm = IGNORED.COM

            [realms]
            # afoo
            ONE.EXAMPLE.COM = {
                kdc = 192.168.1.1
            }*
            ONE.EXAMPLE.COM = {
                kdc = 192.168.1.2
            }
            TWO.EXAMPLE.COM* = {
                kdc = 192.168.1.1
            }
            TWO.EXAMPLE.COM* = {
                kdc = 192.168.1.2
            }
        "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_ok());

        assert!(config.sections.contains_key("libdefaults"));

        let libdefaults = &config.sections["libdefaults"];
        assert!(libdefaults.settled);
        assert_eq!(
            libdefaults.relations.get("default_realm"),
            Some(&Relation {
                tag: "default_realm".to_string(),
                settled: false,
                value: Value::String(vec!["EXAMPLE.COM".to_string()]),
            })
        );

        assert_eq!(
            libdefaults.relations.get("ticket_lifetime"),
            Some(&Relation {
                tag: "ticket_lifetime".to_string(),
                settled: true,
                value: Value::String(vec!["24h".to_string()]),
            })
        );

        let realms = &config.sections["realms"];
        let one = &realms.relations["ONE.EXAMPLE.COM"];
        assert_eq!(one.tag, "ONE.EXAMPLE.COM".to_string());
        assert!(one.settled);
        match &one.value {
            Value::Section(s) => {
                assert_eq!(s.name, "ONE.EXAMPLE.COM".to_string());
                //assert!(s.settled);
                let kdc = &s.relations["kdc"];
                assert_eq!(kdc.tag, "kdc".to_string());
                assert_eq!(kdc.value, Value::String(vec!["192.168.1.1".to_string()]));
            }
            _ => panic!(),
        }

        let two = &realms.relations["TWO.EXAMPLE.COM"];
        assert_eq!(two.tag, "TWO.EXAMPLE.COM".to_string());
        assert!(two.settled);
        match &two.value {
            Value::Section(s) => {
                assert_eq!(s.name, "TWO.EXAMPLE.COM".to_string());
                //assert!(s.settled);
                let kdc = &s.relations["kdc"];
                assert_eq!(kdc.tag, "kdc".to_string());
                assert_eq!(kdc.value, Value::String(vec!["192.168.1.1".to_string()]));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn test_config_non_closed_nested_section() {
        // Test non-closed subsections
        let input = r#"
            [realms]
                EXAMPLE.COM = {
                    kdc = kerberos.example.com
                    admin_server = admin.example.com
            "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_nested_section() {
        let input = r#"
                [realms]
                    EXAMPLE.COM = {
                        kdc = kerberos.example.com
                        admin_server = admin.example.com
                    }
                "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_ok());

        assert!(config.sections.contains_key("realms"));

        let realms = &config.sections["realms"];
        let realm_entry = &realms.relations["EXAMPLE.COM"];

        if let Value::Section(nested_section) = &realm_entry.value {
            assert_eq!(
                &nested_section.relations["kdc"],
                &Relation {
                    tag: "kdc".to_string(),
                    settled: false,
                    value: Value::String(vec!["kerberos.example.com".to_string()])
                }
            );
            assert_eq!(
                &nested_section.relations["admin_server"],
                &Relation {
                    tag: "admin_server".to_string(),
                    settled: false,
                    value: Value::String(vec!["admin.example.com".to_string()])
                }
            );
        } else {
            panic!("Expected nested section, but got something else");
        }

        // Test nested recursion
        let input = r#"
              [appdefaults]
                  telnet = {
                      ATHENA.MIT.EDU = {
                          option1 = false
                      }
                  }
                  telnet = {
                      option1 = true
                      option2 = true
                  }
                  ATHENA.MIT.EDU = {
                      option2 = false
                  }
                  option2 = true
            "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_ok());

        // From krb5.conf manpage:
        //
        // if telnet is running in the realm EXAMPLE.COM, it should, by default, have option1 and option2 set to true.
        // However, a telnet program in the realm ATHENA.MIT.EDU should have option1 set to false and option2 set to
        // true. Any other programs in ATHENA.MIT.EDU should have option2 set to false by default.  Any programs
        // running in other realms should have option2 set to true.

        let appdefaults = &config.sections["appdefaults"];

        if let Value::Section(telnet) = &appdefaults.relations["telnet"].value {
            assert_eq!(telnet.relations.len(), 3);

            assert_eq!(
                &telnet.relations["option1"],
                &Relation {
                    tag: "option1".to_string(),
                    settled: false,
                    value: Value::String(vec!["true".to_string()])
                }
            );
            assert_eq!(
                &telnet.relations["option2"],
                &Relation {
                    tag: "option2".to_string(),
                    settled: false,
                    value: Value::String(vec!["true".to_string()])
                }
            );

            if let Value::Section(athena) = &telnet.relations["ATHENA.MIT.EDU"].value {
                assert_eq!(athena.relations.len(), 1);
                assert_eq!(
                    &athena.relations["option1"],
                    &Relation {
                        tag: "option1".to_string(),
                        settled: false,
                        value: Value::String(vec!["false".to_string()])
                    }
                );
            }
        } else {
            panic!();
        }

        if let Value::Section(athena) = &appdefaults.relations["ATHENA.MIT.EDU"].value {
            // ATHENA.MIT.EDU options for all apps
            assert_eq!(athena.relations.len(), 1);
            assert_eq!(
                &athena.relations["option2"],
                &Relation {
                    tag: "option2".to_string(),
                    settled: false,
                    value: Value::String(vec!["false".to_string()])
                }
            );
        } else {
            panic!()
        }

        assert_eq!(
            &appdefaults.relations["option2"],
            &Relation {
                tag: "option2".to_string(),
                settled: false,
                value: Value::String(vec!["true".to_string()])
            }
        );
    }

    #[test]
    fn test_config_comments_and_whitespace() {
        let input = r#"
            # This is a comment
            [libdefaults]
            default_realm = EXAMPLE.COM
    
            ; Another comment format
              ; This time with leading spaces
               # in both formats
            ticket_lifetime = 24h
        "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_ok());

        assert!(config.sections.contains_key("libdefaults"));

        let libdefaults = &config.sections["libdefaults"];
        assert_eq!(libdefaults.relations.len(), 2);
        assert_eq!(
            &libdefaults.relations["default_realm"].value,
            &Value::String(vec!["EXAMPLE.COM".to_string()])
        );
        assert_eq!(
            &libdefaults.relations["ticket_lifetime"].value,
            &Value::String(vec!["24h".to_string()])
        );
    }

    #[test]
    fn test_config_invalid_line() {
        let input = r#"
            [libdefaults]
            # Missing '='
            default_realm EXAMPLE.COM
        "#;

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_empty_config() {
        let input = "";

        let mut config = KerberosConfig::default();
        let result = KerberosConfig::parse(input, &mut config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_config_from_file_success() {
        let file_content = r#"
            [domain_realm]
            .example.com = EXAMPLE.COM
            .otherdomain.com = OTHERREALM.COM
        "#;

        // Write test content to a temporary file
        let mut file = NamedTempFile::new().expect("new namedtempfile");
        file.write_all(file_content.as_bytes())
            .expect("Failed to write to temporary file");
        file.flush().expect("flush temp file");

        // Test from_file
        let result = KerberosConfig::from_file(file.path());
        assert!(result.is_ok());

        let config = result.unwrap();
        assert!(config.sections.contains_key("domain_realm"));

        let domain_realm = &config.sections["domain_realm"];
        assert_eq!(
            &domain_realm.relations[".example.com"].value,
            &Value::String(vec!["EXAMPLE.COM".to_string()])
        );
        assert_eq!(
            &domain_realm.relations[".otherdomain.com"].value,
            &Value::String(vec!["OTHERREALM.COM".to_string()])
        );

        // Clean up temporary file
        file.close().expect("close temp file");
    }

    #[test]
    fn test_config_from_file_failure() {
        let invalid_path = std::path::Path::new("non_existent.conf");
        let result = KerberosConfig::from_file(invalid_path);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_parse_include() {
        let content = r#"
            [libdefaults]
            default_realm = FROM.INCLUDED.CONF
        "#;
        let mut inc_file = NamedTempFile::new().expect("new namedtempfile");
        inc_file
            .write_all(content.as_bytes())
            .expect("Failed to write to temporary file");
        inc_file.flush().expect("flush temp file");

        let content = r#"
            [libdefaults]
            default_realm = FROM.MAIN.CONF
        "#;

        // Fist include, then main
        let content = format!("include {}\n{}", inc_file.path().to_string_lossy(), content);
        let mut main_file = NamedTempFile::new().expect("new namedtempfile");
        main_file
            .write_all(content.as_bytes())
            .expect("Failed to write to temporary file");
        main_file.flush().expect("flush temp file");

        let config = KerberosConfig::from_file(main_file.path()).expect("parse");

        let libdefaults = &config.sections["libdefaults"];
        assert_eq!(
            &libdefaults.relations["default_realm"].value,
            &Value::String(vec![
                "FROM.INCLUDED.CONF".to_string(),
                "FROM.MAIN.CONF".to_string(),
            ])
        );

        main_file.close().expect("close");

        // Fist main, then include
        let content = r#"
            [libdefaults]
            default_realm = FROM.MAIN.CONF
        "#;
        let content = format!("{}\ninclude {}", content, inc_file.path().to_string_lossy());
        let mut main_file = NamedTempFile::new().expect("new namedtempfile");
        main_file
            .write_all(content.as_bytes())
            .expect("Failed to write to temporary file");
        main_file.flush().expect("flush temp file");

        let config = KerberosConfig::from_file(main_file.path()).expect("parse");

        let libdefaults = &config.sections["libdefaults"];
        assert_eq!(
            &libdefaults.relations["default_realm"].value,
            &Value::String(vec![
                "FROM.MAIN.CONF".to_string(),
                "FROM.INCLUDED.CONF".to_string(),
            ])
        );

        main_file.close().expect("close");

        inc_file.close().expect("close");
    }

    #[test]
    fn test_config_parse_includedir() {
        let inc_dir = tempdir().expect("tempdir");

        let inc_a_content = r#"
            [libdefaults]
            default_realm = FROM.INC.A.CONF
        "#;

        let inc_b_content = r#"
            [libdefaults]
            default_realm = FROM.INC.B.CONF
        "#;

        let inc_a_path = inc_dir.path().join("a.conf");
        let mut inc_a_file = File::create(inc_a_path).expect("create");
        inc_a_file
            .write_all(inc_a_content.as_bytes())
            .expect("Failed to write to temporary file");
        inc_a_file.flush().expect("flush temp file");

        let inc_b_path = inc_dir.path().join("b.conf");
        let mut inc_b_file = File::create(inc_b_path).expect("create");
        inc_b_file
            .write_all(inc_b_content.as_bytes())
            .expect("Failed to write to temporary file");
        inc_b_file.flush().expect("flush temp file");

        let main_content = format!(
            "
            includedir {}
            [libdefaults]
            default_realm = FROM.MAIN.CONF
        ",
            inc_dir.path().to_string_lossy()
        );
        let mut main_file = NamedTempFile::new().expect("new namedtempfile");
        main_file
            .write_all(main_content.as_bytes())
            .expect("Failed to write to temporary file");
        main_file.flush().expect("flush temp file");

        let config = KerberosConfig::from_file(main_file.path()).expect("parse");

        let libdefaults = &config.sections["libdefaults"];
        assert_eq!(
            &libdefaults.relations["default_realm"].value,
            &Value::String(vec![
                "FROM.INC.A.CONF".to_string(),
                "FROM.INC.B.CONF".to_string(),
                "FROM.MAIN.CONF".to_string()
            ])
        );

        drop(inc_a_file);
        drop(inc_b_file);
        inc_dir.close().expect("close");
        main_file.close().expect("close");
    }
}