rootasrole-core 4.0.0

This core crate for the RootAsRole project.
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
use std::{
    borrow::Cow,
    cell::RefCell,
    error::Error,
    fmt::Debug,
    fs::{File, OpenOptions},
    io::{self, BufReader, Seek},
    path::{Path, PathBuf},
    rc::Rc,
};

use bon::Builder;
use capctl::Cap;
use log::{debug, error, warn};
use nix::fcntl::Flock;
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use crate::{
    SettingsContent,
    database::{migration::Migration, structs::SPolicy, versionning::Versioning},
    util::{
        RAR_CFG_IMMUTABLE, RAR_CFG_PATH, RAR_CFG_TYPE, StorageMethod, has_privileges, is_immutable,
        open_lock_with_privileges, read_with_privileges, with_mutable_config, write_config,
    },
};

pub const ROOT_MIGRATIONS: &[Migration<RootSettings>] = &[];
pub const POLICY_MIGRATIONS: &[Migration<Rc<RefCell<SPolicy>>>] = &[];

#[derive(Debug)]
pub struct LockedSettingsFile<T: Serialize + DeserializeOwned + Debug + Default> {
    path: PathBuf,
    fd: Flock<File>, // file descriptor to the opened file, to keep the lock
    pub data: T,
}

/// This opens, deserialize and locks a settings file, and keeps the file descriptor open to keep the lock
/// it allows to save the settings file later
impl<T: Serialize + DeserializeOwned + Debug + Default> LockedSettingsFile<T> {
    /// # Errors
    /// Returns an error if the file cannot be opened, deserialized or locked
    pub fn open_read<S>(
        path: S,
        data_loader: impl Fn(&S, &File) -> io::Result<T>,
    ) -> std::io::Result<Self>
    where
        S: AsRef<Path>,
    {
        Self::open(path, OpenOptions::new().read(true), false, data_loader)
    }
    /// # Errors
    /// Returns an error if the file cannot be opened, deserialized, locked or written to
    pub fn open_write<S>(
        path: S,
        data_loader: impl Fn(&S, &File) -> io::Result<T>,
    ) -> std::io::Result<Self>
    where
        S: AsRef<Path>,
    {
        Self::open(
            path,
            OpenOptions::new().read(true).write(true).create(true),
            true,
            data_loader,
        )
    }

    /// # Errors
    /// Returns an error if the file cannot be opened, deserialized or locked
    pub fn open<S>(
        path: S,
        options: &std::fs::OpenOptions,
        write: bool,
        data_loader: impl Fn(&S, &File) -> io::Result<T>,
    ) -> std::io::Result<Self>
    where
        S: AsRef<Path>,
    {
        let load_data = || -> io::Result<Self> {
            let file = open_lock_with_privileges(
                path.as_ref(),
                options,
                nix::fcntl::FlockArg::LockExclusive,
            )?;

            Ok(Self {
                path: path.as_ref().to_path_buf(),
                data: data_loader(&path, &file)?,
                fd: file,
            })
        };

        if write && path.as_ref().exists() {
            let mut file = read_with_privileges(&path)?;
            if is_immutable(&file)? {
                return with_mutable_config(&mut file, |_| load_data());
            }
        }

        load_data()
    }

    /// # Errors
    /// Returns an error if the file cannot be written
    /// due to a lock, permission error or writing error
    pub fn save(&mut self, method: StorageMethod, immutable: bool) -> Result<(), Box<dyn Error>> {
        let immuable = immutable && has_privileges(&[Cap::LINUX_IMMUTABLE])?;
        debug!("Settings file immutable: {immuable}");
        if immuable {
            debug!("Toggling immutable off for config file");
            with_mutable_config(&mut self.fd, |file| {
                debug!("Toggled immutable off for config file");
                file.rewind()?;
                file.set_len(0)?;
                write_config(&self.data, file, method)
            })
            .map_err(|e| format!("Failed to write config file: {e}"))?;
        } else {
            let file = &mut *self.fd;
            debug!("Writing config file");
            file.rewind()?;
            debug!("Rewound config file for writing");
            file.set_len(0)?;
            debug!("Truncated config file");
            write_config(&self.data, file, method)?;
            // clear the rest of the file if any
            debug!("Wrote config file");
        }

        Ok(())
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Default, Builder, PartialEq, Eq)]
pub struct RootSettings {
    pub storage: SettingsContent,
    #[serde(flatten)]
    #[builder(default)]
    pub config: Rc<RefCell<SPolicy>>,
}

