mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
craft-settings: read config.toml up to a 16 MiB limit
SettingsStore read config.toml with read_to_string at open, in the read-only fallback and before every save, so a file of any size was read into memory whole before parsing. The store now reads at most store::MAX_CONFIG_BYTES. A larger file is left untouched: the store opens read-only with Unreadable carrying ErrorKind::FileTooLarge, and a file that grows past the limit while the app runs makes the save return SettingsError::ReadOnly.
This commit is contained in:
1 parent
a20dfd1623
commit
4e349df893
3 files changed
+68
-5
No files matched your search
@@ -139,6 +139,7 @@ things that do not belong in `config.toml`.
|
||||
| Older `schema_version` | `Settings::migrate` once per step, then saved; `report.migrated_from`. |
|
||||
| Newer `schema_version` | Values shown, store read-only, so an older build never overwrites a newer file. |
|
||||
| Migration step fails | Store read-only, file untouched. |
|
||||
| Larger than `store::MAX_CONFIG_BYTES` (16 MiB) | Not read into memory; defaults; store read-only, file untouched; `report.read_only` is `Unreadable` with `ErrorKind::FileTooLarge`. |
|
||||
|
||||
## What happens when saving
|
||||
|
||||
@@ -155,7 +156,7 @@ which can stay the same on FAT, HFS+ or network shares) with what it last read o
|
||||
| Changed, parses | Adopts it so its comments and unknown keys survive, backs it up, then writes this store's values over its known keys. |
|
||||
| Changed, does not parse | Moves it to `config.broken-<ts>.toml` (the edit is kept; `take_moved_aside()` returns the path to show), leaves the previous backup alone, then writes. |
|
||||
| Blank | Leaves the previous backup alone, then writes. |
|
||||
| From a newer build, or its migration fails | Writes nothing; the store becomes read-only and the save returns `SettingsError::ReadOnly`, the same as at startup. |
|
||||
| From a newer build, its migration fails, or larger than `store::MAX_CONFIG_BYTES` | Writes nothing; the store becomes read-only and the save returns `SettingsError::ReadOnly`, the same as at startup. |
|
||||
|
||||
### Concurrency contract
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The in-memory store: load once, read every frame, save while the application runs.
|
||||
|
||||
use std::io::{self, Write};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -16,6 +16,9 @@ use crate::recovery;
|
||||
/// The settings file name.
|
||||
pub const CONFIG_FILE: &str = "config.toml";
|
||||
|
||||
/// Largest `config.toml` the store reads. A larger file is left untouched and the store is read-only.
|
||||
pub const MAX_CONFIG_BYTES: u64 = 16 << 20;
|
||||
|
||||
/// How long after the last change a save is attempted.
|
||||
pub const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(500);
|
||||
|
||||
@@ -156,7 +159,7 @@ impl<T: Settings> SettingsStore<T> {
|
||||
return (store, report);
|
||||
}
|
||||
|
||||
match std::fs::read_to_string(&path) {
|
||||
match read_config(&path) {
|
||||
Ok(text) => store.load_text(&path, &text, &mut report),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
if let Some((value, from)) = migrate::import_legacy(&options.legacy) {
|
||||
@@ -291,7 +294,7 @@ impl<T: Settings> SettingsStore<T> {
|
||||
/// user's values instead of defaults.
|
||||
fn load_best_effort(&mut self, report: &mut LoadReport) {
|
||||
if let Some(path) = &self.path
|
||||
&& let Ok(text) = std::fs::read_to_string(path)
|
||||
&& let Ok(text) = read_config(path)
|
||||
&& let Ok(mut doc) = document::parse(&text)
|
||||
{
|
||||
// A failed migration leaves the document half-upgraded; show defaults instead.
|
||||
@@ -380,9 +383,15 @@ impl<T: Settings> SettingsStore<T> {
|
||||
/// and a file from a newer build, or one whose migration fails, makes the store read-only
|
||||
/// instead of overwriting it, the same as at startup.
|
||||
fn check_disk(&mut self, path: &Path) -> Result<Option<String>, SettingsError> {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
let text = match read_config(path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
// Same as at startup: leave the oversized file untouched and stop saving.
|
||||
Err(e) if e.kind() == io::ErrorKind::FileTooLarge => {
|
||||
let why = ReadOnlyReason::Unreadable(e).to_string();
|
||||
self.read_only = Some(why.clone());
|
||||
return Err(SettingsError::ReadOnly(why));
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
// A blank file still parses, so adopting it below would replace this store's document --
|
||||
@@ -416,6 +425,24 @@ impl<T: Settings> SettingsStore<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `config.toml` as text. A file larger than [`MAX_CONFIG_BYTES`] fails with
|
||||
/// `ErrorKind::FileTooLarge` without being read into memory; text that is not UTF-8 fails with
|
||||
/// `ErrorKind::InvalidData`, as `std::fs::read_to_string` does.
|
||||
fn read_config(path: &Path) -> io::Result<String> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let too_large = || io::Error::new(io::ErrorKind::FileTooLarge, format!("file is larger than {MAX_CONFIG_BYTES} bytes"));
|
||||
if file.metadata()?.len() > MAX_CONFIG_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
// The length can change after the check, or be unknown (a pipe), so the read is capped too.
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_CONFIG_BYTES + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_CONFIG_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
|
||||
}
|
||||
|
||||
/// Exponential backoff: 1 s, 2 s, 4 s, … capped at [`MAX_RETRY_DELAY`].
|
||||
pub fn retry_delay(failures: u32) -> Duration {
|
||||
let exp = failures.saturating_sub(1).min(16);
|
||||
|
||||
@@ -32,6 +32,41 @@ fn two_broken_files_get_different_names() {
|
||||
assert!(second.broken_moved_to.unwrap().exists());
|
||||
}
|
||||
|
||||
/// Pads `config.toml` past the read limit; the file is sparse where the file system allows it.
|
||||
fn grow_past_limit(dir: &std::path::Path) -> u64 {
|
||||
let len = craft_settings::store::MAX_CONFIG_BYTES + 1;
|
||||
std::fs::OpenOptions::new().write(true).open(config_path(dir)).unwrap().set_len(len).unwrap();
|
||||
len
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_file_opens_read_only_and_is_left_in_place() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write_config(tmp.path(), "schema_version = 2\n[general]\nlanguage = \"de\"\n");
|
||||
let len = grow_past_limit(tmp.path());
|
||||
let (mut store, report) = open_in(tmp.path());
|
||||
assert!(matches!(&report.read_only, Some(ReadOnlyReason::Unreadable(e)) if e.kind() == std::io::ErrorKind::FileTooLarge), "{report:?}");
|
||||
assert!(report.broken_moved_to.is_none(), "{report:?}");
|
||||
assert_eq!(report.source, Source::Defaults);
|
||||
assert!(matches!(store.flush(), Err(SettingsError::ReadOnly(_))));
|
||||
assert_eq!(std::fs::metadata(config_path(tmp.path())).unwrap().len(), len, "the file is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_grown_past_the_limit_while_running_is_not_overwritten() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (mut store, _) = open_in(tmp.path());
|
||||
store.flush().unwrap();
|
||||
let len = grow_past_limit(tmp.path());
|
||||
|
||||
store.update(|p| p.general.language = "fr".into());
|
||||
assert!(matches!(store.flush(), Err(SettingsError::ReadOnly(_))));
|
||||
assert!(store.is_read_only());
|
||||
assert!(store.take_moved_aside().is_empty());
|
||||
assert_eq!(std::fs::metadata(config_path(tmp.path())).unwrap().len(), len, "the file is untouched");
|
||||
assert!(matches!(store.tick(std::time::Instant::now()).status, craft_settings::SaveStatus::Idle), "no retries once read-only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_value_only_resets_its_section() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user