Skip to main content

keyhog_core/
state_file.rs

1//! Bounded reads for on-disk KeyHog state artifacts (calibration cache,
2//! merkle index, etc.).
3
4use fs2::FileExt;
5use std::ffi::OsString;
6use std::fs::{File, OpenOptions};
7use std::io::Read;
8use std::path::{Path, PathBuf};
9
10/// Exclusive advisory lock held across a state file's read/merge/write cycle.
11///
12/// The sibling `<filename>.lock` file is stable; the operating-system lock is
13/// released automatically when this value is dropped, including after a panic
14/// or process exit. Keeping one implementation here prevents state caches from
15/// independently reintroducing lost-update races.
16pub struct StateFileWriteLock {
17    file: File,
18}
19
20impl StateFileWriteLock {
21    /// Acquire the canonical sibling lock for `state_path`.
22    pub fn acquire(state_path: &Path) -> std::io::Result<Self> {
23        let lock_path = state_file_lock_path(state_path)?;
24        let parent = lock_path.parent().ok_or_else(|| {
25            std::io::Error::new(
26                std::io::ErrorKind::InvalidInput,
27                "state-file lock path has no parent directory",
28            )
29        })?;
30        std::fs::create_dir_all(parent)?;
31        let file = OpenOptions::new()
32            .create(true)
33            .read(true)
34            .write(true)
35            .open(lock_path)?;
36        file.lock_exclusive()?;
37        Ok(Self { file })
38    }
39}
40
41impl Drop for StateFileWriteLock {
42    fn drop(&mut self) {
43        if let Err(error) = FileExt::unlock(&self.file) {
44            tracing::warn!(%error, "failed to unlock KeyHog state file; closing the lock file will release the OS lock");
45        }
46    }
47}
48
49/// Canonical sibling lock filename for a KeyHog state artifact.
50pub fn state_file_lock_path(state_path: &Path) -> std::io::Result<PathBuf> {
51    let Some(base_name) = state_path.file_name() else {
52        return Err(std::io::Error::new(
53            std::io::ErrorKind::InvalidInput,
54            format!("state path '{}' has no file name", state_path.display()),
55        ));
56    };
57    let mut file_name = OsString::from(base_name);
58    file_name.push(".lock");
59    Ok(state_path.with_file_name(file_name))
60}
61
62/// Maximum on-disk calibration cache (`calibration.json`) size.
63///
64/// The artifact holds one `{alpha, beta}` pair per detector id, control-plane
65/// data, not scan input. Multi-megabyte calibration files are corrupt or hostile.
66pub(crate) const CALIBRATION_CACHE_FILE_BYTES: u64 = 16 * 1024 * 1024;
67
68/// Maximum size of a user-authored config file read wholesale into memory
69/// suppression rules (`.keyhogignore`/rule-filter TOML) and allowlists. These are
70/// hand-authored control-plane data; a multi-megabyte one is corrupt or a
71/// resource-exhaustion vector, so the wholesale read is bounded like the caches.
72pub(crate) const RULE_CONFIG_FILE_BYTES: u64 = 16 * 1024 * 1024;
73
74/// Maximum on-disk merkle index cache file size.
75///
76/// The JSON index stores `(path, chunk_offset, mtime, size, hash)` rows. Large
77/// monorepo caches can reach hundreds of MB; this bound still refuses
78/// multi-gigabyte hostile files in the state directory.
79pub(crate) const MERKLE_INDEX_CACHE_FILE_BYTES: u64 = 512 * 1024 * 1024;
80
81/// Read a state artifact through a metadata pre-check and a TOCTOU-safe cap.
82pub(crate) fn read_capped(path: &Path, cap: u64, kind: &str) -> std::io::Result<Vec<u8>> {
83    let file = std::fs::File::open(path)?;
84    let len = file.metadata()?.len();
85    if len > cap {
86        return Err(std::io::Error::new(
87            std::io::ErrorKind::InvalidData,
88            format!(
89                "{kind} {} exceeds {cap} byte cap; delete the cache file and rerun",
90                path.display()
91            ),
92        ));
93    }
94
95    let mut data = Vec::with_capacity(len as usize);
96    file.take(cap.saturating_add(1)).read_to_end(&mut data)?;
97    if data.len() as u64 > cap {
98        return Err(std::io::Error::new(
99            std::io::ErrorKind::InvalidData,
100            format!(
101                "{kind} {} grew past {cap} byte cap while reading; retry after the file is stable",
102                path.display()
103            ),
104        ));
105    }
106    Ok(data)
107}
108
109/// Atomically replace `path` with `bytes` via a same-directory temp file.
110///
111/// Single owner for the create-dir / prefixed-tempfile / fsync / rename dance
112/// that the calibration cache and the merkle index both persist through. The
113/// `prefix` is the temp-file name prefix so each caller's stale-tmp sweep can
114/// still recognize its own orphans by name. A parentless or empty path resolves
115/// to the current directory so a bare `calibration.json` filename saves cleanly
116/// instead of failing `create_dir_all("")`.
117pub(crate) fn write_atomically(path: &Path, prefix: &str, bytes: &[u8]) -> std::io::Result<()> {
118    let parent = match path.parent().filter(|p| !p.as_os_str().is_empty()) {
119        Some(parent) => parent,
120        None => Path::new("."),
121    };
122    std::fs::create_dir_all(parent)?;
123    let mut tmp = tempfile::Builder::new()
124        .prefix(prefix)
125        .tempfile_in(parent)?;
126    std::io::Write::write_all(&mut tmp, bytes)?;
127    tmp.as_file().sync_all()?;
128    tmp.persist(path).map_err(|e| e.error)?;
129    Ok(())
130}
131
132/// Best-effort sweep of stale temp files left beside `cache_path` by a
133/// SIGKILL'd process (`tempfile`'s Drop cleans up on panic but not on signal).
134///
135/// Single owner for the sweep both the calibration cache and the merkle index
136/// perform. Deliberately conservative: only files whose name starts with one of
137/// the keyhog-owned `prefixes` AND older than `cutoff_secs` are removed, so a
138/// peer process's in-flight save or an unrelated file is never touched. Returns
139/// the number of files removed; callers own their summary logging.
140pub(crate) fn sweep_stale_tmp_siblings(
141    cache_path: &Path,
142    prefixes: &[&str],
143    cutoff_secs: u64,
144) -> usize {
145    let Some(parent) = cache_path.parent() else {
146        return 0;
147    };
148    let Ok(entries) = std::fs::read_dir(parent) else {
149        return 0;
150    };
151    let now = std::time::SystemTime::now();
152    let mut swept = 0usize;
153    for entry in entries {
154        let entry = match entry {
155            Ok(entry) => entry,
156            // Best-effort maintenance: a failed dir-entry read drops no scan
157            // coverage, so skip the entry rather than aborting the sweep.
158            Err(error) => {
159                tracing::warn!(dir = %parent.display(), %error, "skip unreadable tmp dir entry during stale-state sweep");
160                continue;
161            }
162        };
163        let name = entry.file_name();
164        let Some(name_str) = name.to_str() else {
165            continue;
166        };
167        if !prefixes.iter().any(|p| name_str.starts_with(p)) {
168            continue;
169        }
170        let path = entry.path();
171        if path == cache_path {
172            continue;
173        }
174        let Ok(meta) = path.metadata() else {
175            continue;
176        };
177        let Ok(modified) = meta.modified() else {
178            continue;
179        };
180        // A future mtime (clock skew) means "don't delete this one yet".
181        let Ok(age) = now.duration_since(modified) else {
182            continue;
183        };
184        if age.as_secs() < cutoff_secs {
185            continue;
186        }
187        if std::fs::remove_file(&path).is_ok() {
188            swept += 1;
189        }
190    }
191    swept
192}