Skip to main content

rf_cache/
lib.rs

1//! rf-cache — the *one* scan cache shared by `rop-finder` (rf-cli) and
2//! `rop-finder-mcp` (rf-mcp).
3//!
4//! This crate exists because the duplication *was* the bug. Two copies of
5//! the cache meant two copies of the hex decoder, and the ROB-04
6//! char-boundary panic lived in both of them; it meant two key builders,
7//! and only one of them ever learned about `--align`. Everything that
8//! decides whether a cached result may be believed now lives here:
9//!
10//! * **[`make_key`]** — a versioned key. Every output-affecting parameter
11//!   goes in (CLI-01/ENG-05: the old rf-cli key omitted `--rawArch`,
12//!   `--rawMode` and `--rawEndian`, so `--cache` served an x86 scan for an
13//!   ARM query), and the schema version is in both the hashed material and
14//!   the file name, so the *next* key change misses instead of
15//!   mismatching.
16//! * **[`DiskCache`]** — HMAC-SHA256 over `key || 0x00 || body` with a
17//!   per-directory random key, 0600 entries in a 0700 directory,
18//!   `create_new` + rename for atomicity, and a byte-weighted LRU with a
19//!   TTL (CLI-07/MCP-04, CLI-08/PERF-12).
20//! * **[`MemCache`]** — the in-memory half: a byte-weighted LRU with a
21//!   TTL, weighted by [`CachedScan::heap_bytes`] and evicted on insert
22//!   (MCP-05/ROB-07). The unbounded `HashMap` it replaces walked the MCP
23//!   server's RSS from 5 MB to 84 MB over twelve scans of one 900 KB
24//!   binary and pinned 2.57 GB from a single depth-40 request.
25//! * **[`CachedScan::validate`]** — run on every deserialize, so a
26//!   corrupt or hostile entry is a miss with a counter rather than a
27//!   panic or a lie (ROB-04).
28//!
29//! A cache that cannot prove an entry is its own does not fall back to
30//! trusting it: [`DiskCache::open`] fails, and the caller runs uncached.
31//!
32//! # Semver policy
33//!
34//! Covered by semver from 1.0: the signatures of [`make_key`],
35//! [`DiskCache`]'s and [`MemCache`]'s methods, and the fields of
36//! [`CacheLimits`], [`CacheStats`] and [`MemStats`].
37//!
38//! **Not** covered: the on-disk format. [`CACHE_FORMAT_VERSION`] and the
39//! key schema version are in both the hashed material and the file name
40//! precisely so that changing them MISSES rather than mismatching — a
41//! format change is a cold cache, never a wrong answer, and so it is not a
42//! breaking change. The text of an [`OpenError`] is not covered either.
43//! Pin `rf-cache = "1"`.
44//!
45//! See `docs/API-STABILITY.md` in the repository for the workspace-wide
46//! statement.
47
48#![deny(clippy::indexing_slicing, clippy::string_slice)]
49// ENG-08: every public item carries documentation.
50#![warn(missing_docs)]
51
52mod hex;
53mod mac;
54mod mem;
55mod record;
56mod store;
57
58pub use hex::{decode_hex, encode_hex, is_hex_bytes, parse_hex_u64, MAX_GADGET_BYTES};
59pub use mac::{ct_eq, hmac_sha256, sha256_hex, MAC_LEN};
60pub use mem::{now_unix, MemCache, MemLimits, MemStats, DEFAULT_MEM_MAX_BYTES, DEFAULT_MEM_TTL};
61pub use record::{
62    CachedGadget, CachedScan, CACHE_FORMAT_VERSION, GADGET_OVERHEAD_BYTES, KNOWN_CLASSES,
63    MAX_GADGETS_PER_ENTRY, MAX_INSNS_PER_GADGET, MAX_LABEL_BYTES, MAX_PREV_BYTES, MAX_TEXT_BYTES,
64    SCAN_OVERHEAD_BYTES,
65};
66pub use store::{
67    CacheLimits, CacheStats, DiskCache, OpenError, DEFAULT_MAX_ENTRY_BYTES,
68    DEFAULT_MAX_TOTAL_BYTES, DEFAULT_TTL, KEY_FILE,
69};
70
71/// Key schema version.
72///
73/// It is hashed *into* the parameter digest and prefixed onto the file
74/// name. Both matter: the prefix means a v1 entry is never even opened by
75/// a v2 lookup, and the hashed copy means two schemas can never
76/// accidentally agree on a digest. When a future release adds another
77/// output-affecting flag, bumping this is the whole migration — old
78/// entries miss, get rescanned, and age out under the TTL.
79pub const KEY_SCHEMA_VERSION: u32 = 1;
80
81/// Build a cache key from the input file's SHA-256 (hex) and a rendering
82/// of every parameter that can change the output.
83///
84/// `params` is the caller's business — it is the front end that knows
85/// which flags it has — but it must be *complete*. CLI-01/ENG-05 was
86/// exactly an incomplete `params`.
87#[must_use]
88pub fn make_key(file_sha256_hex: &str, params: &str) -> String {
89    let material = format!("rf-cache/key/v{KEY_SCHEMA_VERSION}\u{1f}{params}");
90    let param_hash = sha256_hex(material.as_bytes());
91    // "--" separator: ':' is not a legal Windows file name character.
92    format!("v{KEY_SCHEMA_VERSION}-{file_sha256_hex}--{param_hash}")
93}
94
95/// First 16 characters of a key, for log lines. Char-safe by construction
96/// (`str::get`, not a byte-range slice) — the same discipline that ROB-04
97/// was a failure of.
98#[must_use]
99pub fn key_prefix(key: &str) -> &str {
100    match key.char_indices().nth(16) {
101        Some((i, _)) => key.get(..i).unwrap_or(key),
102        None => key,
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn key_is_deterministic_and_parameter_sensitive() {
112        let f = sha256_hex(b"binary");
113        let a = make_key(&f, "depth=10|align=1");
114        assert_eq!(a, make_key(&f, "depth=10|align=1"));
115        assert_ne!(a, make_key(&f, "depth=10|align=4"));
116        assert_ne!(a, make_key(&sha256_hex(b"other"), "depth=10|align=1"));
117    }
118
119    #[test]
120    fn key_carries_the_schema_version_in_the_name() {
121        let k = make_key(&sha256_hex(b"binary"), "p");
122        assert!(k.starts_with(&format!("v{KEY_SCHEMA_VERSION}-")), "{k}");
123        // Windows file names cannot contain ':'.
124        assert!(!k.contains(':'));
125        // A key is a legal file-name stem.
126        assert!(k
127            .bytes()
128            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'));
129    }
130
131    #[test]
132    fn key_prefix_never_splits_a_character() {
133        assert_eq!(key_prefix("0123456789abcdefXYZ"), "0123456789abcdef");
134        assert_eq!(key_prefix("short"), "short");
135        assert_eq!(key_prefix(""), "");
136        // Not a key we would ever build, but the helper must still not
137        // panic on one.
138        assert_eq!(key_prefix("€€€"), "€€€");
139    }
140}