kache_format/lib.rs
1//! Cache-entry metadata and validation shared by local and remote storage.
2
3use serde::{Deserialize, Serialize};
4use std::path::Path;
5
6/// Cache-key recipe version written into entry metadata.
7pub const CACHE_KEY_VERSION: u32 = 31;
8
9/// Emit kinds represented by the current entry format.
10pub const GATED_EMIT_KINDS: [&str; 8] = [
11 "link", "metadata", "obj", "dep-info", "asm", "llvm-ir", "llvm-bc", "mir",
12];
13
14/// Metadata stored alongside cached artifacts.
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
16pub struct EntryMeta {
17 pub cache_key: String,
18 /// Cache-key recipe version that produced `cache_key`.
19 ///
20 /// Entries written before this field existed deserialize as `0` (unknown),
21 /// so an explicit stale-schema sweep can reclaim them without making old
22 /// stores unreadable during an ordinary upgrade.
23 #[serde(default)]
24 pub key_schema: u32,
25 pub crate_name: String,
26 pub crate_types: Vec<String>,
27 pub files: Vec<CachedFile>,
28 pub stdout: String,
29 pub stderr: String,
30 #[serde(default)]
31 pub features: Vec<String>,
32 #[serde(default)]
33 pub target: String,
34 #[serde(default)]
35 pub profile: String,
36 #[serde(default)]
37 pub compile_time_ms: u64,
38 /// Canonical rustc `--emit` kinds this entry actually contains, derived
39 /// from the stored output files at put time (kunobi-ninja/kache#325). Lookup
40 /// uses it to reject an entry that doesn't cover what the invocation's
41 /// `--emit` requested. `#[serde(default)]` keeps pre-gate `meta.json` (no
42 /// field) deserializable — an empty set means "unknown", so the lookup gate
43 /// skips the check rather than mass-invalidating old entries.
44 #[serde(default)]
45 pub emit_kinds: Vec<String>,
46}
47
48impl EntryMeta {
49 /// Whether this entry's recorded outputs cover every `--emit` kind the
50 /// caller requested (kunobi-ninja/kache#325). Superset-tolerant: an entry
51 /// that contains more kinds than requested still covers it (a lib
52 /// `--emit=link` legitimately also produces `.rmeta`).
53 ///
54 /// Returns `true` when `emit_kinds` is empty — pre-gate entries recorded no
55 /// coverage, so the check is skipped rather than mass-invalidating them.
56 /// Requested kinds that map to no stored file class (e.g. an exotic emit
57 /// kache doesn't model) are ignored so the gate never rejects on a kind it
58 /// can't reason about.
59 pub fn covers_requested_emit(&self, requested: &[String]) -> bool {
60 if self.emit_kinds.is_empty() {
61 return true;
62 }
63 requested
64 .iter()
65 .filter(|kind| GATED_EMIT_KINDS.contains(&kind.as_str()))
66 .all(|kind| self.emit_kinds.iter().any(|have| have == kind))
67 }
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
71pub struct CachedFile {
72 /// Filename relative to the cache entry directory
73 pub name: String,
74 /// Size in bytes
75 pub size: u64,
76 /// blake3 hash of file content
77 pub hash: String,
78 /// Whether the source file had the executable bit set at store time.
79 /// Folded into the local content-dedup hash so two entries differing only
80 /// by which file is executable can't collide (kunobi-ninja/kache#324).
81 /// `#[serde(default)]` keeps old `meta.json` (no field) deserializable.
82 #[serde(default)]
83 pub executable: bool,
84}
85
86/// Is `s` a well-formed cache key: exactly 64 lowercase hex chars, matching
87/// the `blake3::Hash::to_hex()` output produced by cache-key recipes?
88///
89/// Cache keys that arrive from an untrusted source — a prefetch planner
90/// response or an S3 bucket listing — get interpolated into local filesystem
91/// paths (`store_dir().join(cache_key)`) and S3 object keys. An unvalidated
92/// value like `../../../home/user/.config` is a path-traversal / prefix-escape
93/// primitive (`PathBuf::join` walks up on `..` and resets on an absolute
94/// component). Callers must **reject** such keys, never sanitize them.
95pub fn is_valid_cache_key(s: &str) -> bool {
96 s.len() == 64
97 && s.bytes()
98 .all(|b| b.is_ascii_digit() || matches!(b, b'a'..=b'f'))
99}
100
101/// Is `s` a crate name safe to use as an S3 object-key path component?
102///
103/// Permissive enough for real crate names and cc source basenames
104/// (`[A-Za-z0-9_.-]`) but rejects anything that could escape a path or key
105/// prefix: separators, `..` traversal, NUL/control chars, the empty string,
106/// or an absurd length. Like [`is_valid_cache_key`], this guards values that
107/// cross the untrusted-remote boundary; reject, do not sanitize.
108pub fn is_valid_crate_name(s: &str) -> bool {
109 !s.is_empty()
110 && s.len() <= 128
111 && !s.contains("..")
112 && s.bytes()
113 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
114}
115
116/// A blob hash is a 64-char blake3 hex digest. Validated where untrusted
117/// `meta.json` enters (download/import) so a malformed hash can never reach
118/// path construction or the integrity gate (#211).
119pub fn is_blob_hash(s: &str) -> bool {
120 s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
121}
122
123/// A cached artifact's `name` must be a single, normal path component — no
124/// absolute/rooted path, no `..`, no separators. `meta.json` names are
125/// attacker-influenced for a shared/MITM'd bucket, and `Path::join` with an
126/// absolute or `..`-bearing component escapes the entry/target dir (e.g.
127/// `dir.join("/etc/x") == "/etc/x"`), giving an arbitrary read/overwrite
128/// primitive. Enforced at the import and restore trust boundaries (#211).
129pub fn is_safe_artifact_name(name: &str) -> bool {
130 use std::path::Component;
131 let mut components = Path::new(name).components();
132 matches!(
133 (components.next(), components.next()),
134 (Some(Component::Normal(_)), None)
135 )
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141 #[test]
142 fn is_valid_cache_key_rejects_traversal_and_malformed() {
143 assert!(!is_valid_cache_key(""));
144 assert!(!is_valid_cache_key("abc123")); // too short
145 assert!(!is_valid_cache_key(&"a".repeat(63)));
146 assert!(!is_valid_cache_key(&"a".repeat(65)));
147 assert!(!is_valid_cache_key(&"A".repeat(64))); // uppercase not produced by to_hex
148 assert!(!is_valid_cache_key(&"g".repeat(64))); // non-hex
149 // Path-traversal / prefix-escape attempts, padded to 64 chars.
150 assert!(!is_valid_cache_key(&format!(
151 "{:/<64}",
152 "../../../etc/passwd"
153 )));
154 assert!(!is_valid_cache_key(&format!("{:0<64}", "/abs/path")));
155 assert!(!is_valid_cache_key(&format!("{:0<63}\n", "x"))); // newline
156 }
157 #[test]
158 fn is_valid_crate_name_accepts_real_names() {
159 for name in [
160 "serde",
161 "tokio_stream",
162 "foo-bar",
163 "build_script_build",
164 "a.out",
165 "x",
166 ] {
167 assert!(is_valid_crate_name(name), "{name} should be valid");
168 }
169 assert!(is_valid_crate_name(&"a".repeat(128)));
170 }
171 #[test]
172 fn is_valid_crate_name_rejects_path_escapes() {
173 assert!(!is_valid_crate_name(""));
174 assert!(!is_valid_crate_name("../evil"));
175 assert!(!is_valid_crate_name("a/b"));
176 assert!(!is_valid_crate_name("a\\b"));
177 assert!(!is_valid_crate_name("a..b")); // traversal substring
178 assert!(!is_valid_crate_name("nul\0byte"));
179 assert!(!is_valid_crate_name("tab\there"));
180 assert!(!is_valid_crate_name(&"a".repeat(129))); // too long
181 }
182 /// #211: the trust-boundary hash validator accepts only a 64-char blake3
183 /// hex digest and rejects everything a hostile/corrupt meta.json might
184 /// carry (empty, short, wrong length, non-hex, traversal-shaped).
185 #[test]
186 fn is_blob_hash_accepts_only_blake3_hex() {
187 assert!(is_blob_hash(&"a".repeat(64)));
188 assert!(is_blob_hash(&"0123456789abcdef".repeat(4)));
189 assert!(!is_blob_hash(""));
190 assert!(!is_blob_hash("ab"));
191 assert!(!is_blob_hash(&"a".repeat(63)));
192 assert!(!is_blob_hash(&"a".repeat(65)));
193 assert!(!is_blob_hash(&"g".repeat(64))); // non-hex
194 assert!(!is_blob_hash("../../etc/passwd"));
195 }
196 /// #211: a cached artifact name must be a single normal component — reject
197 /// absolute, rooted, parent-dir, separator-bearing, and empty names.
198 #[test]
199 fn is_safe_artifact_name_requires_single_normal_component() {
200 assert!(is_safe_artifact_name("libfoo-abc123.rlib"));
201 assert!(is_safe_artifact_name("foo.d"));
202 assert!(!is_safe_artifact_name(""));
203 assert!(!is_safe_artifact_name("/etc/passwd"));
204 assert!(!is_safe_artifact_name("../escape"));
205 assert!(!is_safe_artifact_name("a/b"));
206 assert!(!is_safe_artifact_name("./a"));
207 assert!(!is_safe_artifact_name(".."));
208 }
209 /// kunobi-ninja/kache#325: the lookup gate is superset-tolerant, skips empty
210 /// (pre-gate) entries, and rejects genuinely-missing kinds.
211 #[test]
212 fn covers_requested_emit_semantics() {
213 let mk = |kinds: &[&str]| EntryMeta {
214 cache_key: "k".into(),
215 key_schema: CACHE_KEY_VERSION,
216 crate_name: "c".into(),
217 crate_types: vec![],
218 files: vec![],
219 stdout: String::new(),
220 stderr: String::new(),
221 features: vec![],
222 target: String::new(),
223 profile: String::new(),
224 compile_time_ms: 0,
225 emit_kinds: kinds.iter().map(|s| s.to_string()).collect(),
226 };
227 let req = |kinds: &[&str]| -> Vec<String> { kinds.iter().map(|s| s.to_string()).collect() };
228
229 // Superset: entry has link+metadata+dep-info, request just link.
230 assert!(mk(&["dep-info", "link", "metadata"]).covers_requested_emit(&req(&["link"])));
231 // Exact.
232 assert!(
233 mk(&["dep-info", "metadata"]).covers_requested_emit(&req(&["dep-info", "metadata"]))
234 );
235 // Missing the requested obj → not covered.
236 assert!(!mk(&["link"]).covers_requested_emit(&req(&["link", "obj"])));
237 // Pre-gate entry (no recorded kinds) → skip the check.
238 assert!(mk(&[]).covers_requested_emit(&req(&["link", "obj"])));
239 // A requested kind the gate can't map to a file is ignored, not rejected.
240 assert!(mk(&["link"]).covers_requested_emit(&req(&["link", "future-exotic"])));
241 }
242}