diff --git a/docs/config.md b/docs/config.md index 6a52530..b687551 100644 --- a/docs/config.md +++ b/docs/config.md @@ -17,8 +17,12 @@ How a file is read and written: - **Two plain files start with defaults instead.** `devices.json` and `attached.json` are not critical and their defaults are safe (nothing shared, nothing remembered), so a corrupt one does not stop Koppel. It starts empty in memory, the file is left untouched, and `GET /api/system/checks` shows a `devices` or `attached` entry ("devices.json was not used.") with the reason. The first change made while the file is bad (sharing a device, attaching one) moves it aside as `.unreadable-`, logs a warning, and writes a fresh file; fixing the file by hand instead clears the entry. `settings.json` and the encrypted files still refuse to start: defaults would put a machine back in the Server role, or lose keys and credentials. - **Hand edits are validated** the same way a REST change is, including the port rules. While Koppel runs, a bad edit is ignored: the last good value stays, a warning is logged, and `GET /api/system/checks` shows a `settings` entry, "settings.json was not applied", with the reason. A later valid edit clears it. A REST change made over a bad hand edit replaces the bad file with the last good value plus the change. - **A valid hand edit** is loaded before the next change, so a change from the UI never overwrites it. -- **Pushes are ordered.** A change reaches subscribers in write order, one change at a time, even when several writes are in flight. A handler may update the same file: the nested change is written and applied at once, its delivery is queued behind the running one and anything already waiting, so every subscriber sees the same order, and the nested call returns without waiting for that delivery (it would wait for itself). -- **Writes** go to a random temp name, are flushed, and replace the file; a failed write removes its temp file, the replace is retried on a sharing error, and stale temp files are swept at start. +- **Pushes are ordered.** A change reaches subscribers in write order, one change at a time, even when several writes are in flight. A handler may update the same file: the nested change is written and applied at once, its delivery is queued behind the running one and anything already waiting, so every subscriber sees the same order, and the nested call returns without waiting for that delivery (it would wait for itself). A handler that changes the file from another task and waits for it is not seen as nested, so that call gives up waiting for the delivery after 15 seconds and returns; its change is on disk by then. +- **Writes** go to a random temp name (mode `0600` on Linux), are flushed, and replace the file, and then the directory is flushed too, so a power cut cannot bring the old file back after the change was acknowledged. A failed write removes its temp file, the replace is retried on a sharing error, and stale temp files are swept at start. Windows has no directory flush; NTFS journals its metadata. +- **Own writes are told from edits by content.** After a write the file's size and time are taken from the temp file before it is moved, and a SHA-256 of the bytes is kept. A file whose size or time differs is read and hashed, and one with the same hash is our own write. A file written in the last three seconds is hashed on every poll, so an edit that keeps the size and a coarse file system time (`"server"` and `"client"` are both six letters) is still seen. No plaintext copy of a file is kept to compare with. +- **Limits and versions:** a config file over 8 MiB is refused without being read whole. Every file carries `"version": 1` after its fields, which 0.1.x ignores. A file with a newer version stops start-up (or is not applied, for a hand edit) and is left as it was, as a secret file with a newer format is. Names in a hand-edited file that Koppel does not know are logged at start and on each edit: they are ignored and are gone after the next change Koppel writes. A file without `version` is read as version 1. +- **Errors have kinds** (`ConfigErrorKind`: `Io`, `Decrypt`, `Parse`, `Invalid`, `Newer`), and the advice is composed from the kind: only a file that did not decrypt is told to restore the keys directory, and a full disk is not. +- **`shareOnStartup` has one default, true,** for a new install and for a hand-edited `settings.json` that leaves it out. 0.1.x read a missing one as false. - **Enums are names only:** a number where a name is expected (`"role": 1`) is refused. The encrypted files are sealed with a key in a separate keys directory (`Paths:Keys`): machine DPAPI on @@ -30,7 +34,7 @@ and goes in 0.2.0, which cannot read a key ring protected with it. Data folder hardening. Before anything is written, Koppel restricts the config and keys directories: - **Windows:** the owner becomes Administrators and the ACL is protected (no inherited access) with full control for SYSTEM and Administrators only. A directory that is a junction or a symbolic link is refused. A process that is not elevated, such as a developer running from a console, cannot take ownership, so it also keeps its own access. -- **Linux:** `chmod 700`. A bind-mounted config directory that the process cannot chmod makes start-up fail. +- **Linux:** a symbolic link is refused, as on Windows, and so is a directory owned by anyone but the user Koppel runs as (its owner could swap what is in it). Then `chmod 700`. A bind-mounted config directory that the process cannot chmod makes start-up fail. Where the config directory is: @@ -65,12 +69,15 @@ with the same rules. through Docker bind mounts, where file change events may not arrive. - **Hardening:** as 0.1.x on Windows (owner Administrators, a protected ACL for SYSTEM and Administrators, an unelevated process keeping its own access, links refused, `%ProgramData%\Koppel` - itself when the folders are in it) and `chmod 700` on Linux. + itself when the folders are in it), and on Linux a link refused, the owner checked and `chmod 700`. - **Session key:** `ui-session.key` in the keys directory, sealed the same way, signs the UI's session cookies (see ["The UI's server side in Rust"](ui.md#the-uis-server-side-in-rust)). - **Secret files:** a six byte header, `KPSF`, a format version (1) and a scheme. Scheme 1, on Windows, is machine DPAPI over the JSON. Scheme 2, elsewhere, is AES-256-GCM with a random key in `koppel-secrets.key` in the keys directory, mode `0600`; the file then holds that key's id and a - nonce before the ciphertext. Data Protection's key ring is no longer used. As before, anyone who can + nonce before the ciphertext. The key file is made through a temp file and a hard link, so it never + exists half written; on a file system without hard links (some network, FUSE and Docker bind + mounts) it is made in place with `create_new`, and a start that meets it mid-write waits for it. + Two Koppels starting together end up with one key either way. Data Protection's key ring is no longer used. As before, anyone who can read the keys directory on Linux can decrypt the files. - **The upgrade from 0.1.x:** at the first start, each of `secrets.json`, `connection.json` and `ui-auth.json` that is still a Data Protection payload is decrypted with the 0.1.x key ring (machine diff --git a/src/Cargo.lock b/src/Cargo.lock index d086d2f..90a7da5 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -923,6 +923,7 @@ dependencies = [ "cbc", "des", "koppel-web", + "libc", "ring", "roxmltree", "rustls", diff --git a/src/Cargo.toml b/src/Cargo.toml index f25d585..e1305d4 100644 --- a/src/Cargo.toml +++ b/src/Cargo.toml @@ -119,7 +119,8 @@ windows-service = "0.8.1" winresource = "0.1.34" # The USB layer (koppel-usb). libc (MIT OR Apache-2.0), already here through tokio, for the one -# ioctl sysfs cannot do: resetting a USB device through its usbfs node on Linux. +# ioctl sysfs cannot do: resetting a USB device through its usbfs node on Linux. koppel-config takes +# it too, for `geteuid`, to check who owns the config and keys directories. libc = "0.2.191" # The transport between Koppel machines: Skakel 0.2.1 (MIT), protocol version 2 over gRPC, from its diff --git a/src/koppel-config/Cargo.toml b/src/koppel-config/Cargo.toml index b1203a2..a03452b 100644 --- a/src/koppel-config/Cargo.toml +++ b/src/koppel-config/Cargo.toml @@ -22,6 +22,9 @@ cbc.workspace = true des.workspace = true roxmltree.workspace = true +[target.'cfg(unix)'.dependencies] +libc.workspace = true + [target.'cfg(windows)'.dependencies] windows.workspace = true diff --git a/src/koppel-config/src/file.rs b/src/koppel-config/src/file.rs index c701ba7..9bd4b33 100644 --- a/src/koppel-config/src/file.rs +++ b/src/koppel-config/src/file.rs @@ -13,23 +13,35 @@ //! stays; a good one is loaded before the next change, so a change never undoes it. //! - Changes reach subscribers in write order, one at a time. A subscriber may change the same file //! from its handler: that change is written at once and its delivery queued behind the running -//! one, and the call returns without waiting for it, since it would wait for itself. +//! one, and the call returns without waiting for it, since it would wait for itself. A handler +//! that changes the file from another task and waits for it is not seen as nested; the call then +//! gives up waiting for the delivery after [`Options::delivery_timeout`] (the change is already +//! on disk) instead of waiting forever. +//! - A write is durable when `update` returns: the temp file is flushed, moved over the file, and +//! the directory is flushed too, so a power cut cannot bring the old file back. +//! - The file holds a `version` (1). A file with a newer one is refused, as a secret file with a +//! newer format is. Names Koppel does not know in a hand-edited file are logged, and are gone +//! after the next write. //! //! Hand edits are found by looking at the file's size and time every quarter second rather than //! through the operating system's change events: those do not arrive through every Docker bind -//! mount, and the poll costs one `stat` per file. +//! mount, and the poll costs one `stat` per file. A changed file is told from our own write by a +//! SHA-256 of its bytes, and a file written in the last few seconds is hashed on every round, so +//! an edit that leaves the size and a coarse time as they were is still seen. use std::fmt; use std::fs; -use std::io::{self, Write}; +use std::io::{self, Read as _, Write}; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError, Weak}; use std::time::{Duration, SystemTime}; +use ring::digest; use serde::Serialize; use serde::de::DeserializeOwned; +use serde_json::Value; use time::OffsetDateTime; use tokio::sync::{mpsc, oneshot}; use tokio::task::JoinHandle; @@ -42,6 +54,13 @@ const REPLACE_ATTEMPTS: u32 = 20; const REPLACE_RETRY_DELAY: Duration = Duration::from_millis(100); const TEMP_SUFFIX: &str = ".tmp"; const WATCH_INTERVAL: Duration = Duration::from_millis(250); +/// A file this young is hashed every round, since a coarse clock may give an edit its time. +const RECENT: Duration = Duration::from_secs(3); +/// The most a config file may hold. Real ones are a few kilobytes. +const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024; +/// The `version` this code writes and the newest it reads. +const FORMAT_VERSION: u64 = 1; +const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15); /// Turns a file's JSON into the bytes on disk and back, so a file can be encrypted. pub trait FileCodec: Send + Sync { @@ -75,32 +94,68 @@ impl FileCodec for PlainText { } } -/// A config file exists but cannot be used, or a change could not be written. The file is left -/// exactly as it was. The wording is 0.1.x's. +/// What kind of trouble a config file had, so a caller can tell a full disk from a missing key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum ConfigErrorKind { + /// The file could not be read or written: permissions, a full disk, a lock that did not clear, + /// a file over the size limit. + Io, + /// The encrypted file did not open: another key, or damaged. + Decrypt, + /// The text is not JSON for this file. + Parse, + /// It parsed, but the value is not acceptable. + Invalid, + /// The file says it is a newer version than this Koppel reads. + Newer, +} + +/// A config file exists but cannot be used, or a change could not be written. The wording of the +/// advice follows the kind; the `reason` is one line about this file. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ConfigFileError { /// The file. pub path: PathBuf, + /// What went wrong. + pub kind: ConfigErrorKind, /// What is wrong with it, in one line. pub reason: String, } impl ConfigFileError { - fn new(path: &Path, reason: impl Into) -> Self { + pub(crate) fn new(path: &Path, kind: ConfigErrorKind, reason: impl Into) -> Self { Self { path: path.to_path_buf(), + kind, reason: reason.into(), } } + + pub(crate) fn io(path: &Path, reason: impl Into) -> Self { + Self::new(path, ConfigErrorKind::Io, reason) + } } impl fmt::Display for ConfigFileError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let advice = match self.kind { + ConfigErrorKind::Io => { + "Check the disk and the permissions of its directory. A change that was being saved may not have been kept." + } + ConfigErrorKind::Decrypt => { + "The file was not changed. The key ring that encrypted it is missing or has changed: restore the keys directory. Then start Koppel again." + } + ConfigErrorKind::Parse | ConfigErrorKind::Invalid => { + "The file was not changed. If it was edited by hand, fix the edit or restore the file. Then start Koppel again." + } + ConfigErrorKind::Newer => { + "The file was not changed. Install the Koppel that wrote it, or restore an older copy of the file." + } + }; write!( f, - "Koppel cannot use {}: {}. The file was not changed. If it is encrypted, the key ring that \ - encrypted it is missing or has changed: restore the keys directory. If it was edited by \ - hand, fix the edit or restore the file. Then start Koppel again.", + "Koppel cannot use {}: {}. {advice}", self.path.display(), self.reason ) @@ -125,6 +180,11 @@ pub struct Options { /// Start with the defaults, and the file untouched, when it exists but cannot be used. Only /// for plain files whose defaults are safe. pub start_with_defaults_when_unusable: bool, + /// Log the names in the file that Koppel does not know. For the files people edit by hand. + pub warn_unknown_keys: bool, + /// How long `update` waits for the subscribers to finish with its change before it returns + /// anyway. The change is on disk by then. + pub delivery_timeout: Duration, } impl Default for Options { @@ -133,6 +193,8 @@ impl Default for Options { codec: Arc::new(PlainText), validate: None, start_with_defaults_when_unusable: false, + warn_unknown_keys: false, + delivery_timeout: DELIVERY_TIMEOUT, } } } @@ -140,10 +202,27 @@ impl Default for Options { /// The size and time of the file, to see that it changed. type Stamp = (u64, SystemTime); +/// SHA-256 of a file's bytes. +type Hash = [u8; 32]; + +/// What was last on disk: the size and time, and the bytes' hash. The hash is what says a file is +/// ours, the stamp only says when it is worth looking. +#[derive(Clone, Copy, PartialEq, Eq)] +struct Seen { + stamp: Stamp, + hash: Hash, +} + +fn hash_of(bytes: &[u8]) -> Hash { + digest::digest(&digest::SHA256, bytes) + .as_ref() + .try_into() + .expect("SHA-256 is 32 bytes") +} + struct State { current: Arc, - current_json: Vec, - last_stamp: Option, + last: Option, problem: Option, } @@ -169,6 +248,8 @@ struct Inner { codec: Arc, validate: Option>, lenient: bool, + warn_unknown_keys: bool, + delivery_timeout: Duration, gate: tokio::sync::Mutex<()>, state: Mutex>, handlers: Mutex)>>, @@ -209,11 +290,10 @@ pub struct Subscription(u64); impl ConfigFile where - T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, + T: Serialize + DeserializeOwned + Clone + PartialEq + Send + Sync + 'static, { /// A file at `path` holding `defaults` until it is started. pub fn new(path: impl Into, defaults: T, options: Options) -> Self { - let current_json = json::to_vec(&defaults).expect("a config value always serializes"); let (deliveries, receiver) = mpsc::unbounded_channel(); Self { inner: Arc::new(Inner { @@ -223,11 +303,12 @@ where codec: options.codec, validate: options.validate, lenient: options.start_with_defaults_when_unusable, + warn_unknown_keys: options.warn_unknown_keys, + delivery_timeout: options.delivery_timeout, gate: tokio::sync::Mutex::new(()), state: Mutex::new(State { current: Arc::new(defaults), - current_json, - last_stamp: None, + last: None, problem: None, }), handlers: Mutex::new(Vec::new()), @@ -280,7 +361,7 @@ where .map(Path::to_path_buf) .unwrap_or_default(); fs::create_dir_all(&directory).map_err(|e| { - ConfigFileError::new( + ConfigFileError::io( &inner.path, format!("its directory could not be made ({e})"), ) @@ -288,7 +369,8 @@ where delete_stale_temp_files(&inner.path); if inner.path.exists() { match inner.load().await { - Ok((value, stamp)) => inner.set_current(value, Some(stamp)), + Ok(Loaded::New(value, seen)) => inner.set_current(value, seen), + Ok(Loaded::Same(_)) => {} Err(e) if inner.lenient => { lock(&inner.state).problem = Some(e.reason.clone()); tracing::warn!( @@ -300,8 +382,8 @@ where Err(e) => return Err(e), } } else { - let stamp = inner.write(&inner.defaults).await?; - lock(&inner.state).last_stamp = Some(stamp); + let seen = inner.write(&inner.defaults).await?; + lock(&inner.state).last = Some(seen); tracing::info!("Wrote defaults to {}", inner.path.display()); } @@ -324,8 +406,9 @@ where /// value as it was skips the write but is still delivered once, because whoever asked waits /// for it. A hand edit made since the last read or write is loaded first. /// - /// Waits until the subscribers have seen the change, except when called from inside one of - /// this file's deliveries. + /// Returns once the subscribers have seen the change, except when called from inside one of + /// this file's deliveries, and except after [`Options::delivery_timeout`]: the change is on + /// disk by then, and a handler that is stuck cannot hold the caller for ever. pub async fn update(&self, change: impl FnOnce(&T) -> T) -> Result, ConfigFileError> { let inner = &self.inner; let context = DELIVERING.try_with(Clone::clone).unwrap_or_default(); @@ -335,42 +418,51 @@ where inner.pick_up_hand_edit().await?; let current = self.current(); let next = change(¤t); - let next_json = json::to_vec(&next).expect("a config value always serializes"); - let unchanged = next_json == lock(&inner.state).current_json; + let unchanged = *current == next; if !unchanged || !inner.path.exists() { - let stamp = inner.write(&next).await?; - lock(&inner.state).last_stamp = Some(stamp); + let seen = inner.write(&next).await?; + lock(&inner.state).last = Some(seen); } let next = Arc::new(next); { let mut state = lock(&inner.state); state.current = next.clone(); - state.current_json = next_json; state.problem = None; } let done = inner.enqueue(next.clone(), context); (next, done) }; - if !nested { - let _ = done.await; + if !nested + && tokio::time::timeout(inner.delivery_timeout, done) + .await + .is_err() + { + tracing::warn!( + "The subscribers of {} were still busy {} seconds after a change, which is on disk; not waiting for them", + inner.path.display(), + inner.delivery_timeout.as_secs() + ); } Ok(next) } } +/// What reading the file found. +enum Loaded { + /// The bytes are the ones we already know, so nothing was decoded. + Same(Seen), + New(T, Seen), +} + impl Inner where - T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, + T: Serialize + DeserializeOwned + Clone + PartialEq + Send + Sync + 'static, { - fn set_current(&self, value: T, stamp: Option) { - let current_json = json::to_vec(&value).expect("a config value always serializes"); + fn set_current(&self, value: T, seen: Seen) { let mut state = lock(&self.state); state.current = Arc::new(value); - state.current_json = current_json; state.problem = None; - if stamp.is_some() { - state.last_stamp = stamp; - } + state.last = Some(seen); } /// Queues a delivery. Called under the gate, so deliveries keep the order of the writes. @@ -387,31 +479,43 @@ where waiter } - /// Reads, decodes, parses and checks the file. Retries a file that is briefly locked. - async fn load(&self) -> Result<(T, Stamp), ConfigFileError> { + /// Reads, decodes, parses and checks the file. Retries a file that is briefly locked or being + /// written. Bytes that hash as the last ones seen are not decoded again. + async fn load(&self) -> Result, ConfigFileError> { let path = self.path.clone(); let codec = self.codec.clone(); let validate = self.validate.clone(); + let warn_unknown_keys = self.warn_unknown_keys; + let known = lock(&self.state).last.map(|seen| seen.hash); tokio::task::spawn_blocking(move || { - load_blocking(&path, codec.as_ref(), validate.as_deref()) + load_blocking( + &path, + codec.as_ref(), + validate.as_deref(), + warn_unknown_keys, + known, + ) }) .await - .map_err(|e| ConfigFileError::new(&self.path, format!("it could not be read ({e})")))? + .map_err(|e| ConfigFileError::io(&self.path, format!("it could not be read ({e})")))? } - async fn write(&self, value: &T) -> Result { - let json = json::to_vec(value).expect("a config value always serializes"); + async fn write(&self, value: &T) -> Result { + let json = versioned_json(value); let path = self.path.clone(); let codec = self.codec.clone(); tokio::task::spawn_blocking(move || { let bytes = codec.encode(&json).map_err(|e| { - ConfigFileError::new(&path, format!("it could not be encrypted ({e})")) + ConfigFileError::io(&path, format!("it could not be encrypted ({e})")) })?; - write_atomic(&path, &bytes) - .map_err(|e| ConfigFileError::new(&path, format!("it could not be written ({e})"))) + let hash = hash_of(&bytes); + let stamp = write_atomic(&path, &bytes).map_err(|e| { + ConfigFileError::io(&path, format!("it could not be written ({e})")) + })?; + Ok(Seen { stamp, hash }) }) .await - .map_err(|e| ConfigFileError::new(&self.path, format!("it could not be written ({e})")))? + .map_err(|e| ConfigFileError::io(&self.path, format!("it could not be written ({e})")))? } /// Under the gate: loads the file when it changed behind our back and is usable. @@ -419,11 +523,13 @@ where let Some(stamp) = stamp(&self.path) else { return Ok(()); }; - if Some(stamp) == lock(&self.state).last_stamp { + let last = lock(&self.state).last; + if Some(stamp) == last.map(|seen| seen.stamp) && !recent(stamp.1) { return Ok(()); } match self.load().await { - Ok((value, stamp)) => self.set_current(value, Some(stamp)), + Ok(Loaded::New(value, seen)) => self.set_current(value, seen), + Ok(Loaded::Same(seen)) => lock(&self.state).last = Some(seen), Err(e) if self.lenient => self.move_aside(&e.reason)?, Err(e) => tracing::warn!( "{} was edited by hand but is not usable ({}); this update replaces it", @@ -443,7 +549,7 @@ where )); let aside = PathBuf::from(aside); fs::rename(&self.path, &aside).map_err(|e| { - ConfigFileError::new( + ConfigFileError::io( &self.path, format!("it is not usable ({reason}) and could not be moved aside ({e})"), ) @@ -461,21 +567,27 @@ where let done = { let _gate = self.gate.lock().await; match self.load().await { - Ok((value, stamp)) => { - let json = json::to_vec(&value).expect("a config value always serializes"); - let changed = json != lock(&self.state).current_json; + Ok(Loaded::New(value, seen)) => { + let changed = *lock(&self.state).current != value; if changed { - self.set_current(value, Some(stamp)); + self.set_current(value, seen); let current = lock(&self.state).current.clone(); Some(self.enqueue(current, Vec::new())) } else { - // Our own writes land here too; they read back the same and are ignored. + // An edit that leaves the value as it was, such as another layout. let mut state = lock(&self.state); state.problem = None; - state.last_stamp = Some(stamp); + state.last = Some(seen); None } } + Ok(Loaded::Same(seen)) => { + // Our own write, or the bad file put back as it was. + let mut state = lock(&self.state); + state.problem = None; + state.last = Some(seen); + None + } Err(e) => { lock(&self.state).problem = Some(e.reason.clone()); tracing::warn!( @@ -493,6 +605,21 @@ where } true } + + /// Whether the bytes on disk are not the ones last seen. A file that cannot be read says no. + async fn bytes_differ(&self) -> bool { + let path = self.path.clone(); + let Some(known) = lock(&self.state).last.map(|seen| seen.hash) else { + return true; + }; + tokio::task::spawn_blocking(move || match read_once(&path) { + Ok(Read::Stable(bytes, _)) => hash_of(&bytes) != known, + Ok(Read::TooLarge | Read::Changed) => true, + Err(_) => false, + }) + .await + .unwrap_or(false) + } } /// Delivers changes one at a time, each handler in turn. A handler that panics is logged and the @@ -533,7 +660,7 @@ async fn deliver( /// tried again until it changes. async fn watch(file: Weak>) where - T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, + T: Serialize + DeserializeOwned + Clone + PartialEq + Send + Sync + 'static, { let mut seen: Option = None; let mut refused: Option = None; @@ -542,12 +669,18 @@ where let Some(inner) = file.upgrade() else { return; }; - let now = stamp(&inner.path); - let last = lock(&inner.state).last_stamp; - let Some(now) = now.filter(|s| Some(*s) != last && Some(*s) != refused) else { + let Some(now) = stamp(&inner.path).filter(|s| Some(*s) != refused) else { seen = None; continue; }; + let last = lock(&inner.state).last.map(|seen| seen.stamp); + // The size and time say when to look. A file written a moment ago is looked at every round, + // because a coarse clock can give a second edit the time of the first. + let changed = Some(now) != last || (recent(now.1) && inner.bytes_differ().await); + if !changed { + seen = None; + continue; + } if seen != Some(now) { seen = Some(now); continue; @@ -559,69 +692,241 @@ where } } +fn stamp_of(metadata: &fs::Metadata) -> Stamp { + ( + metadata.len(), + metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH), + ) +} + fn stamp(path: &Path) -> Option { - let metadata = fs::metadata(path).ok()?; - Some((metadata.len(), metadata.modified().ok()?)) + fs::metadata(path).ok().map(|m| stamp_of(&m)) } -fn load_blocking( +/// A file touched this recently may share its time with the next edit. +fn recent(modified: SystemTime) -> bool { + let apart = match SystemTime::now().duration_since(modified) { + Ok(age) => age, + Err(ahead) => ahead.duration(), + }; + apart < RECENT +} + +/// What one pass at reading a file found. +enum Read { + /// The bytes, and the size and time of the file they came from. + Stable(Vec, Stamp), + /// The file changed while it was read. + Changed, + TooLarge, +} + +/// Reads the whole file through one handle, so the bytes and the stamp belong together, and not +/// more than [`MAX_FILE_BYTES`]. +fn read_once(path: &Path) -> io::Result { + let file = fs::File::open(path)?; + let before = stamp_of(&file.metadata()?); + if before.0 > MAX_FILE_BYTES { + return Ok(Read::TooLarge); + } + let mut bytes = Vec::with_capacity(before.0 as usize); + (&file).take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Ok(Read::TooLarge); + } + let after = stamp_of(&file.metadata()?); + if before != after || bytes.len() as u64 != after.0 { + return Ok(Read::Changed); + } + Ok(Read::Stable(bytes, after)) +} + +fn load_blocking( path: &Path, codec: &dyn FileCodec, validate: Option<&ValidateFn>, -) -> Result<(T, Stamp), ConfigFileError> { + warn_unknown_keys: bool, + known: Option, +) -> Result, ConfigFileError> { let mut attempt = 1; let (bytes, stamp) = loop { - let before = stamp(path); - match fs::read(path) { - Ok(bytes) => break (bytes, before.unwrap_or((0, SystemTime::UNIX_EPOCH))), - Err(_) if attempt < READ_ATTEMPTS => { - attempt += 1; - std::thread::sleep(READ_RETRY_DELAY); - } - Err(e) => { - return Err(ConfigFileError::new( + let trouble = match read_once(path) { + Ok(Read::Stable(bytes, stamp)) => break (bytes, stamp), + Ok(Read::TooLarge) => { + return Err(ConfigFileError::io( path, - format!("it could not be read ({e})"), + format!("it is larger than {} MiB", MAX_FILE_BYTES / (1024 * 1024)), )); } + Ok(Read::Changed) => "it kept changing while it was read".to_string(), + Err(e) => format!("it could not be read ({e})"), + }; + if attempt >= READ_ATTEMPTS { + return Err(ConfigFileError::io(path, trouble)); } + attempt += 1; + std::thread::sleep(READ_RETRY_DELAY); + }; + let seen = Seen { + stamp, + hash: hash_of(&bytes), }; - let text = codec - .decode(&bytes) - .map_err(|e| ConfigFileError::new(path, format!("it could not be decrypted ({e})")))?; + if known == Some(seen.hash) { + return Ok(Loaded::Same(seen)); + } + let text = codec.decode(&bytes).map_err(|e| { + ConfigFileError::new( + path, + ConfigErrorKind::Decrypt, + format!("it could not be decrypted ({e})"), + ) + })?; let not_json = |e: serde_json::Error| { - ConfigFileError::new(path, format!("it is not valid JSON for this file ({e})")) + ConfigFileError::new( + path, + ConfigErrorKind::Parse, + format!("it is not valid JSON for this file ({e})"), + ) }; - let value = json::parse(&text).map_err(not_json)?; + let mut value = json::parse(&text).map_err(not_json)?; if value.is_null() { - return Err(ConfigFileError::new(path, "it holds no value")); + return Err(ConfigFileError::new( + path, + ConfigErrorKind::Invalid, + "it holds no value", + )); } + take_version(path, &mut value)?; + let names: Vec = match (&value, warn_unknown_keys) { + (Value::Object(map), true) => map.keys().cloned().collect(), + _ => Vec::new(), + }; let value: T = json::from_value(value).map_err(not_json)?; if let Some(invalid) = validate.and_then(|validate| validate(&value)) { return Err(ConfigFileError::new( path, + ConfigErrorKind::Invalid, format!("it is not valid ({invalid})"), )); } - Ok((value, stamp)) + let unknown = unknown_names(&names, &value); + if !unknown.is_empty() { + tracing::warn!( + "{} has names Koppel does not know ({}). They are ignored, and gone after the next change Koppel writes", + path.display(), + unknown.join(", ") + ); + } + Ok(Loaded::New(value, seen)) +} + +/// Takes `version` out of the file's top level. A file from a newer Koppel is refused, since +/// writing it back would drop what that Koppel put there. A file without one is version 1. +fn take_version(path: &Path, value: &mut Value) -> Result<(), ConfigFileError> { + let Value::Object(map) = value else { + return Ok(()); + }; + let Some(key) = map + .keys() + .find(|key| key.eq_ignore_ascii_case("version")) + .cloned() + else { + return Ok(()); + }; + match map.shift_remove(&key).and_then(|v| v.as_u64()) { + Some(version) if version > FORMAT_VERSION => Err(ConfigFileError::new( + path, + ConfigErrorKind::Newer, + format!( + "it is version {version}, written by a newer Koppel; this one reads version {FORMAT_VERSION}" + ), + )), + Some(_) => Ok(()), + None => Err(ConfigFileError::new( + path, + ConfigErrorKind::Invalid, + "its version is not a whole number", + )), + } } -/// Writes `bytes` to a random temp name beside `path`, flushes it to disk, and moves it over -/// `path`. The move is retried for a while, because on Windows a reader (an editor, antivirus) can -/// hold the target open for a moment. A failed write removes its temp file. +/// The top level names in `input` that `value` has no field for, matched without regard to case +/// as reading does. +fn unknown_names(input: &[String], value: &T) -> Vec { + if input.is_empty() { + return Vec::new(); + } + let Ok(Value::Object(known)) = json::to_vec(value) + .map_err(|_| ()) + .and_then(|bytes| json::parse(&bytes).map_err(|_| ())) + else { + return Vec::new(); + }; + input + .iter() + .filter(|name| !known.keys().any(|k| k.eq_ignore_ascii_case(name))) + .cloned() + .collect() +} + +/// What goes into the file: the value's fields as 0.1.x writes them, then `version`. +fn versioned_json(value: &T) -> Vec { + #[derive(Serialize)] + struct Versioned<'a, T> { + #[serde(flatten)] + value: &'a T, + version: u64, + } + json::to_vec(&Versioned { + value, + version: FORMAT_VERSION, + }) + .expect("a config value always serializes") +} + +/// The points in writing a file where a test can make it fail, to see what a crash leaves behind. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Step { + TempCreated, + TempWritten, + TempFlushed, + BeforeReplace, + Replaced, + DirectoryFlushed, +} + +/// Writes `bytes` to a random temp name beside `path`, flushes it to disk, moves it over `path` +/// and flushes the directory, so the new file survives a power cut. The temp file is `0600`. The +/// move is retried for a while, because on Windows a reader (an editor, antivirus) can hold the +/// target open for a moment. A failed write removes its temp file. Returns the new file's size and +/// time, taken from the file before it was moved, so an edit that lands after the move is not +/// mistaken for this write. pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result { + write_atomic_with(path, bytes, &|_| Ok(())) +} + +pub(crate) fn write_atomic_with( + path: &Path, + bytes: &[u8], + at: &dyn Fn(Step) -> io::Result<()>, +) -> io::Result { let mut temp = path.as_os_str().to_owned(); temp.push(format!(".{}{TEMP_SUFFIX}", crate::random_hex(16))); let temp = PathBuf::from(temp); let result = (|| { - let mut file = fs::File::create_new(&temp)?; + let mut file = create_private(&temp)?; + at(Step::TempCreated)?; file.write_all(bytes)?; + at(Step::TempWritten)?; file.sync_all()?; + at(Step::TempFlushed)?; + let stamp = stamp_of(&file.metadata()?); drop(file); + at(Step::BeforeReplace)?; let mut attempt = 1; loop { match fs::rename(&temp, path) { - Ok(()) => return Ok(()), + Ok(()) => break, Err(_) if attempt < REPLACE_ATTEMPTS => { attempt += 1; std::thread::sleep(REPLACE_RETRY_DELAY); @@ -629,12 +934,59 @@ pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result { Err(e) => return Err(e), } } + at(Step::Replaced)?; + sync_directory(path)?; + at(Step::DirectoryFlushed)?; + Ok(stamp) })(); - if let Err(e) = result { + if result.is_err() { let _ = fs::remove_file(&temp); - return Err(e); } - Ok(stamp(path).unwrap_or((0, SystemTime::UNIX_EPOCH))) + result +} + +/// A new file that only its owner can read, where the platform has modes. On Windows the +/// directory's access list decides, and the config directories are restricted already. +pub(crate) fn create_private(path: &Path) -> io::Result { + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path) +} + +/// Flushes the directory `path` is in, so a file moved or made there is not undone by a power cut. +/// Windows keeps its file system's metadata in a journal and has no call for this. A file system +/// that cannot flush a directory (some network and FUSE mounts) says so with an error that is not +/// worth failing a write over. +pub(crate) fn sync_directory(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + let directory = match path.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent, + _ => Path::new("."), + }; + match fs::File::open(directory).and_then(|d| d.sync_all()) { + Err(e) + if matches!( + e.kind(), + io::ErrorKind::InvalidInput | io::ErrorKind::Unsupported + ) => + { + tracing::debug!( + "{} cannot be flushed ({e}); relying on the file system", + directory.display() + ); + Ok(()) + } + other => other, + } + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } } /// Leftovers of a crash between creating a temp file and moving it: `name.*.tmp`. Nothing else @@ -675,3 +1027,192 @@ pub(crate) fn utc_stamp(now: OffsetDateTime) -> String { now.millisecond() ) } + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + + use super::*; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("koppel-file-{name}-{}", crate::random_hex(6))); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn leftovers(dir: &Path) -> Vec { + fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(TEMP_SUFFIX)) + .collect() + } + + const ALL_STEPS: [Step; 6] = [ + Step::TempCreated, + Step::TempWritten, + Step::TempFlushed, + Step::BeforeReplace, + Step::Replaced, + Step::DirectoryFlushed, + ]; + + #[test] + fn a_write_goes_through_every_step_in_order_and_flushes_the_directory_last() { + let dir = temp_dir("steps"); + let seen = RefCell::new(Vec::new()); + write_atomic_with(&dir.join("a.json"), b"new", &|step| { + seen.borrow_mut().push(step); + Ok(()) + }) + .unwrap(); + assert_eq!(*seen.borrow(), ALL_STEPS); + assert_eq!(fs::read(dir.join("a.json")).unwrap(), b"new"); + let _ = fs::remove_dir_all(dir); + } + + /// A failure at each point stands for the process dying there. Before the replace the old file + /// is whole and no temp file is left behind; from the replace on, the new file is whole. + #[test] + fn a_failure_at_any_step_leaves_the_old_file_or_the_whole_new_one() { + for failing in ALL_STEPS { + let dir = temp_dir("crash"); + let target = dir.join("a.json"); + fs::write(&target, b"old contents").unwrap(); + + let result = write_atomic_with(&target, b"new contents, longer", &|step| { + if step == failing { + Err(io::Error::other("injected")) + } else { + Ok(()) + } + }); + + assert!(result.is_err(), "{failing:?}"); + let on_disk = fs::read(&target).unwrap(); + let replaced = matches!(failing, Step::Replaced | Step::DirectoryFlushed); + let expected: &[u8] = if replaced { + b"new contents, longer" + } else { + b"old contents" + }; + assert_eq!(on_disk, expected, "{failing:?}"); + assert!(leftovers(&dir).is_empty(), "{failing:?}"); + let _ = fs::remove_dir_all(dir); + } + } + + #[test] + fn a_failure_to_make_the_file_leaves_no_file_at_all() { + let dir = temp_dir("fresh"); + let target = dir.join("a.json"); + let result = write_atomic_with(&target, b"x", &|step| { + if step == Step::TempWritten { + Err(io::Error::other("disk full")) + } else { + Ok(()) + } + }); + assert!(result.is_err()); + assert!(!target.exists()); + assert!(leftovers(&dir).is_empty()); + let _ = fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn the_temp_file_and_so_the_file_are_for_their_owner_only() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("mode"); + let seen = RefCell::new(None); + write_atomic_with(&dir.join("a.json"), b"x", &|step| { + if step == Step::TempCreated { + // The temp file is the only entry with the suffix at this point. + let temp = leftovers(&dir).pop().unwrap(); + *seen.borrow_mut() = + Some(fs::metadata(dir.join(temp)).unwrap().permissions().mode() & 0o777); + } + Ok(()) + }) + .unwrap(); + assert_eq!(*seen.borrow(), Some(0o600)); + let mode = fs::metadata(dir.join("a.json")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn the_stamp_is_the_files_own_size_and_time_so_nothing_slips_in_after_the_move() { + let dir = temp_dir("stamp"); + let target = dir.join("a.json"); + let stamp = write_atomic(&target, b"{}").unwrap(); + assert_eq!(stamp, super::stamp(&target).unwrap()); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_files_version_is_read_and_a_newer_one_refused() { + let path = Path::new("x.json"); + let mut plain: Value = serde_json::from_str(r#"{"role":"client"}"#).unwrap(); + take_version(path, &mut plain).unwrap(); + + let mut current: Value = serde_json::from_str(r#"{"Version":1,"role":"client"}"#).unwrap(); + take_version(path, &mut current).unwrap(); + assert!(current.get("Version").is_none(), "taken out of the value"); + + let mut newer: Value = serde_json::from_str(r#"{"version":2}"#).unwrap(); + let refused = take_version(path, &mut newer).unwrap_err(); + assert_eq!(refused.kind, ConfigErrorKind::Newer); + + for odd in [ + r#"{"version":"1"}"#, + r#"{"version":-1}"#, + r#"{"version":1.5}"#, + ] { + let mut value: Value = serde_json::from_str(odd).unwrap(); + assert_eq!( + take_version(path, &mut value).unwrap_err().kind, + ConfigErrorKind::Invalid, + "{odd}" + ); + } + } + + #[test] + fn names_the_type_has_no_field_for_are_found_in_any_case() { + let settings = crate::files::KoppelSettings::default(); + let input: Vec = ["Role", "shareOnStartup", "colour", "NOTIFYLINK", "x"] + .map(String::from) + .to_vec(); + assert_eq!(unknown_names(&input, &settings), ["colour", "x"]); + assert!(unknown_names(&[], &settings).is_empty()); + } + + #[test] + fn what_is_written_ends_with_the_version_after_the_fields_as_before() { + let text = String::from_utf8(versioned_json(&crate::files::KoppelSettings::default())) + .unwrap() + .replace("\r\n", "\n"); + assert!(text.starts_with("{\n \"role\": \"server\",\n"), "{text}"); + assert!( + text.ends_with("\"notifyAttachFailures\": true,\n \"version\": 1\n}"), + "{text}" + ); + } + + #[test] + fn each_kind_of_error_gives_its_own_advice() { + let path = Path::new("secrets.json"); + let advice = |kind| ConfigFileError::new(path, kind, "why").to_string(); + assert!(advice(ConfigErrorKind::Decrypt).contains("restore the keys directory")); + assert!(advice(ConfigErrorKind::Parse).contains("fix the edit")); + assert!(advice(ConfigErrorKind::Invalid).contains("fix the edit")); + assert!(advice(ConfigErrorKind::Newer).contains("Install the Koppel that wrote it")); + let io = advice(ConfigErrorKind::Io); + assert!(!io.contains("restore the keys directory"), "{io}"); + assert!(io.starts_with("Koppel cannot use secrets.json: why. ")); + } +} diff --git a/src/koppel-config/src/files.rs b/src/koppel-config/src/files.rs index cc207c4..39b90c1 100644 --- a/src/koppel-config/src/files.rs +++ b/src/koppel-config/src/files.rs @@ -83,8 +83,9 @@ pub struct KoppelSettings { /// A missing role is the enum's first value, as .NET reads it. #[serde(default)] pub role: Role, - /// Share the devices that were shared before a restart. Missing reads as false, as in .NET. - #[serde(default)] + /// Share the devices that were shared before a restart. Missing reads as true, the same as a + /// new install writes. 0.1.x read a missing value as false. + #[serde(default = "yes")] pub share_on_startup: bool, /// False until the first-run setup in the UI is finished. #[serde(default)] @@ -526,13 +527,14 @@ mod tests { empty, KoppelSettings { role: Role::Server, - share_on_startup: false, + share_on_startup: true, setup_complete: false, notify_pairing: true, notify_link: true, notify_attach_failures: true } ); + assert_eq!(empty, KoppelSettings::default()); } #[test] diff --git a/src/koppel-config/src/harden.rs b/src/koppel-config/src/harden.rs index 3945840..9c8788e 100644 --- a/src/koppel-config/src/harden.rs +++ b/src/koppel-config/src/harden.rs @@ -7,8 +7,9 @@ //! would land on its target. A process that is not elevated cannot give the owner away and would //! lock itself out, so it also gets full control and the owner is left alone: that is a developer //! at a console, while the service runs as LocalSystem. -//! - **Elsewhere:** `chmod 700`. A directory that cannot be changed, such as a bind mount owned by -//! someone else, is an error. +//! - **Elsewhere:** a symbolic link is refused as on Windows, and so is a directory owned by +//! anyone but the user Koppel runs as, since its owner could swap what is in it. Then `chmod 700`. +//! A directory that cannot be changed, such as a bind mount owned by someone else, is an error. use std::io; use std::path::Path; @@ -21,9 +22,30 @@ pub fn harden_directory(directory: &Path) -> io::Result<()> { } #[cfg(not(windows))] { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700)) + harden_unix(directory) + } +} + +#[cfg(not(windows))] +fn harden_unix(directory: &Path) -> io::Result<()> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let metadata = std::fs::symlink_metadata(directory)?; + if metadata.file_type().is_symlink() { + return Err(io::Error::other(format!( + "{} is a symbolic link. Koppel will not keep its files behind a link: point Paths:Config and Paths:Keys at a real directory.", + directory.display() + ))); + } + // SAFETY: geteuid takes no arguments and cannot fail. + let user = unsafe { libc::geteuid() }; + if metadata.uid() != user { + return Err(io::Error::other(format!( + "{} belongs to user {}, not to user {user}, which Koppel runs as. Its owner could swap what is in it: give it to the user Koppel runs as.", + directory.display(), + metadata.uid() + ))); } + std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700)) } #[cfg(windows)] @@ -230,6 +252,39 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[cfg(unix)] + #[test] + fn a_symbolic_link_is_refused() { + let dir = temp_dir("symlink"); + let target = dir.join("target"); + std::fs::create_dir(&target).unwrap(); + let link = dir.join("link"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let refused = harden_directory(&link).unwrap_err(); + assert!(refused.to_string().contains("symbolic link"), "{refused}"); + let _ = std::fs::remove_dir_all(dir); + } + + /// Needs root to give a directory away, which the test container is. + #[cfg(unix)] + #[test] + fn a_directory_owned_by_someone_else_is_refused() { + // SAFETY: geteuid takes no arguments and cannot fail. + if unsafe { libc::geteuid() } != 0 { + return; + } + let dir = temp_dir("owner"); + std::os::unix::fs::chown(&dir, Some(12345), None).unwrap(); + let refused = harden_directory(&dir).unwrap_err(); + assert!( + refused.to_string().contains("belongs to user 12345"), + "{refused}" + ); + std::os::unix::fs::chown(&dir, Some(0), None).unwrap(); + harden_directory(&dir).unwrap(); + let _ = std::fs::remove_dir_all(dir); + } + #[cfg(windows)] #[test] fn the_acl_is_protected_and_lists_only_system_administrators_and_an_unelevated_user() { diff --git a/src/koppel-config/src/lib.rs b/src/koppel-config/src/lib.rs index 6ea438a..b270260 100644 --- a/src/koppel-config/src/lib.rs +++ b/src/koppel-config/src/lib.rs @@ -33,8 +33,8 @@ use ring::rand::{SecureRandom, SystemRandom}; pub use certificate::{CertificateError, ServerCertificate}; pub use dataprotection::{DataProtectionError, KOPPEL_PURPOSES, KeyRing}; pub use file::{ - CodecError, ConfigFile, ConfigFileError, FileCodec, Options, PlainText, Subscription, - ValidateFn, Validator, + CodecError, ConfigErrorKind, ConfigFile, ConfigFileError, FileCodec, Options, PlainText, + Subscription, ValidateFn, Validator, }; pub use harden::harden_directory; pub use migrate::{Conversion, ConversionError, convert_0_1_secrets}; @@ -54,7 +54,10 @@ pub mod open { ConfigFile::new( paths.settings_file(), KoppelSettings::default(), - Options::default(), + Options { + warn_unknown_keys: true, + ..Options::default() + }, ) } @@ -65,6 +68,7 @@ pub mod open { SharedDevices::empty(), Options { start_with_defaults_when_unusable: true, + warn_unknown_keys: true, ..Options::default() }, ) @@ -77,6 +81,7 @@ pub mod open { AttachedDevices::empty(), Options { start_with_defaults_when_unusable: true, + warn_unknown_keys: true, ..Options::default() }, ) @@ -120,7 +125,7 @@ pub mod open { Options { codec: secrets.codec(), validate: Some(Arc::new(UiCredentials::invalid)), - start_with_defaults_when_unusable: false, + ..Options::default() }, ) } diff --git a/src/koppel-config/src/secret.rs b/src/koppel-config/src/secret.rs index 0bcf749..4a3726f 100644 --- a/src/koppel-config/src/secret.rs +++ b/src/koppel-config/src/secret.rs @@ -19,12 +19,13 @@ use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; +use std::time::Duration; use ring::aead::{AES_256_GCM, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey}; use ring::rand::{SecureRandom, SystemRandom}; use crate::dataprotection; -use crate::file::{CodecError, FileCodec}; +use crate::file::{CodecError, FileCodec, create_private, sync_directory}; /// What every secret file starts with. pub const MAGIC: [u8; 4] = *b"KPSF"; @@ -44,6 +45,9 @@ const KEY_MAGIC: [u8; 4] = *b"KPSK"; const KEY_ID_LEN: usize = 16; const KEY_LEN: usize = 32; const HEADER_LEN: usize = 6; +const KEY_FILE_LEN: usize = 5 + KEY_ID_LEN + KEY_LEN; +const KEY_FILE_WAITS: u32 = 30; +const KEY_FILE_WAIT: Duration = Duration::from_millis(100); /// Why a secret could not be sealed, opened, or its key loaded. #[derive(Debug)] @@ -147,14 +151,14 @@ impl SecretBox { path: path.clone(), reason, }; - let bytes = match fs::read(&path) { + let bytes = match read_key_file(&path) { Ok(bytes) => bytes, Err(e) if e.kind() == io::ErrorKind::NotFound => { create_key_file(&path, &random).map_err(|e| failed(e.to_string()))? } Err(e) => return Err(failed(e.to_string())), }; - if bytes.len() != 5 + KEY_ID_LEN + KEY_LEN || bytes[..4] != KEY_MAGIC { + if bytes.len() != KEY_FILE_LEN || bytes[..4] != KEY_MAGIC { return Err(failed("it is not a Koppel key file".into())); } if bytes[4] != VERSION { @@ -276,9 +280,20 @@ impl SecretBox { } } -/// Writes the key file once: to a temp file with mode `0600`, flushed, then linked into place so -/// it never exists half written and an existing one is never replaced. +/// Writes the key file once. The first choice is a temp file with mode `0600`, flushed, then linked +/// into place, so it never exists half written and an existing one is never replaced. A file system +/// without hard links (some network, FUSE and Docker bind mounts) refuses the link; the key file +/// is then made in place with `create_new`, which still never replaces one, and a start that finds +/// it while it is being written waits for it ([`read_key_file`]). The directory is flushed after. fn create_key_file(path: &Path, random: &SystemRandom) -> io::Result> { + create_key_file_with(path, random, &|from, to| fs::hard_link(from, to)) +} + +fn create_key_file_with( + path: &Path, + random: &SystemRandom, + link: &dyn Fn(&Path, &Path) -> io::Result<()>, +) -> io::Result> { let mut bytes = KEY_MAGIC.to_vec(); bytes.push(VERSION); let mut material = [0u8; KEY_ID_LEN + KEY_LEN]; @@ -290,26 +305,58 @@ fn create_key_file(path: &Path, random: &SystemRandom) -> io::Result> { let mut temp = path.as_os_str().to_owned(); temp.push(format!(".{}.tmp", crate::random_hex(16))); let temp = PathBuf::from(temp); - let result = (|| { - let mut options = fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - let mut file = options.open(&temp)?; + let linked = (|| { + let mut file = create_private(&temp)?; file.write_all(&bytes)?; file.sync_all()?; drop(file); - fs::hard_link(&temp, path) + link(&temp, path) })(); let _ = fs::remove_file(&temp); - match result { - Ok(()) => Ok(bytes), + let result = match linked { + Ok(()) => Ok(()), // Another start made it first: use that one. - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => fs::read(path), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => return read_key_file(path), + Err(e) => { + tracing::debug!( + "{} could not be linked into place ({e}); writing it in place", + path.display() + ); + write_in_place(path, &bytes) + } + }; + match result { + Ok(()) => { + sync_directory(path)?; + Ok(bytes) + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => read_key_file(path), Err(e) => Err(e), } } +/// The key file made where it will stay, for a file system that cannot link. A crash in the middle +/// leaves a short file, which a start refuses with the instruction to delete it: nothing was +/// sealed with a key that never finished being written. +fn write_in_place(path: &Path, bytes: &[u8]) -> io::Result<()> { + let mut file = create_private(path)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// Reads the key file, waiting a moment for one that another start is still writing. +fn read_key_file(path: &Path) -> io::Result> { + let mut bytes = fs::read(path)?; + for _ in 0..KEY_FILE_WAITS { + if bytes.len() >= KEY_FILE_LEN { + break; + } + std::thread::sleep(KEY_FILE_WAIT); + bytes = fs::read(path)?; + } + Ok(bytes) +} + struct SecretCodec(Arc); impl FileCodec for SecretCodec { @@ -416,6 +463,95 @@ mod tests { let _ = fs::remove_dir_all(dir); } + #[test] + fn a_file_system_without_hard_links_still_gets_a_key_file() { + let dir = temp_dir("nolinks"); + let path = dir.join(KEY_FILE); + let refuse = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported)); + + let made = create_key_file_with(&path, &SystemRandom::new(), &refuse).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), made); + let names: Vec<_> = fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names.len(), 1, "no temp file is left: {names:?}"); + // And it is a usable key file. + let first = SecretBox::with_key_file(&dir).unwrap(); + let sealed = first.protect(b"x").unwrap(); + assert_eq!( + SecretBox::with_key_file(&dir) + .unwrap() + .unprotect(&sealed) + .unwrap(), + b"x" + ); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn without_hard_links_an_existing_key_file_is_used_and_not_replaced() { + let dir = temp_dir("nolinks-exists"); + let existing = SecretBox::with_key_file(&dir).unwrap(); + let before = fs::read(dir.join(KEY_FILE)).unwrap(); + let refuse = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::PermissionDenied)); + + let made = + create_key_file_with(&dir.join(KEY_FILE), &SystemRandom::new(), &refuse).unwrap(); + + assert_eq!(made, before); + assert_eq!(fs::read(dir.join(KEY_FILE)).unwrap(), before); + let sealed = existing.protect(b"x").unwrap(); + assert!( + SecretBox::with_key_file(&dir) + .unwrap() + .unprotect(&sealed) + .is_ok() + ); + let _ = fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn the_key_file_made_in_place_is_for_its_owner_only() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("nolinks-mode"); + let refuse = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported)); + create_key_file_with(&dir.join(KEY_FILE), &SystemRandom::new(), &refuse).unwrap(); + let mode = fs::metadata(dir.join(KEY_FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_key_file_that_is_still_being_written_is_waited_for() { + let dir = temp_dir("slow"); + let path = dir.join(KEY_FILE); + let source = temp_dir("slow-source"); + let whole = { + SecretBox::with_key_file(&source).unwrap(); + fs::read(source.join(KEY_FILE)).unwrap() + }; + fs::write(&path, &whole[..10]).unwrap(); + let finish = { + let (path, whole) = (path.clone(), whole.clone()); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + fs::write(path, whole).unwrap(); + }) + }; + + let opened = SecretBox::with_key_file(&dir); + + finish.join().unwrap(); + assert!(opened.is_ok(), "{opened:?}"); + let _ = (fs::remove_dir_all(dir), fs::remove_dir_all(source)); + } + #[cfg(windows)] #[test] fn windows_seals_with_machine_dpapi() { diff --git a/src/koppel-config/tests/config_file.rs b/src/koppel-config/tests/config_file.rs index b45a3d1..04d2dc7 100644 --- a/src/koppel-config/tests/config_file.rs +++ b/src/koppel-config/tests/config_file.rs @@ -6,7 +6,10 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use koppel_config::files::{KoppelSettings, Role, SharedDevices}; -use koppel_config::{ConfigFile, KoppelPaths, Options, SecretBox, json, open}; +use koppel_config::{ + CodecError, ConfigErrorKind, ConfigFile, FileCodec, KoppelPaths, Options, PlainText, SecretBox, + json, open, +}; fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!( @@ -51,7 +54,7 @@ async fn a_missing_file_is_seeded_with_the_defaults_as_0_1_writes_them() { settings.start().await.unwrap(); let written = fs::read(paths.settings_file()).unwrap(); - let expected = "{\n \"role\": \"server\",\n \"shareOnStartup\": true,\n \"setupComplete\": false,\n \"notifyPairing\": true,\n \"notifyLink\": true,\n \"notifyAttachFailures\": true\n}"; + let expected = "{\n \"role\": \"server\",\n \"shareOnStartup\": true,\n \"setupComplete\": false,\n \"notifyPairing\": true,\n \"notifyLink\": true,\n \"notifyAttachFailures\": true,\n \"version\": 1\n}"; let expected = expected.replace('\n', if cfg!(windows) { "\r\n" } else { "\n" }); assert_eq!(String::from_utf8(written).unwrap(), expected); settings.stop(); @@ -99,7 +102,7 @@ async fn json_null_and_a_failed_check_are_named() { Options { codec: secrets.codec(), validate: Some(Arc::new(koppel_config::files::UiCredentials::invalid)), - start_with_defaults_when_unusable: false, + ..Options::default() }, ); assert_eq!( @@ -442,3 +445,275 @@ async fn an_encrypted_file_round_trips_and_is_not_readable_as_text() { again.stop(); let _ = fs::remove_dir_all(dir); } + +fn settings_text(role: &str) -> String { + format!(r#"{{ "role": "{role}", "shareOnStartup": true }}"#) +} + +/// Writes `edited` over the settings file and puts its time back as `modified`. +fn edit_keeping_the_time(path: &Path, edited: String, modified: std::time::SystemTime) { + fs::write(path, edited).unwrap(); + fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(modified) + .unwrap(); +} + +#[tokio::test] +async fn an_edit_with_the_same_size_and_time_as_our_write_is_still_seen() { + let dir = temp_dir("samestamp"); + let paths = paths(&dir); + let settings = open::settings(&paths); + settings.start().await.unwrap(); + settings.update(client()).await.unwrap(); + let written = fs::read_to_string(paths.settings_file()).unwrap(); + let modified = fs::metadata(paths.settings_file()) + .unwrap() + .modified() + .unwrap(); + + // "client" and "server" are both six letters, and the time is put back as it was: only the + // bytes tell this from our own write, as on a file system with a coarse clock. + let edited = written.replace("client", "server"); + assert_eq!(edited.len(), written.len()); + edit_keeping_the_time(&paths.settings_file(), edited, modified); + + eventually(|| settings.current().role == Role::Server).await; + settings.stop(); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn an_edit_over_our_own_write_is_not_taken_for_ours_by_an_update() { + let dir = temp_dir("samestamp-update"); + let paths = paths(&dir); + let settings = open::settings(&paths); + settings.start().await.unwrap(); + settings.update(client()).await.unwrap(); + let written = fs::read_to_string(paths.settings_file()).unwrap(); + let modified = fs::metadata(paths.settings_file()) + .unwrap() + .modified() + .unwrap(); + edit_keeping_the_time( + &paths.settings_file(), + written.replace("client", "server"), + modified, + ); + + // The change is made on top of the hand edit, not of what we wrote before it. + let next = settings + .update(|s| KoppelSettings { + setup_complete: true, + ..s.clone() + }) + .await + .unwrap(); + + assert_eq!((next.role, next.setup_complete), (Role::Server, true)); + settings.stop(); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn a_file_is_written_with_a_version_and_a_file_without_one_is_read() { + let dir = temp_dir("version"); + let paths = paths(&dir); + fs::write(paths.settings_file(), settings_text("client")).unwrap(); + let settings = open::settings(&paths); + settings.start().await.unwrap(); + assert_eq!(settings.current().role, Role::Client); + + settings + .update(|s| KoppelSettings { + setup_complete: true, + ..s.clone() + }) + .await + .unwrap(); + + let text = fs::read_to_string(paths.settings_file()).unwrap(); + assert!(text.contains("\"version\": 1"), "{text}"); + settings.stop(); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn a_file_from_a_newer_koppel_is_refused_and_left_alone() { + let dir = temp_dir("newer"); + let paths = paths(&dir); + let text = r#"{ "version": 2, "role": "client", "colour": "blue" }"#; + fs::write(paths.settings_file(), text).unwrap(); + + let error = open::settings(&paths).start().await.unwrap_err(); + + assert_eq!(error.kind, ConfigErrorKind::Newer); + assert!(error.to_string().contains("version 2"), "{error}"); + assert_eq!(fs::read_to_string(paths.settings_file()).unwrap(), text); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn errors_say_what_kind_of_trouble_it_was() { + let dir = temp_dir("kinds"); + let paths = paths(&dir); + for (text, kind) in [ + ("{ nope", ConfigErrorKind::Parse), + ("null", ConfigErrorKind::Invalid), + (r#"{"role":1}"#, ConfigErrorKind::Parse), + (r#"{"version":"x"}"#, ConfigErrorKind::Invalid), + ] { + fs::write(paths.settings_file(), text).unwrap(); + let error = open::settings(&paths).start().await.unwrap_err(); + assert_eq!(error.kind, kind, "{text}"); + } + + let secrets = Arc::new(SecretBox::with_key_file(&paths.keys).unwrap()); + let other_keys = dir.join("other-keys"); + fs::create_dir_all(&other_keys).unwrap(); + let sealed = SecretBox::with_key_file(&other_keys) + .unwrap() + .protect(b"{}") + .unwrap(); + fs::write(paths.connection_file(), sealed).unwrap(); + let error = open::connection(&paths, &secrets) + .start() + .await + .unwrap_err(); + assert_eq!(error.kind, ConfigErrorKind::Decrypt); + assert!(error.to_string().contains("restore the keys directory")); + + // A directory where the file should be cannot be read. + let blocked = dir.join("blocked.json"); + fs::create_dir(&blocked).unwrap(); + let error = ConfigFile::new(&blocked, KoppelSettings::default(), Options::default()) + .start() + .await + .unwrap_err(); + assert_eq!(error.kind, ConfigErrorKind::Io); + assert!(!error.to_string().contains("restore the keys directory")); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn a_file_over_the_size_limit_is_refused_without_reading_it_all() { + let dir = temp_dir("big"); + let paths = paths(&dir); + fs::write(paths.settings_file(), vec![b' '; 9 * 1024 * 1024]).unwrap(); + + let error = open::settings(&paths).start().await.unwrap_err(); + + assert_eq!(error.kind, ConfigErrorKind::Io); + assert!( + error.reason.contains("larger than 8 MiB"), + "{}", + error.reason + ); + let _ = fs::remove_dir_all(dir); +} + +/// Fails to encode from the second write on, as a full disk would. +struct FailsAfterFirst(Mutex); + +impl FileCodec for FailsAfterFirst { + fn encode(&self, json: &[u8]) -> Result, CodecError> { + let mut writes = self.0.lock().unwrap(); + *writes += 1; + if *writes > 1 { + return Err(CodecError("the disk is full".into())); + } + PlainText.encode(json) + } + + fn decode(&self, bytes: &[u8]) -> Result, CodecError> { + PlainText.decode(bytes) + } +} + +#[tokio::test] +async fn a_change_that_could_not_be_written_is_neither_kept_nor_delivered() { + let dir = temp_dir("fault"); + let paths = paths(&dir); + let settings = ConfigFile::new( + paths.settings_file(), + KoppelSettings::default(), + Options { + codec: Arc::new(FailsAfterFirst(Mutex::new(0))), + ..Options::default() + }, + ); + settings.start().await.unwrap(); + let before = fs::read(paths.settings_file()).unwrap(); + let delivered = Arc::new(Mutex::new(0)); + let count = delivered.clone(); + settings.subscribe(move |_| { + *count.lock().unwrap() += 1; + async {} + }); + + let error = settings.update(client()).await.unwrap_err(); + + assert_eq!(error.kind, ConfigErrorKind::Io); + assert_eq!(settings.current().role, Role::Server); + assert_eq!(fs::read(paths.settings_file()).unwrap(), before); + assert_eq!(*delivered.lock().unwrap(), 0); + let names: Vec<_> = fs::read_dir(&paths.config) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["settings.json"]); + settings.stop(); + let _ = fs::remove_dir_all(dir); +} + +#[tokio::test] +async fn a_handler_that_waits_for_a_change_from_another_task_does_not_hold_it_for_ever() { + let dir = temp_dir("deadlock"); + let paths = paths(&dir); + let settings = ConfigFile::new( + paths.settings_file(), + KoppelSettings::default(), + Options { + delivery_timeout: Duration::from_millis(400), + ..Options::default() + }, + ); + settings.start().await.unwrap(); + let finished = Arc::new(Mutex::new(Vec::::new())); + let log = finished.clone(); + let file = settings.clone(); + settings.subscribe(move |value: Arc| { + let log = log.clone(); + let file = file.clone(); + async move { + if value.role == Role::Client { + // A spawned task has lost the sign that it is inside a delivery, so its update + // waits for the delivery this handler is part of, which waits for it. + let waits = tokio::spawn(async move { + file.update(|s| KoppelSettings { + role: Role::Both, + ..s.clone() + }) + .await + .unwrap(); + }); + waits.await.unwrap(); + log.lock().unwrap().push("handler done".into()); + } + } + }); + + let started = std::time::Instant::now(); + tokio::time::timeout(Duration::from_secs(10), settings.update(client())) + .await + .expect("the update must not wait for ever") + .unwrap(); + + assert!(started.elapsed() < Duration::from_secs(5)); + eventually(|| finished.lock().unwrap().len() == 1).await; + assert_eq!(settings.current().role, Role::Both); + settings.stop(); + let _ = fs::remove_dir_all(dir); +} diff --git a/src/koppel-config/tests/key_file_race.rs b/src/koppel-config/tests/key_file_race.rs new file mode 100644 index 0000000..efadfa5 --- /dev/null +++ b/src/koppel-config/tests/key_file_race.rs @@ -0,0 +1,90 @@ +//! Several Koppel processes starting at once on a new install make one key file, and all use it. +//! The test starts itself again as the workers, so the processes are real. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use koppel_config::SecretBox; + +const DIRECTORY: &str = "KOPPEL_RACE_DIRECTORY"; +const GO: &str = "KOPPEL_RACE_GO"; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(text: &str) -> Vec { + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) + .collect() +} + +/// The worker. Without the environment it is not a test, so it passes. +#[test] +fn key_file_race_worker() { + let (Ok(directory), Ok(go)) = (std::env::var(DIRECTORY), std::env::var(GO)) else { + return; + }; + // Every worker waits for the same signal, so they open the key file together. + let waited = Instant::now(); + while !Path::new(&go).exists() { + assert!(waited.elapsed() < Duration::from_secs(20), "no signal"); + std::hint::spin_loop(); + } + let secrets = SecretBox::with_key_file(&PathBuf::from(directory)).unwrap(); + println!("SEALED {}", hex(&secrets.protect(b"{}").unwrap())); +} + +#[test] +fn processes_that_start_together_end_up_with_one_key() { + if std::env::var(DIRECTORY).is_ok() { + return; + } + for round in 0..5 { + let root = std::env::temp_dir().join(format!("koppel-race-{}-{round}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let keys = root.join("keys"); + std::fs::create_dir_all(&keys).unwrap(); + let go = root.join("go"); + + let children: Vec<_> = (0..6) + .map(|_| { + Command::new(std::env::current_exe().unwrap()) + .args(["key_file_race_worker", "--exact", "--nocapture"]) + .env(DIRECTORY, &keys) + .env(GO, &go) + .stdout(Stdio::piped()) + .spawn() + .unwrap() + }) + .collect(); + std::thread::sleep(Duration::from_millis(300)); + std::fs::write(&go, b"go").unwrap(); + + let mut sealed = Vec::new(); + for child in children { + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "a worker failed"); + let text = String::from_utf8(output.stdout).unwrap(); + let line = text + .lines() + .find_map(|l| l.strip_prefix("SEALED ")) + .expect("a worker sealed nothing"); + sealed.push(unhex(line)); + } + + // One key: the file opens every worker's output, and nothing else is left in the directory. + let secrets = SecretBox::with_key_file(&keys).unwrap(); + for blob in &sealed { + assert_eq!(secrets.unprotect(blob).unwrap(), b"{}"); + } + let names: Vec<_> = std::fs::read_dir(&keys) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["koppel-secrets.key"]); + let _ = std::fs::remove_dir_all(&root); + } +}