lean_ctx/core/eval_ab/testbench/
lockfile.rs1use std::collections::HashSet;
11use std::path::{Component, Path, PathBuf};
12
13use anyhow::{Context, Result, bail};
14use serde::{Deserialize, Serialize};
15
16use crate::core::eval_ab::safe_paths::is_safe_relative_file;
17use crate::core::eval_ab::sha256_hex;
18
19pub const TESTBENCH_LOCK_KIND: &str = "lean-ctx.testbench-lock";
21
22fn is_safe_repo_name(value: &str) -> bool {
23 if value.trim().is_empty()
24 || value.as_bytes().contains(&0)
25 || value.contains('/')
26 || value.contains('\\')
27 {
28 return false;
29 }
30 let mut components = Path::new(value).components();
31 matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
32}
33
34fn is_safe_relative_dir(value: &str) -> bool {
35 value == "." || is_safe_relative_file(value)
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct RepoEntry {
41 pub name: String,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub url: Option<String>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub commit: Option<String>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub path: Option<String>,
52 pub suite: String,
54}
55
56impl RepoEntry {
57 pub fn is_local(&self) -> bool {
59 self.path.is_some()
60 }
61
62 pub(crate) fn validate(&self) -> std::result::Result<(), String> {
63 if !is_safe_repo_name(&self.name) {
64 return Err(format!(
65 "repo name {:?} must be a safe single path component",
66 self.name
67 ));
68 }
69 if !is_safe_relative_file(&self.suite) {
70 return Err(format!(
71 "repo {}: suite must be a safe relative file path",
72 self.name
73 ));
74 }
75 match (&self.url, &self.commit, &self.path) {
76 (Some(u), Some(c), None) => {
77 if u.trim().is_empty() || c.trim().is_empty() {
78 return Err(format!(
79 "repo {}: url and commit must be non-empty",
80 self.name
81 ));
82 }
83 Ok(())
84 }
85 (None, None, Some(p)) => {
86 if !is_safe_relative_dir(p) {
87 return Err(format!(
88 "repo {}: path must be a safe relative directory",
89 self.name
90 ));
91 }
92 Ok(())
93 }
94 _ => Err(format!(
95 "repo {}: set EITHER url+commit (remote) OR path (local fixture)",
96 self.name
97 )),
98 }
99 }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct TestbenchLock {
106 pub kind: String,
107 pub repos: Vec<RepoEntry>,
108 #[serde(skip)]
109 dir: PathBuf,
110}
111
112impl TestbenchLock {
113 pub fn load(path: &Path) -> Result<Self> {
115 let raw = std::fs::read_to_string(path)
116 .with_context(|| format!("reading testbench lock {}", path.display()))?;
117 let dir = path
118 .parent()
119 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
120 Self::parse(&raw, dir)
121 }
122
123 pub fn parse(raw: &str, dir: PathBuf) -> Result<Self> {
125 let mut lock: TestbenchLock =
126 serde_json::from_str(raw).context("parsing testbench lock JSON")?;
127 lock.validate()?;
128 lock.dir = dir;
129 Ok(lock)
130 }
131
132 pub(crate) fn validate(&self) -> Result<()> {
134 if self.kind != TESTBENCH_LOCK_KIND {
135 bail!("not a {TESTBENCH_LOCK_KIND} file (kind = {:?})", self.kind);
136 }
137 if self.repos.is_empty() {
138 bail!("testbench lock contains no repos");
139 }
140 let mut seen = HashSet::new();
141 for repo in &self.repos {
142 if let Err(reason) = repo.validate() {
143 bail!("invalid lock entry: {reason}");
144 }
145 if !seen.insert(repo.name.as_str()) {
146 bail!("duplicate repo name: {}", repo.name);
147 }
148 }
149 Ok(())
150 }
151
152 pub(crate) fn suite_path(&self, repo: &RepoEntry) -> Result<PathBuf> {
154 if let Err(reason) = repo.validate() {
155 bail!("invalid lock entry: {reason}");
156 }
157 let root = std::fs::canonicalize(self.dir())
158 .with_context(|| format!("canonicalizing lock directory {}", self.dir().display()))?;
159 let suite = std::fs::canonicalize(root.join(&repo.suite))
160 .with_context(|| format!("canonicalizing suite {}", repo.suite))?;
161 if !suite.starts_with(&root) {
162 bail!(
163 "repo {}: suite {} escapes lock directory",
164 repo.name,
165 repo.suite
166 );
167 }
168 if !suite.is_file() {
169 bail!("repo {}: suite {} is not a file", repo.name, repo.suite);
170 }
171 Ok(suite)
172 }
173
174 pub fn dir(&self) -> &Path {
176 &self.dir
177 }
178
179 pub fn digest(&self) -> String {
182 let bytes = serde_json::to_vec(&self.repos).unwrap_or_default();
184 sha256_hex(&bytes)
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 fn local_lock() -> &'static str {
193 r#"{"kind":"lean-ctx.testbench-lock","repos":[
194 {"name":"qa","path":"repos/qa","suite":"qa.ndjson"},
195 {"name":"code","path":"repos/code","suite":"code.ndjson"}
196 ]}"#
197 }
198
199 #[test]
200 fn parses_local_fixture_lock() {
201 let lock = TestbenchLock::parse(local_lock(), PathBuf::from("/lock")).unwrap();
202 assert_eq!(lock.repos.len(), 2);
203 assert!(lock.repos[0].is_local());
204 assert_eq!(lock.dir(), Path::new("/lock"));
205 }
206
207 #[test]
208 fn parses_remote_entry() {
209 let raw = r#"{"kind":"lean-ctx.testbench-lock","repos":[
210 {"name":"r","url":"https://example.com/r.git","commit":"abc123","suite":"r.ndjson"}
211 ]}"#;
212 let lock = TestbenchLock::parse(raw, PathBuf::from(".")).unwrap();
213 assert!(!lock.repos[0].is_local());
214 }
215
216 #[test]
217 fn rejects_mixed_source() {
218 let raw = r#"{"kind":"lean-ctx.testbench-lock","repos":[
219 {"name":"r","url":"u","commit":"c","path":"p","suite":"s"}
220 ]}"#;
221 assert!(TestbenchLock::parse(raw, PathBuf::from(".")).is_err());
222 }
223
224 #[test]
225 fn rejects_remote_without_commit() {
226 let raw = r#"{"kind":"lean-ctx.testbench-lock","repos":[
227 {"name":"r","url":"u","suite":"s"}
228 ]}"#;
229 assert!(TestbenchLock::parse(raw, PathBuf::from(".")).is_err());
230 }
231
232 #[test]
233 fn rejects_duplicate_names() {
234 let raw = r#"{"kind":"lean-ctx.testbench-lock","repos":[
235 {"name":"r","path":"a","suite":"s"},
236 {"name":"r","path":"b","suite":"s"}
237 ]}"#;
238 assert!(TestbenchLock::parse(raw, PathBuf::from(".")).is_err());
239 }
240
241 #[test]
242 fn rejects_foreign_kind() {
243 let raw = r#"{"kind":"nope","repos":[{"name":"r","path":"p","suite":"s"}]}"#;
244 assert!(TestbenchLock::parse(raw, PathBuf::from(".")).is_err());
245 }
246
247 #[test]
248 fn digest_is_stable_and_ignores_dir() {
249 let a = TestbenchLock::parse(local_lock(), PathBuf::from("/one")).unwrap();
250 let b = TestbenchLock::parse(local_lock(), PathBuf::from("/two")).unwrap();
251 assert_eq!(a.digest(), b.digest());
252 }
253
254 #[test]
255 fn rejects_unsafe_repo_names_and_relative_paths() {
256 for (name, path, suite) in [
257 ("../escape", "repos/qa", "qa.ndjson"),
258 ("nested/name", "repos/qa", "qa.ndjson"),
259 ("qa", "/tmp/fixture", "qa.ndjson"),
260 ("qa", "../fixture", "qa.ndjson"),
261 ("qa", "repos/qa", "/tmp/qa.ndjson"),
262 ("qa", "repos/qa", "../qa.ndjson"),
263 ] {
264 let raw = format!(
265 r#"{{"kind":"lean-ctx.testbench-lock","repos":[{{"name":"{name}","path":"{path}","suite":"{suite}"}}]}}"#
266 );
267 assert!(
268 TestbenchLock::parse(&raw, PathBuf::from(".")).is_err(),
269 "unsafe lock entry accepted: {name} {path} {suite}"
270 );
271 }
272 }
273
274 #[cfg(unix)]
275 #[test]
276 fn suite_path_rejects_symlink_escape() {
277 let root = tempfile::tempdir().unwrap();
278 let outside = tempfile::tempdir().unwrap();
279 let outside_file = outside.path().join("suite.ndjson");
280 let suite_link = root.path().join("suite.ndjson");
281 std::fs::write(&outside_file, "{}").unwrap();
282 std::os::unix::fs::symlink(&outside_file, &suite_link).unwrap();
283 let raw = r#"{"kind":"lean-ctx.testbench-lock","repos":[{"name":"qa","path":"fixture","suite":"suite.ndjson"}]}"#;
284 let lock = TestbenchLock::parse(raw, root.path().to_path_buf()).unwrap();
285 assert!(lock.suite_path(&lock.repos[0]).is_err());
286 }
287}