pub type ConfigMap = Vec<LockedPolicy>;
pub type LockedPolicy = LockedSettingsFile<Versioning<Rc<RefCell<SPolicy>>>>;
pub type LockedRootSettings = LockedSettingsFile<Versioning<RootSettings>>;

#[derive(Builder)]
pub struct FileSettings {
    #[builder(default)]
    map: ConfigMap,
    ///# Errors
    /// Returns an error if any of the files cannot be opened or locked
    #[builder(with = |path: PathBuf,config : RootSettings| -> Result<_, Box<dyn Error>> {
        Ok(LockedSettingsFile::open_write(path, |_, _| {
            let versioned: Versioning<RootSettings> = Versioning::new(config.clone());
            Ok(versioned)
        })?)
    })]
    root: LockedRootSettings,
}

impl FileSettings {
    /// # Errors
    /// Returns an error if any of the files cannot be opened, deserialized or locked
    pub fn read_all<P>(
        rar_cfg_path: P,
        rar_cfg_data_path: P,
        rar_cfg_type: StorageMethod,
    ) -> std::io::Result<Self>
    where
        P: AsRef<Path>,
    {
        Self::load_all(
            rar_cfg_path,
            rar_cfg_data_path,
            rar_cfg_type,
            OpenOptions::new().read(true),
            false,
        )
    }
    /// # Errors
    /// Returns an error if any of the files cannot be opened, deserialized, locked or written to
    pub fn write_all<P>(
        rar_cfg_path: P,
        rar_cfg_data_path: P,
        rar_cfg_type: StorageMethod,
    ) -> std::io::Result<Self>
    where
        P: AsRef<Path>,
    {
        Self::load_all(
            rar_cfg_path,
            rar_cfg_data_path,
            rar_cfg_type,
            OpenOptions::new().read(true).write(true).create(true),
            true,
        )
    }

    /// # Errors
    /// Returns an error if any of the files cannot be opened, deserialized or locked
    pub fn read_policy<P>(cfg_path: P, cfg_type: StorageMethod) -> std::io::Result<LockedPolicy>
    where
        P: AsRef<Path>,
    {
        Self::load_policy_file(cfg_type, OpenOptions::new().read(true), false, cfg_path)
    }
    /// # Errors
    /// Returns an error if any of the files cannot be opened, deserialized, locked or written to
    pub fn write_policy<P>(cfg_path: P, cfg_type: StorageMethod) -> std::io::Result<LockedPolicy>
    where
        P: AsRef<Path>,
    {
        Self::load_policy_file(
            cfg_type,
            OpenOptions::new().read(true).write(true).create(true),
            true,
            cfg_path,
        )
    }
    /// # Errors
    /// Returns an error if any of the files cannot be opened, deserialized or locked
    fn load_all<P>(
        rar_cfg_path: P,
        rar_cfg_data_path: P,
        rar_cfg_type: StorageMethod,
        options: &OpenOptions,
        write: bool,
    ) -> std::io::Result<Self>
    where
        P: AsRef<Path>,
    {
        let rar_cfg_data_path = rar_cfg_data_path.as_ref().to_path_buf();
        let root =
            LockedSettingsFile::open(rar_cfg_path.as_ref(), options, write, |path, file| {
                debug!("Loading root settings from {}", path.display());
                let mut settings: Versioning<RootSettings> = match rar_cfg_type {
                    StorageMethod::JSON => {
                        serde_json::from_reader(file).inspect_err(|e| debug!("{e}"))?
                    }
                    StorageMethod::CBOR => cbor4ii::serde::from_reader(BufReader::new(file))
                        .map_err(|e| {
                            debug!("Failed to deserialize root settings: {e}");
                            io::Error::new(io::ErrorKind::InvalidData, e)
                        })?,
                };
                Self::make_weak_config(&settings.data.config);
                settings.upgrade_version(ROOT_MIGRATIONS).map_err(|e| {
                    debug!("Failed to upgrade root settings: {e}");
                    io::Error::other(e.to_string())
                })?;
                debug!("Loaded root settings from {}", path.display());
                Ok(settings)
            })?;
        let mut map = ConfigMap::new();

        if let Some(path) = root
            .data
            .data
            .storage
            .settings
            .as_ref()
            .and_then(|settings| settings.path.as_ref())
            .and_then(|path| {
                if path.as_path() == rar_cfg_path.as_ref() {
                    None
                } else {
                    Some(path.clone())
                }
            })
            .or_else(|| {
                if rar_cfg_path.as_ref() == rar_cfg_data_path {
                    None
                } else {
                    Some(rar_cfg_data_path)
                }
            })
        {
            if !root.data.data.config.as_ref().borrow().is_empty() {
                warn!(
                    "A policy has been detected in {}, but a different path is specified. 
                    Ignoring the policy and keeping only the ones in the specified path: {}",
                    rar_cfg_path.as_ref().display(),
                    path.display()
                );
            }
            if path.is_dir() {
                debug!("Loading settings from directory {}", path.display());
                for entry in std::fs::read_dir(path)? {
                    let entry = entry?;
                    if entry.file_type()?.is_file() {
                        let path = entry.path();
                        debug!("Loading settings from file {}", path.display());
                        let config = Self::load_policy_file(
                            root.data.data.storage.method,
                            options,
                            write,
                            &path,
                        );
                        match config {
                            Ok(config) => {
                                debug!("Loaded settings from file {}", path.display());
                                Self::make_weak_config(&config.data.data);
                                map.push(config);
                            }
                            Err(e) => debug!(
                                "Failed to load settings from file {}: {}",
                                path.display(),
                                e
                            ),
                        }
                    }
                }
            } else if path.is_file() {
                debug!("Loading settings from file {}", path.display());
                let config =
                    Self::load_policy_file(root.data.data.storage.method, options, write, &path)?;
                debug!("Loaded settings from file {}", path.display());
                map.push(config);
            }
        }

        Ok(Self { map, root })
    }

