From 7bb15ec0397b7f7eeac3db9de409f3f95ef397ab Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 14 Oct 2026 01:40:17 +0200 Subject: [PATCH] feat(M2.2): persist TOML files atomically Resolve private XDG paths, enforce owner and symlink checks, stream mode-0600 same-directory replacements with file and directory fsync, and recover malformed state without rewriting it. Preserve comments during validated profile edits and back up strictly forward migrations. Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features --locked; cargo test --workspace --all-targets --all-features --locked; cargo test --workspace --doc --all-features --locked; cargo clippy --workspace --all-targets --all-features --locked -- -D warnings; cargo build --workspace --release --all-features --locked; cargo check --workspace --all-targets --no-default-features --locked; cargo test --workspace --all-targets --no-default-features --locked (all pass) --- Cargo.lock | 3 + Cargo.toml | 3 + architecture.md | 35 ++++-- config/Cargo.toml | 3 + config/src/document.rs | 59 ++++++++++ config/src/error.rs | 3 + config/src/files.rs | 210 ++++++++++++++++++++++++++++++++++++ config/src/lib.rs | 6 ++ config/src/paths.rs | 134 +++++++++++++++++++++++ config/tests/persistence.rs | 203 ++++++++++++++++++++++++++++++++++ task.md | 7 +- 11 files changed, 658 insertions(+), 8 deletions(-) create mode 100644 config/src/document.rs create mode 100644 config/src/files.rs create mode 100644 config/src/paths.rs create mode 100644 config/tests/persistence.rs diff --git a/Cargo.lock b/Cargo.lock index cf592e9..6faf7db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -175,9 +175,12 @@ name = "fader-config" version = "0.1.0" dependencies = [ "fader-core", + "rustix 1.1.5", "serde", + "tempfile", "thiserror", "toml", + "toml_edit", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 034e32f..599a423 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,9 +17,12 @@ midi = { path = "midi" } proptest = "1.11.0" ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] } regex = "1.13.1" +rustix = { version = "1.1.5", features = ["process"] } serde = { version = "1.0.228", features = ["derive"] } +tempfile = "3.27.0" thiserror = "2.0.21" toml = "0.8.23" +toml_edit = "0.22.27" tui = { path = "tui" } volume_lib = { path = "sound" } diff --git a/architecture.md b/architecture.md index 7425b65..310d724 100644 --- a/architecture.md +++ b/architecture.md @@ -1,9 +1,10 @@ # fader_master architecture -Status: design researched 2026-10-05; foundation, M1 domain contracts, and M2.1 -validated TOML schemas are implemented. The executable remains a Hello World -scaffold and the TUI remains a basic Ratatui example. Configuration persistence, -runtime workers, and native adapters below are planned, not shipped. +Status: design researched 2026-10-05; foundation, M1 domain contracts, and +M2.1–M2.2 schemas and safe file persistence are implemented. The executable +remains a Hello World scaffold and the TUI remains a basic Ratatui example. +Checkpoint scheduling, runtime workers, and native adapters below are planned, +not shipped. ## Implemented boundary at M2 entry @@ -15,9 +16,12 @@ and serial mute intent planning. `config` contains strict version-1 profile, device-capability, and persisted-state schemas. Parsing validates stable IDs, selectors, references, duplicate IDs and physical bindings, audio/MIDI bounds, and feedback/output capabilities before returning a document. It serializes a -canonical semantic round trip; comment-preserving edits and filesystem behavior -remain M2.2 work. MIDI/audio crates are adapter boundaries without native handles -or transport behavior yet. +canonical semantic round trip. XDG resolution, private directory/file modes, +owner/symlink checks, same-directory atomic replacement with file and directory +sync, recoverable state loads, comment-preserving application-label edits, and +forward-migration backups are implemented. Checkpoint scheduling remains M2.3 +work. MIDI/audio crates are adapter boundaries without native handles or +transport behavior yet. Stable IDs contain 1–64 ASCII bytes, start with an alphanumeric character, and otherwise allow alphanumerics, `_`, and `-`. Selector patterns contain 1–256 @@ -50,6 +54,12 @@ Serde defines strict data shapes and TOML supplies parsing and canonical serialization; the resolved `toml_edit` dependency will also underpin M2.2 comment-preserving edits. These versions compile on the pinned Rust 1.88.0. +M2.2 directly uses `rustix 1.1.5` (Rust 1.65, Apache-2.0 WITH +LLVM-exception OR Apache-2.0 OR MIT) for safe effective-user checks and +`tempfile 3.27.0` (Rust 1.63, MIT OR Apache-2.0) for collision-safe +same-directory temporary files. Neither adds a native system-library +prerequisite, and both compile on the pinned toolchain. + ## Purpose and scope Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output. @@ -235,6 +245,17 @@ Reject unknown schema versions/fields, duplicate IDs/physical bindings, dangling Write same-directory temporary files, flush/fsync, rename atomically, then sync the directory. Debounce state writes (initial target: 500 ms after changes, maximum 2 s between dirty checkpoints), flush on orderly shutdown, and document the corresponding crash-loss window. Permission/disk-full errors leave the old file usable and show an unsaved state. Preserve user comments in profile edits with `toml_edit`. The server is the sole writer; TUI edits carry a base revision and conflict if stale. Detect out-of-process file edits before saving rather than overwriting them. +The implemented atomic writer checks that its parent and any existing target +are owned by the effective user and are not symlinks. It creates mode-`0600` +temporary files in the destination directory, streams and syncs their content, +renames over the destination, and syncs the parent directory. Application +directories are mode `0700`. Missing state and malformed readable state are +distinct recoverable load outcomes; malformed bytes are retained for diagnosis. +Profile migration accepts only versions below the current schema, validates the +replacement first, and durably backs up the original bytes before replacement. +M2.3 will add debouncing and shutdown coordination; revision conflict handling +belongs to the server/editor boundary in M9.3. + Profile switch: parse/validate candidate, prepare/probe required resources without writes, pause input briefly, drain old writes with a deadline, obtain fresh state, then commit a new config generation and publish bindings/feedback together. Abort on prepare failure and retain the old profile. If an old in-flight call cannot be safely drained, close/reconnect and reconcile before activation; generation tags alone do not cancel native writes. In-flight group membership is fixed at command acceptance. Re-arm pickup, invalidate stale queued commands, and adopt live volumes by default. Persist the active profile pointer only after successful activation; disk failure leaves the active runtime profile clearly marked unsaved. Durable crash-atomic multi-file transactions are not claimed. ## CLI, IPC, and TUI diff --git a/config/Cargo.toml b/config/Cargo.toml index b0bee58..fd81c26 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -9,6 +9,9 @@ publish.workspace = true [dependencies] fader-core.workspace = true +rustix.workspace = true serde.workspace = true +tempfile.workspace = true thiserror.workspace = true toml.workspace = true +toml_edit.workspace = true diff --git a/config/src/document.rs b/config/src/document.rs new file mode 100644 index 0000000..999d9ad --- /dev/null +++ b/config/src/document.rs @@ -0,0 +1,59 @@ +use std::str::FromStr; + +use toml_edit::{DocumentMut, Item, Value}; + +use crate::{ConfigError, Profile}; + +/// A comment-preserving profile edit that is revalidated before use. +pub struct ProfileDocument { + document: DocumentMut, +} + +impl ProfileDocument { + /// Parses both the editable TOML representation and semantic profile. + pub fn parse(input: &str) -> Result { + Profile::parse(input)?; + let document = DocumentMut::from_str(input)?; + Ok(Self { document }) + } + + /// Changes one application's display label without rebuilding its table. + pub fn set_application_label( + &mut self, + application_id: &str, + label: &str, + ) -> Result<(), ConfigError> { + let applications = self + .document + .get_mut("applications") + .and_then(Item::as_array_of_tables_mut) + .ok_or_else(|| ConfigError::validation("applications", "missing application array"))?; + let Some(application) = applications.iter_mut().find(|table| { + table + .get("id") + .and_then(Item::as_str) + .is_some_and(|id| id == application_id) + }) else { + return Err(ConfigError::validation( + "applications", + format!("unknown application {application_id:?}"), + )); + }; + let existing = application + .get_mut("label") + .and_then(Item::as_value_mut) + .ok_or_else(|| ConfigError::validation("applications.label", "missing string label"))?; + let decor = existing.decor().clone(); + let mut replacement = Value::from(label); + *replacement.decor_mut() = decor; + *existing = replacement; + Ok(()) + } + + /// Returns edited TOML only if the complete result remains valid. + pub fn finish(self) -> Result { + let output = self.document.to_string(); + Profile::parse(&output)?; + Ok(output) + } +} diff --git a/config/src/error.rs b/config/src/error.rs index b4baa5c..61443d9 100644 --- a/config/src/error.rs +++ b/config/src/error.rs @@ -6,6 +6,9 @@ pub enum ConfigError { /// The TOML document did not conform to its strict structural schema. #[error("TOML schema error: {0}")] Toml(#[from] toml::de::Error), + /// Editable TOML could not be represented while retaining formatting. + #[error("editable TOML error: {0}")] + Edit(#[from] toml_edit::TomlError), /// A field was structurally valid TOML but violated a domain invariant. #[error("validation error at {path}: {message}")] Validation { diff --git a/config/src/files.rs b/config/src/files.rs new file mode 100644 index 0000000..0384b1d --- /dev/null +++ b/config/src/files.rs @@ -0,0 +1,210 @@ +use std::{ + fs::{self, File}, + io::{self, Cursor, Read, Write}, + os::unix::fs::{MetadataExt, PermissionsExt}, + path::{Path, PathBuf}, +}; + +use tempfile::NamedTempFile; +use thiserror::Error; + +use crate::{ConfigError, PersistedState, Profile, SCHEMA_VERSION}; + +/// A filesystem persistence failure with operation and path context. +#[derive(Debug, Error)] +pub enum PersistenceError { + /// An operating-system operation failed. + #[error("could not {action} at {path}: {source}")] + Io { + /// Operation being attempted. + action: &'static str, + /// Relevant file or directory. + path: PathBuf, + /// Operating-system error. + #[source] + source: io::Error, + }, + /// A path is a symlink where ownership must be unambiguous. + #[error("refusing symlink at {0}")] + Symlink(PathBuf), + /// A path belongs to a different Unix user. + #[error("refusing path {path}: owner uid {actual} does not match current uid {expected}")] + WrongOwner { + /// Rejected path. + path: PathBuf, + /// Owner found on disk. + actual: u32, + /// Effective user running the process. + expected: u32, + }, +} + +impl PersistenceError { + pub(crate) fn io(action: &'static str, path: impl Into, source: io::Error) -> Self { + Self::Io { + action, + path: path.into(), + source, + } + } +} + +/// Result of reading cache-like state; malformed data can be ignored by startup. +#[derive(Debug)] +pub enum StateLoad { + /// No checkpoint has been written yet. + Missing, + /// A fully validated persisted-state document. + Loaded(PersistedState), + /// Bytes were readable but invalid; they remain untouched for diagnosis. + Malformed { + /// Validation or TOML parsing failure. + error: ConfigError, + }, +} + +/// Secure same-directory atomic file replacement. +pub struct AtomicFile; + +impl AtomicFile { + /// Writes mode `0600`, syncs content, renames, then syncs the directory. + /// + /// The destination is untouched until the temporary file is complete and + /// durable. Temporary files are removed automatically on pre-rename errors. + pub fn write(path: &Path, contents: &[u8]) -> Result<(), PersistenceError> { + Self::write_from(path, &mut Cursor::new(contents)) + } + + /// Streams content into a same-directory temporary file before replacement. + /// + /// This variant keeps memory bounded for larger documents and makes source + /// read failures obey the same no-replacement guarantee as disk failures. + pub fn write_from(path: &Path, source: &mut dyn Read) -> Result<(), PersistenceError> { + let parent = path.parent().ok_or_else(|| { + PersistenceError::io( + "resolve parent directory", + path, + io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"), + ) + })?; + check_owned_not_symlink(parent)?; + if path.exists() { + check_owned_not_symlink(path)?; + } + + let mut temporary = NamedTempFile::new_in(parent) + .map_err(|source| PersistenceError::io("create temporary file", parent, source))?; + temporary + .as_file() + .set_permissions(fs::Permissions::from_mode(0o600)) + .map_err(|source| PersistenceError::io("set temporary permissions", path, source))?; + io::copy(source, &mut temporary) + .map_err(|source| PersistenceError::io("write temporary file", path, source))?; + temporary + .as_file_mut() + .flush() + .map_err(|source| PersistenceError::io("flush temporary file", path, source))?; + temporary + .as_file() + .sync_all() + .map_err(|source| PersistenceError::io("sync temporary file", path, source))?; + temporary.persist(path).map_err(|error| { + PersistenceError::io("atomically replace destination", path, error.error) + })?; + File::open(parent) + .and_then(|directory| directory.sync_all()) + .map_err(|source| PersistenceError::io("sync parent directory", parent, source))?; + Ok(()) + } +} + +pub(crate) fn check_owned_not_symlink(path: &Path) -> Result<(), PersistenceError> { + let metadata = fs::symlink_metadata(path) + .map_err(|source| PersistenceError::io("inspect ownership", path, source))?; + if metadata.file_type().is_symlink() { + return Err(PersistenceError::Symlink(path.to_owned())); + } + let expected = rustix::process::geteuid().as_raw(); + let actual = metadata.uid(); + if actual != expected { + return Err(PersistenceError::WrongOwner { + path: path.to_owned(), + actual, + expected, + }); + } + Ok(()) +} + +pub(crate) fn load_state(path: &Path) -> Result { + let contents = match fs::read_to_string(path) { + Ok(contents) => contents, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(StateLoad::Missing), + Err(source) => return Err(PersistenceError::io("read state", path, source)), + }; + Ok(match PersistedState::parse(&contents) { + Ok(state) => StateLoad::Loaded(state), + Err(error) => StateLoad::Malformed { error }, + }) +} + +/// Why a profile migration could not be committed. +#[derive(Debug, Error)] +pub enum MigrationError { + /// Only strictly forward migrations to the current version are allowed. + #[error("incompatible migration from schema {from} to schema {to}")] + Incompatible { + /// Existing schema version. + from: u16, + /// Current schema version. + to: u16, + }, + /// The proposed migrated profile is invalid. + #[error(transparent)] + Config(#[from] ConfigError), + /// Reading, backing up, or replacing the file failed. + #[error(transparent)] + Persistence(#[from] PersistenceError), +} + +/// Validates and atomically installs a forward migration after backing up bytes. +pub fn migrate_profile( + path: &Path, + from_version: u16, + migrated: &str, +) -> Result { + if from_version >= SCHEMA_VERSION { + return Err(MigrationError::Incompatible { + from: from_version, + to: SCHEMA_VERSION, + }); + } + Profile::parse(migrated)?; + let old = fs::read(path) + .map_err(|source| PersistenceError::io("read pre-migration profile", path, source))?; + let file_name = path + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| { + PersistenceError::io( + "construct migration backup", + path, + io::Error::new( + io::ErrorKind::InvalidInput, + "non-UTF-8 or missing file name", + ), + ) + })?; + let backup = path.with_file_name(format!("{file_name}.v{from_version}.bak")); + if backup.exists() { + return Err(PersistenceError::io( + "create migration backup", + &backup, + io::Error::new(io::ErrorKind::AlreadyExists, "backup already exists"), + ) + .into()); + } + AtomicFile::write(&backup, &old)?; + AtomicFile::write(path, migrated.as_bytes())?; + Ok(backup) +} diff --git a/config/src/lib.rs b/config/src/lib.rs index c51ce1e..29f1415 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -8,12 +8,18 @@ #![forbid(unsafe_code)] mod device; +mod document; mod error; +mod files; +mod paths; mod profile; mod state; pub use device::{DeviceCapabilities, DeviceProfile}; +pub use document::ProfileDocument; pub use error::ConfigError; +pub use files::{AtomicFile, MigrationError, PersistenceError, StateLoad, migrate_profile}; +pub use paths::{XdgEnvironment, XdgPaths}; pub use profile::{ Adapter, Application, Audio, Binding, Fader, Group, NewStreamPolicy, Profile, StartupPolicy, Surface, diff --git a/config/src/paths.rs b/config/src/paths.rs new file mode 100644 index 0000000..a0afc43 --- /dev/null +++ b/config/src/paths.rs @@ -0,0 +1,134 @@ +use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf}; + +use fader_core::ProfileId; + +use crate::{ConfigError, PersistenceError, StateLoad, files::load_state}; + +/// Relevant XDG environment values, separated from process globals for tests. +#[derive(Clone, Debug)] +pub struct XdgEnvironment { + /// User home used only for XDG fallbacks. + pub home: PathBuf, + /// `$XDG_CONFIG_HOME`; relative values are ignored by the XDG specification. + pub config_home: Option, + /// `$XDG_STATE_HOME`; relative values are ignored by the XDG specification. + pub state_home: Option, + /// `$XDG_RUNTIME_DIR`; no shared temporary-directory fallback is invented. + pub runtime_dir: Option, +} + +impl XdgEnvironment { + /// Captures relevant process environment without applying path policy yet. + pub fn from_process() -> Result { + let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| { + ConfigError::validation("HOME", "is required when resolving XDG fallbacks") + })?; + Ok(Self { + home, + config_home: std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from), + state_home: std::env::var_os("XDG_STATE_HOME").map(PathBuf::from), + runtime_dir: std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from), + }) + } +} + +/// Resolved per-user configuration, state, and optional runtime paths. +#[derive(Clone, Debug)] +pub struct XdgPaths { + config_dir: PathBuf, + state_dir: PathBuf, + runtime_dir: Option, +} + +impl XdgPaths { + /// Resolves absolute XDG roots and specification-defined home fallbacks. + pub fn resolve(environment: &XdgEnvironment) -> Result { + if !environment.home.is_absolute() { + return Err(ConfigError::validation("HOME", "must be an absolute path")); + } + let config_root = absolute_or(&environment.config_home, || { + environment.home.join(".config") + }); + let state_root = absolute_or(&environment.state_home, || { + environment.home.join(".local/state") + }); + let runtime_dir = environment + .runtime_dir + .as_ref() + .filter(|path| path.is_absolute()) + .map(|path| path.join("fader_master")); + Ok(Self { + config_dir: config_root.join("fader_master"), + state_dir: state_root.join("fader_master"), + runtime_dir, + }) + } + + /// Root containing the global config, profiles, and device documents. + pub fn config_dir(&self) -> &std::path::Path { + &self.config_dir + } + + /// Global active-profile configuration document. + pub fn config_file(&self) -> PathBuf { + self.config_dir.join("config.toml") + } + + /// Durable state checkpoint document. + pub fn state_file(&self) -> PathBuf { + self.state_dir.join("state.toml") + } + + /// Optional private runtime directory; absent when XDG provides none. + pub fn runtime_dir(&self) -> Option<&std::path::Path> { + self.runtime_dir.as_deref() + } + + /// Resolves a validated stable profile ID without accepting path syntax. + pub fn profile_file(&self, id: &str) -> Result { + let id = ProfileId::new(id).map_err(|error| { + ConfigError::validation("profile ID", format!("unsafe profile ID: {error}")) + })?; + Ok(self + .config_dir + .join("profiles") + .join(format!("{}.toml", id.as_str()))) + } + + /// Creates application-owned directories with mode `0700`. + pub fn create_layout(&self) -> Result<(), PersistenceError> { + for directory in [ + self.config_dir.clone(), + self.config_dir.join("profiles"), + self.config_dir.join("devices"), + self.state_dir.clone(), + ] + .into_iter() + .chain(self.runtime_dir.iter().cloned()) + { + create_private_dir(&directory)?; + } + Ok(()) + } + + /// Reads state without treating absence or malformed cached data as fatal. + pub fn load_state(&self) -> Result { + load_state(&self.state_file()) + } +} + +fn absolute_or(value: &Option, fallback: impl FnOnce() -> PathBuf) -> PathBuf { + value + .as_ref() + .filter(|path| path.is_absolute()) + .cloned() + .unwrap_or_else(fallback) +} + +fn create_private_dir(path: &std::path::Path) -> Result<(), PersistenceError> { + fs::create_dir_all(path) + .map_err(|source| PersistenceError::io("create directory", path, source))?; + super::files::check_owned_not_symlink(path)?; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .map_err(|source| PersistenceError::io("set directory permissions", path, source)) +} diff --git a/config/tests/persistence.rs b/config/tests/persistence.rs new file mode 100644 index 0000000..49b9de1 --- /dev/null +++ b/config/tests/persistence.rs @@ -0,0 +1,203 @@ +use std::{ + fs, + io::{self, Read}, + os::unix::fs::PermissionsExt, + path::Path, +}; + +use fader_config::{ + AtomicFile, ConfigError, MigrationError, ProfileDocument, StateLoad, XdgEnvironment, XdgPaths, + migrate_profile, +}; +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 result = AtomicFile::write(&target, b"replacement"); + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap(); + + assert!(result.is_err()); + 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 { .. }))); +} + +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(result: Result, 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 { + 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()) + } +} diff --git a/task.md b/task.md index ad0379c..dafe7d7 100644 --- a/task.md +++ b/task.md @@ -52,7 +52,12 @@ Dependencies: M1 types; runtime activation follows in M10. checked-in example are test-locked to one another; five integration tests cover semantic round trips, reference/capability failures, unknown fields, versions, duplicates, and MIDI channel/data endpoints. -- [ ] **M2.2 Atomic files:** XDG paths, same-directory temp/rename/fsync, restrictive ownership, comment-preserving edits and migration backups. Tests: disk/permission/write failures keep the old document readable; malformed/missing state is recoverable; unsafe profile paths and incompatible migrations are rejected. +- [x] **M2.2 Atomic files:** XDG paths, same-directory temp/rename/fsync, restrictive ownership, comment-preserving edits and migration backups. Tests: disk/permission/write failures keep the old document readable; malformed/missing state is recoverable; unsafe profile paths and incompatible migrations are rejected. + XDG roots now resolve with specification fallbacks and no shared runtime + fallback. Private layout creation, effective-owner/symlink checks, mode-0600 + streaming atomic writes, directory sync, recoverable state loading, + comment-preserving validated edits, and backed-up forward migration are + covered by seven persistence integration tests. - [ ] **M2.3 Checkpoints:** per-profile observed state and separate validated desired object volume/mute, surface assignments, UI preferences, debounce and shutdown flush. Tests with a fake clock: sustained movement causes bounded writes and final state persists; crash/restart treats cached observations as stale, never restores runtime IDs or pending requests; an offline command survives restart as saved intent but only explicit restore applies it when the application launches (adopt emits no write). ## M3 — Server and fake-adapter vertical slice