fader_master/config/tests/persistence.rs

279 lines
9.6 KiB
Rust

use std::{
fs,
io::{self, Read},
os::unix::fs::PermissionsExt,
path::Path,
};
use fader_config::{
ActiveConfig, AtomicFile, ConfigError, MigrationError, PersistenceError, ProfileDocument,
ProfileUpgrade, StateLoad, XdgEnvironment, XdgPaths, migrate_profile, upgrade_profile,
};
#[test]
fn active_profile_pointer_is_strict_and_round_trips() {
let active = ActiveConfig::new("desktop").unwrap();
let encoded = active.to_toml().unwrap();
assert_eq!(
ActiveConfig::parse(&encoded)
.unwrap()
.active_profile()
.as_str(),
"desktop"
);
assert!(ActiveConfig::parse("schema_version = 1\nactive_profile = '../escape'").is_err());
assert!(
ActiveConfig::parse("schema_version = 1\nactive_profile = 'desktop'\nunknown = true")
.is_err()
);
}
use tempfile::tempdir;
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn xdg_paths_use_absolute_overrides_and_reject_unsafe_profile_names() {
let root = tempdir().expect("temporary root");
let home = root.path().join("home");
let config = root.path().join("configuration");
let state = root.path().join("state");
let runtime = root.path().join("runtime");
let paths = XdgPaths::resolve(&XdgEnvironment {
home: home.clone(),
config_home: Some(config.clone()),
state_home: Some(state.clone()),
runtime_dir: Some(runtime.clone()),
})
.expect("absolute XDG paths");
assert_eq!(paths.config_file(), config.join("fader_master/config.toml"));
assert_eq!(paths.state_file(), state.join("fader_master/state.toml"));
assert_eq!(
paths.runtime_dir(),
Some(runtime.join("fader_master").as_path())
);
assert_eq!(
paths.profile_file("desktop").unwrap(),
config.join("fader_master/profiles/desktop.toml")
);
assert_error_contains(paths.profile_file("../escape"), "profile ID");
assert_error_contains(paths.profile_file("nested/name"), "profile ID");
let fallback = XdgPaths::resolve(&XdgEnvironment {
home: home.clone(),
config_home: Some(Path::new("relative").to_path_buf()),
state_home: None,
runtime_dir: None,
})
.expect("relative XDG override falls back according to the specification");
assert_eq!(
fallback.config_file(),
home.join(".config/fader_master/config.toml")
);
assert_eq!(
fallback.state_file(),
home.join(".local/state/fader_master/state.toml")
);
}
#[test]
fn secure_layout_and_atomic_replacement_use_restrictive_modes() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().expect("secure application layout");
assert_eq!(
fs::metadata(paths.config_dir())
.unwrap()
.permissions()
.mode()
& 0o777,
0o700
);
let target = paths.config_file();
AtomicFile::write(&target, b"old").expect("initial write");
AtomicFile::write(&target, b"new").expect("replacement write");
assert_eq!(fs::read(&target).unwrap(), b"new");
assert_eq!(
fs::metadata(&target).unwrap().permissions().mode() & 0o777,
0o600
);
assert!(
fs::read_dir(target.parent().unwrap())
.unwrap()
.all(|entry| !entry
.unwrap()
.file_name()
.to_string_lossy()
.contains(".tmp")),
"successful writes must not leave temporary files"
);
}
#[test]
fn permission_failure_leaves_the_old_document_readable() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.config_file();
AtomicFile::write(&target, b"old").unwrap();
let directory = target.parent().unwrap();
fs::set_permissions(directory, fs::Permissions::from_mode(0o500)).unwrap();
let error = AtomicFile::write(&target, b"replacement").expect_err("directory is read-only");
fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap();
assert!(matches!(
error,
PersistenceError::Io { source, .. }
if source.kind() == io::ErrorKind::PermissionDenied
));
assert_eq!(fs::read(&target).unwrap(), b"old");
}
#[test]
fn streaming_write_failure_leaves_the_old_document_readable() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.config_file();
AtomicFile::write(&target, b"old").unwrap();
let mut failing = FailingReader { emitted: false };
assert!(AtomicFile::write_from(&target, &mut failing).is_err());
assert_eq!(fs::read(&target).unwrap(), b"old");
}
#[test]
fn missing_and_malformed_state_are_recoverable_without_rewriting_disk() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
assert!(matches!(paths.load_state().unwrap(), StateLoad::Missing));
AtomicFile::write(&paths.state_file(), b"not = [valid").unwrap();
let malformed = paths.load_state().expect("malformed cache is recoverable");
assert!(matches!(malformed, StateLoad::Malformed { .. }));
assert_eq!(
fs::read_to_string(paths.state_file()).unwrap(),
"not = [valid"
);
}
#[test]
fn profile_edits_preserve_comments_and_revalidate_the_result() {
let source = PROFILE.replace("label = \"Music\"", "# favorite player\nlabel = \"Music\"");
let mut document = ProfileDocument::parse(&source).expect("valid editable profile");
document
.set_application_label("music", "Listening")
.expect("known application");
let edited = document.finish().expect("edited profile remains valid");
assert!(edited.contains("# favorite player"));
assert!(edited.contains("label = \"Listening\""));
}
#[test]
fn migration_keeps_a_backup_and_rejects_downgrades() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.profile_file("desktop").unwrap();
AtomicFile::write(&target, b"legacy profile").unwrap();
let backup = migrate_profile(&target, 0, PROFILE).expect("forward migration");
assert_eq!(fs::read_to_string(&backup).unwrap(), "legacy profile");
assert!(fader_config::Profile::parse(&fs::read_to_string(&target).unwrap()).is_ok());
let result = migrate_profile(&target, 1, PROFILE);
assert!(matches!(result, Err(MigrationError::Incompatible { .. })));
}
#[test]
fn profile_upgrade_preserves_comments_and_backs_up_old_schema() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.profile_file("desktop").unwrap();
let legacy = PROFILE
.replace("schema_version = 1", "schema_version = 0")
.replace("id = \"desktop\"", "# keep this comment\nid = \"desktop\"");
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
let outcome = upgrade_profile(&target).expect("known old schema upgrades");
let ProfileUpgrade::Upgraded { backup, from, to } = outcome else {
panic!("old profile was not upgraded");
};
assert_eq!((from, to), (0, 1));
assert_eq!(fs::read_to_string(backup).unwrap(), legacy);
let upgraded = fs::read_to_string(target).unwrap();
assert!(upgraded.contains("# keep this comment"));
assert!(fader_config::Profile::parse(&upgraded).is_ok());
}
#[test]
fn profile_upgrade_never_rewrites_an_invalid_candidate() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.profile_file("broken").unwrap();
let invalid = "schema_version = 0\nid = 'broken'\nunknown = true\n";
AtomicFile::write(&target, invalid.as_bytes()).unwrap();
assert!(upgrade_profile(&target).is_err());
assert_eq!(fs::read_to_string(&target).unwrap(), invalid);
assert!(!target.with_file_name("broken.toml.v0.bak").exists());
}
#[test]
fn profile_upgrade_accepts_a_pre_versioned_document() {
let root = tempdir().expect("temporary root");
let paths = test_paths(root.path());
paths.create_layout().unwrap();
let target = paths.profile_file("desktop").unwrap();
let legacy = PROFILE.replacen("schema_version = 1\n", "", 1);
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
assert!(matches!(
upgrade_profile(&target).unwrap(),
ProfileUpgrade::Upgraded { from: 0, to: 1, .. }
));
assert!(fader_config::Profile::parse(&fs::read_to_string(target).unwrap()).is_ok());
}
fn test_paths(root: &Path) -> XdgPaths {
XdgPaths::resolve(&XdgEnvironment {
home: root.join("home"),
config_home: Some(root.join("config")),
state_home: Some(root.join("state")),
runtime_dir: Some(root.join("runtime")),
})
.unwrap()
}
fn assert_error_contains<T>(result: Result<T, ConfigError>, needle: &str) {
let error = result.err().expect("operation should fail").to_string();
assert!(
error.contains(needle),
"expected {error:?} to contain {needle:?}"
);
}
struct FailingReader {
emitted: bool,
}
impl Read for FailingReader {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.emitted {
return Err(io::Error::new(
io::ErrorKind::StorageFull,
"injected full disk",
));
}
self.emitted = true;
let bytes = b"partial";
buffer[..bytes.len()].copy_from_slice(bytes);
Ok(bytes.len())
}
}