    /// # Errors
    /// Returns an error if the file cannot be opened or deserialized
    fn load_policy_file<P>(
        file_type: StorageMethod,
        options: &OpenOptions,
        write: bool,
        path: P,
    ) -> std::io::Result<LockedPolicy>
    where
        P: AsRef<Path>,
    {
        let mut policyfile: LockedPolicy =
            LockedSettingsFile::open(path, options, write, |_, file| {
                Ok(match file_type {
                    StorageMethod::JSON => serde_json::from_reader(file)?,
                    StorageMethod::CBOR => cbor4ii::serde::from_reader(BufReader::new(file))
                        .map_err(io::Error::other)?,
                })
            })?;
        Self::make_weak_config(&policyfile.data.data);
        policyfile
            .data
            .upgrade_version(POLICY_MIGRATIONS)
            .map_err(|e| io::Error::other(e.to_string()))?;
        debug!("{}", serde_json::to_string_pretty(&policyfile.data.data)?);
        Ok(policyfile)
    }

    fn make_weak_config(config: &Rc<RefCell<SPolicy>>) {
        for role in &config.as_ref().borrow().roles {
            role.as_ref().borrow_mut().config = Some(Rc::downgrade(config));
            for task in &role.as_ref().borrow().tasks {
                task.as_ref().borrow_mut().role = Some(Rc::downgrade(role));
            }
        }
    }

    /// # Errors
    /// Returns an error if any of the files cannot be written
    pub fn save_all(&mut self) -> Result<(), Box<dyn Error>> {
        let immutable = self
            .root
            .data
            .data
            .storage
            .settings
            .as_ref()
            .and_then(|s| s.immutable)
            .unwrap_or(RAR_CFG_IMMUTABLE);

        if let Some(path) = self.root.data.data.storage.settings.as_ref().and_then(|s| {
            s.path.as_ref().and_then(|p| {
                debug!(
                    "Checking if root settings path needs to be updated: current {}, new {}",
                    p.display(),
                    p.display()
                );
                if *p == self.root.path {
                    None
                } else {
                    Some(p.clone())
                }
            })
        }) {
            // Open the new file with the new path
            let new_root = LockedSettingsFile::open_write(path, |_, _| {
                Ok(Versioning::new(self.root.data.data.clone()))
            })?;
            debug!(
                "Moved root settings to new path: {}",
                new_root.path.display()
            );
            // Manually drop the old root using unsafe code to trigger Drop impl
            unsafe {
                let old_root_ptr = &raw mut self.root;
                std::ptr::drop_in_place(old_root_ptr);
            }
            self.root = new_root;
        }

        let mut has_errors = if let Err(e) = self.root.save(RAR_CFG_TYPE, immutable) {
            error!("Failed to save root settings: {e}");
            true
        } else {
            debug!("Saved root settings");
            false
        };

        for config in &mut self.map {
            if let Err(e) = config.save(self.root.data.data.storage.method, immutable) {
                error!(
                    "Failed to save settings for {}: {}",
                    config.path.display(),
                    e
                );
                has_errors = true;
            }
        }

        if has_errors {
            Err("One or more files failed to save. Check the logs for details.".into())
        } else {
            Ok(())
        }
    }

    #[must_use]
    pub fn get_files(&self) -> Vec<Cow<'_, str>> {
        let mut vec: Vec<_> = self.map.iter().map(|e| e.path.to_string_lossy()).collect();
        vec.push(RAR_CFG_PATH.into());
        vec
    }

    #[must_use]
    pub fn get(&self, path: &Path) -> Option<&Rc<RefCell<SPolicy>>> {
        if path == RAR_CFG_PATH {
            Some(&self.root.data.data.config)
        } else {
            self.map
                .iter()
                .find(|config| config.path == path)
                .map(|config| &config.data.data)
        }
    }

    #[must_use]
    pub const fn get_root(&self) -> &RootSettings {
        &self.root.data.data
    }

    pub const fn get_root_mut(&mut self) -> &mut RootSettings {
        &mut self.root.data.data
    }

    #[must_use]
    pub fn get_policies(&self) -> Vec<&Rc<RefCell<SPolicy>>> {
        self.map.iter().map(|config| &config.data.data).collect()
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};

    use crate::database::actor::SActor;
    use crate::database::structs::{SCommand, SCommands, SCredentials, SRole, STask, SetBehavior};
    use crate::{PACKAGE_VERSION, RemoteStorageSettings};

    use super::*;

    pub struct Defer<F: FnOnce()>(Option<F>);

    impl<F: FnOnce()> Defer<F> {
        pub fn new(f: F) -> Self {
            Self(Some(f))
        }
    }

    impl<F: FnOnce()> Drop for Defer<F> {
        fn drop(&mut self) {
            if let Some(f) = self.0.take() {
                f();
            }
        }
    }

    pub fn defer<F: FnOnce()>(f: F) -> Defer<F> {
        Defer::new(f)
    }

    #[test]
    fn test_get_settings_same_file() {
        // Create a test JSON file
        let value = "/tmp/test_get_settings_same_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(value);
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(value)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .config(
                SPolicy::builder()
                    .role(
                        SRole::builder("test_role")
                            .actor(SActor::user(0).build())
                            .task(
                                STask::builder("test_task")
                                    .cred(SCredentials::builder().setuid(0).setgid(0).build())
                                    .commands(
                                        SCommands::builder(SetBehavior::None)
                                            .add(vec![SCommand::Simple(
                                                "/usr/bin/true".to_string(),
                                            )])
                                            .build(),
                                    )
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut config = LockedSettingsFile::open_write(PathBuf::from(value), |_, _| {
            Ok(Versioning::new(settings.clone()))
        })
        .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        let full = FileSettings::read_all(value, value, StorageMethod::JSON).unwrap();
        assert_eq!(*full.get_root(), settings);
    }

    #[test]
    fn test_get_settings_different_file() {
        // Create a test JSON file
        let external_file_path = "/tmp/test_get_settings_different_file_external.json";
        let test_file_path = "/tmp/test_get_settings_different_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file_path)
                .canonicalize()
                .unwrap_or_else(|_| test_file_path.into());
            if std::fs::remove_file(test_file_path).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let _cleanup2 = defer(|| {
            let filename = PathBuf::from(external_file_path)
                .canonicalize()
                .unwrap_or_else(|_| external_file_path.into());
            if std::fs::remove_file(external_file_path).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let settings_config = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(external_file_path)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .config(
                SPolicy::builder()
                    .role(SRole::builder("IGNORED").build())
                    .build(),
            )
            .build();
        let mut file = LockedSettingsFile::open_write(test_file_path, |_, _| {
            Ok(Versioning::new(settings_config.clone()))
        })
        .unwrap();
        file.save(StorageMethod::JSON, false).unwrap();
        drop(file); // yes, it is ugly.
        let config = SPolicy::builder()
            .role(
                SRole::builder("test_role")
                    .actor(SActor::user(0).build())
                    .task(
                        STask::builder("test_task")
                            .cred(SCredentials::builder().setuid(0).setgid(0).build())
                            .commands(
                                SCommands::builder(SetBehavior::None)
                                    .add(vec![SCommand::Simple("/usr/bin/true".to_string())])
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut file = LockedSettingsFile::open_write(external_file_path, |_, _| {
            Ok(Versioning::new(config.clone()))
        })
        .unwrap();
        file.save(StorageMethod::JSON, false).unwrap();
        let data = file.data.clone();
        drop(file); // yes, it is ugly.

        let full = FileSettings::read_all(test_file_path, external_file_path, StorageMethod::JSON)
            .unwrap();
        assert_eq!(full.get_policies().len(), 1);
        assert_eq!(
            *full.get_policies()[0].borrow(),
            *data.data.as_ref().borrow()
        );
    }

    #[test]
    fn test_save_settings_same_file() {
        let test_file = "/tmp/test_save_settings_same_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(test_file)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .config(
                SPolicy::builder()
                    .role(
                        SRole::builder("test_role")
                            .actor(SActor::user(0).build())
                            .task(
                                STask::builder("test_task")
                                    .cred(SCredentials::builder().setuid(0).setgid(0).build())
                                    .commands(
                                        SCommands::builder(SetBehavior::None)
                                            .add(vec![SCommand::Simple(
                                                "/usr/bin/true".to_string(),
                                            )])
                                            .build(),
                                    )
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
    }

    #[test]
    fn test_save_settings_different_file() {
        let external_file = "/tmp/test_save_settings_different_file_external.json";
        let test_file = "/tmp/test_save_settings_different_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let _cleanup2 = defer(|| {
            let filename = PathBuf::from(external_file)
                .canonicalize()
                .unwrap_or_else(|_| external_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        let settings_config = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(external_file)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut config = LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| {
            Ok(settings_config.clone())
        })
        .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        let policy = SPolicy::builder()
            .role(
                SRole::builder("test_role")
                    .actor(SActor::user(0).build())
                    .task(
                        STask::builder("test_task")
                            .cred(SCredentials::builder().setuid(0).setgid(0).build())
                            .commands(
                                SCommands::builder(SetBehavior::None)
                                    .add(vec![SCommand::Simple("/usr/bin/true".to_string())])
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut config = LockedSettingsFile::open_write(PathBuf::from(external_file), |_, _| {
            Ok(Versioning::new(policy.clone()))
        })
        .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        // assert that external_file contains /usr/bin/true
        let mut file = read_with_privileges(external_file).unwrap();
        let mut content = String::new();
        file.read_to_string(&mut content).unwrap();
        assert!(content.contains("/usr/bin/true"));

        // assert that test_file does NOT contain /usr/bin/true (only storage settings)
        let mut file = read_with_privileges(test_file).unwrap();
        let mut content = String::new();
        file.read_to_string(&mut content).unwrap();
        assert!(!content.contains("/usr/bin/true"));
    }

    #[test]
    fn test_save_cbor_format() {
        let external_file = "/tmp/test_save_cbor_format.bin";
        let test_file = "/tmp/test_save_cbor_format.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let _cleanup2 = defer(|| {
            let filename = PathBuf::from(external_file)
                .canonicalize()
                .unwrap_or_else(|_| external_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        let settings = Versioning::new(
            RootSettings::builder()
                .storage(
                    SettingsContent::builder()
                        .method(StorageMethod::CBOR)
                        .settings(
                            RemoteStorageSettings::builder()
                                .path(external_file)
                                .not_immutable()
                                .build(),
                        )
                        .build(),
                )
                .build(),
        );
        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        config.save(StorageMethod::CBOR, false).unwrap();
        drop(config); // yes, it is ugly.
        let policy = Versioning::new(
            SPolicy::builder()
                .role(
                    SRole::builder("test_role")
                        .actor(SActor::user(0).build())
                        .task(
                            STask::builder("test_task")
                                .cred(SCredentials::builder().setuid(0).setgid(0).build())
                                .commands(
                                    SCommands::builder(SetBehavior::None)
                                        .add(vec![SCommand::Simple("/usr/bin/true".to_string())])
                                        .build(),
                                )
                                .build(),
                        )
                        .build(),
                )
                .build(),
        );
        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(external_file), |_, _| Ok(policy.clone()))
                .unwrap();
        config.save(StorageMethod::CBOR, false).unwrap();
        drop(config); // yes, it is ugly.
        // Assert that external_file is a binary file with CBOR format
        let mut file = read_with_privileges(external_file).unwrap();
        let mut content = Vec::new();
        file.read_to_end(&mut content).unwrap();
        let deserialized: Versioning<Rc<RefCell<SPolicy>>> =
            cbor4ii::serde::from_reader(&content[..]).unwrap();
        assert_eq!(deserialized.version, PACKAGE_VERSION);
    }

    #[test]
    fn test_locked_settings_file_open_new_file() {
        let test_file = "/tmp/test_locked_settings_file_open_new_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Test opening a non-existent file with write mode
        let locked_file = LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| {
            Ok(RootSettings::default())
        })
        .unwrap();

        // Should create default settings
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        assert_eq!(locked_file.data, RootSettings::default());
    }

    #[test]
    fn test_locked_settings_file_open_existing_file() {
        let test_file = "/tmp/test_locked_settings_file_open_existing_file.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create and save a test file with some content
        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(test_file)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .config(
                SPolicy::builder()
                    .role(
                        SRole::builder("test_role")
                            .actor(SActor::user(0).build())
                            .task(
                                STask::builder("test_task")
                                    .cred(SCredentials::builder().setuid(0).setgid(0).build())
                                    .commands(
                                        SCommands::builder(SetBehavior::None)
                                            .add(vec![SCommand::Simple(
                                                "/usr/bin/true".to_string(),
                                            )])
                                            .build(),
                                    )
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();

        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        // Test opening existing file
        let locked_file = LockedSettingsFile::open_read(PathBuf::from(test_file), |_, file| {
            let versioned: RootSettings = serde_json::from_reader(file)?;
            Ok(versioned)
        })
        .unwrap();

        // Should load the existing settings
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        assert_eq!(locked_file.data, settings);
    }

    #[test]
    fn test_locked_settings_file_open_write_mode_non_immutable() {
        let test_file = "/tmp/test_locked_settings_file_open_write_mode_non_immutable.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create a test file with non-immutable settings
        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(test_file)
                            .not_immutable() // explicitly not immutable
                            .build(),
                    )
                    .build(),
            )
            .build();

        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        // Test opening existing file with write mode - should work normally for non-immutable files
        let result = LockedSettingsFile::open_write(PathBuf::from(test_file), |_, file| {
            let versioned: RootSettings = serde_json::from_reader(file)?;
            Ok(versioned)
        });
        match result {
            Ok(locked_file) => {
                assert_eq!(locked_file.path, PathBuf::from(test_file));
                // The loaded settings should match our created config
                assert_eq!(locked_file.data.storage, settings.storage);
            }
            Err(_) => {
                println!("Test skipped due to insufficient privileges in test environment");
            }
        }
    }

    #[test]
    fn test_locked_settings_file_open_with_separate_config() {
        let test_file = "/tmp/test_locked_settings_file_open_with_separate_config.json";
        let external_file =
            "/tmp/test_locked_settings_file_open_with_separate_config_external.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });
        let _cleanup2 = defer(|| {
            let filename = PathBuf::from(external_file)
                .canonicalize()
                .unwrap_or_else(|_| external_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create external config file
        let sconfig = SPolicy::builder()
            .role(
                SRole::builder("test_role")
                    .actor(SActor::user(0).build())
                    .task(
                        STask::builder("test_task")
                            .cred(SCredentials::builder().setuid(0).setgid(0).build())
                            .commands(
                                SCommands::builder(SetBehavior::None)
                                    .add(vec![SCommand::Simple("/usr/bin/true".to_string())])
                                    .build(),
                            )
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut external_config = LockedSettingsFile::open_write(
            PathBuf::from(external_file),
            |_, _| Ok(sconfig.clone()),
        )
        .unwrap();
        external_config.save(StorageMethod::JSON, false).unwrap();
        drop(external_config);

        // Create settings file pointing to external config
        let settings_config = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .settings(
                        RemoteStorageSettings::builder()
                            .path(external_file)
                            .not_immutable()
                            .build(),
                    )
                    .build(),
            )
            .build();
        let mut config = LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| {
            Ok(settings_config.clone())
        })
        .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        // Test opening file with separate config
        let locked_file = LockedSettingsFile::open_read(PathBuf::from(test_file), |_, file| {
            let versioned: RootSettings = serde_json::from_reader(file)?;
            Ok(versioned)
        })
        .unwrap();

        // Should load settings and external config
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        assert_eq!(locked_file.data.storage, settings_config.storage);
    }

    #[test]
    fn test_locked_settings_file_open_invalid_json() {
        let test_file = "/tmp/test_locked_settings_file_open_invalid_json.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create a file with invalid JSON
        let mut file = File::create(test_file).unwrap();
        file.write_all(b"{ invalid json content }").unwrap();
        drop(file);

        // Test opening file with invalid JSON - should fall back to default
        let locked_file = LockedSettingsFile::open_read(PathBuf::from(test_file), |_, file| {
            serde_json::from_reader::<_, RootSettings>(file)
                .map_or_else(|_| Ok(RootSettings::default()), Ok)
        })
        .unwrap();

        // Should fall back to default settings when JSON is invalid
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        assert_eq!(locked_file.data, RootSettings::default());
    }

    #[test]
    fn test_locked_settings_file_open_readonly() {
        let test_file = "/tmp/test_locked_settings_file_open_readonly.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create a test file with minimal settings
        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .build(),
            )
            .build();

        let mut config =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        config.save(StorageMethod::JSON, false).unwrap();
        drop(config); // yes, it is ugly.
        // Test opening file in read-only mode
        let locked_file = LockedSettingsFile::open_read(PathBuf::from(test_file), |_, file| {
            let versioned: RootSettings = serde_json::from_reader(file)?;
            Ok(versioned)
        })
        .unwrap();

        // Should successfully open and load settings
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        // The storage settings should match what we wrote
        assert_eq!(locked_file.data.storage.method, settings.storage.method);
        assert_eq!(locked_file.data.storage.settings, settings.storage.settings);
    }

    #[test]
    fn test_locked_settings_file_open_nonexistent_file_error() {
        let test_file = "/tmp/test_locked_settings_file_open_nonexistent_file_error.json";

        // Ensure the file doesn't exist
        let _ = std::fs::remove_file(test_file);

        // Test opening non-existent file without create option - should fail
        let result = LockedSettingsFile::open_read(PathBuf::from(test_file), |_, file| {
            let versioned: Versioning<RootSettings> = serde_json::from_reader(file)?;
            Ok(versioned.data)
        });

        // Should fail because file doesn't exist
        assert!(result.is_err());
    }

    #[test]
    fn test_locked_settings_file_open_create_new() {
        let test_file = "/tmp/test_locked_settings_file_open_create_new.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Ensure the file doesn't exist
        let _ = std::fs::remove_file(test_file);

        // Test creating a new file
        let locked_file = LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| {
            Ok(RootSettings::default())
        })
        .unwrap();

        // Should create new file with default settings
        assert_eq!(locked_file.path, PathBuf::from(test_file));
        // File should exist now
        assert!(PathBuf::from(test_file).exists());
    }

    #[test]
    fn test_locked_settings_truncates_file_on_save() {
        let test_file = "/tmp/test_locked_settings_truncates_file_on_save.json";
        let _cleanup = defer(|| {
            let filename = PathBuf::from(test_file)
                .canonicalize()
                .unwrap_or_else(|_| test_file.into());
            if std::fs::remove_file(&filename).is_err() {
                debug!("Failed to delete the file: {}", filename.display());
            }
        });

        // Create a test file with some initial content
        let initial_content = r#"{
            "version": "0.1.0",
            "storage": {
                "method": "JSON"
            }
        }"#;
        let mut file = File::create(test_file).unwrap();
        file.write_all(initial_content.as_bytes()).unwrap();
        drop(file);

        // Create new settings with no config
        let settings = RootSettings::builder()
            .storage(
                SettingsContent::builder()
                    .method(StorageMethod::JSON)
                    .build(),
            )
            .build();

        // Open and save - should truncate old content
        let mut locked =
            LockedSettingsFile::open_write(PathBuf::from(test_file), |_, _| Ok(settings.clone()))
                .unwrap();
        locked.save(StorageMethod::JSON, false).unwrap();
        drop(locked); // yes, it is ugly.

        // Read back the file content
        let mut file = File::open(test_file).unwrap();
        let mut content = String::new();
        file.read_to_string(&mut content).unwrap();

        // The content should NOT contain old roles
        assert!(!content.contains("old_role"));
        assert!(!content.contains("another_old_role"));
        assert!(!content.contains("yet_another_old_role"));
        assert!(!content.contains("oldest_role"));
    }
}