返回 CodeWhale
artifact.rs
1 use std::collections::{BTreeMap, HashSet};
2 use std::fs::{self, OpenOptions};
3 use std::io::Write;
4 use std::path::{Path, PathBuf};
5
6 use serde::{Deserialize, Serialize};
7 use serde_json::{Value, json};
8 use sha2::{Digest, Sha256};
9 use unicode_normalization::UnicodeNormalization;
10
11 use super::{git, in_scope, normalized_path, protected_git_path, protected_test_path};
12
13 const MAX_FILES: usize = 4096;
14 const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024;
15 const MAX_TREE_BYTES: u64 = 64 * 1024 * 1024;
16 const MAX_CHANGE_BYTES: u64 = 8 * 1024 * 1024;
17 const MAX_SCANNED_FILES: usize = 36_864;
18
19 fn generated_output(path: &str) -> bool {
20 in_scope(path, "target") || path.split('/').any(|part| part == "__pycache__")
21 }
22
23 pub(super) fn capture_policy() -> Value {
24 json!({
25 "version": 1,
26 "excluded_untracked_root": "target",
27 "excluded_untracked_component": "__pycache__",
28 "tracked_and_protected_included": true,
29 "max_scanned_files": MAX_SCANNED_FILES,
30 })
31 }
32
33 #[derive(Clone, Deserialize, Serialize)]
34 pub(super) struct FileEntry {
35 pub path: String,
36 pub mode: u32,
37 pub size_bytes: u64,
38 pub blob_hash: String,
39 }
40
41 #[derive(Clone, Deserialize, Serialize)]
42 pub(super) struct Change {
43 pub path: String,
44 pub kind: String,
45 pub mode: Option<u32>,
46 pub size_bytes: Option<u64>,
47 pub blob_hash: Option<String>,
48 }
49
50 #[derive(Clone, Deserialize, Serialize)]
51 pub(super) struct Artifact {
52 pub schema_version: u32,
53 pub artifact_id: String,
54 pub baseline_id: String,
55 pub candidate_tree_hash: String,
56 pub entries: Vec<Change>,
57 pub parent_artifact_ids: Vec<String>,
58 pub candidate_id: String,
59 pub excluded_generated_paths: Vec<String>,
60 }
61
62 pub(super) struct ArtifactStore {
63 root: PathBuf,
64 baseline: Vec<FileEntry>,
65 baseline_id: String,
66 }
67
68 fn digest(bytes: &[u8]) -> String {
69 Sha256::digest(bytes)
70 .iter()
71 .map(|byte| format!("{byte:02x}"))
72 .collect()
73 }
74
75 fn canonical_hash<T: Serialize>(value: &T) -> Result<String, String> {
76 serde_json::to_vec(value)
77 .map(|bytes| digest(&bytes))
78 .map_err(|error| error.to_string())
79 }
80
81 fn check_paths<'a>(paths: impl IntoIterator<Item = &'a str>) -> Result<(), String> {
82 let mut folded = HashSet::new();
83 for path in paths {
84 normalized_path(path)?;
85 let key = path.nfkc().collect::<String>().to_lowercase();
86 if !folded.insert(key) {
87 return Err(format!("artifact path collision: {path}"));
88 }
89 }
90 Ok(())
91 }
92
93 fn mode(path: &Path) -> Result<u32, String> {
94 let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
95 if !metadata.is_file() || metadata.file_type().is_symlink() {
96 return Err(format!(
97 "artifact contains a link or special file: {}",
98 path.display()
99 ));
100 }
101 #[cfg(unix)]
102 {
103 use std::os::unix::fs::MetadataExt;
104 use std::os::unix::fs::PermissionsExt;
105 if metadata.nlink() != 1 {
106 return Err(format!("artifact contains a hardlink: {}", path.display()));
107 }
108 Ok(if metadata.permissions().mode() & 0o111 != 0 {
109 0o100755
110 } else {
111 0o100644
112 })
113 }
114 #[cfg(not(unix))]
115 {
116 Ok(0o100644)
117 }
118 }
119
120 fn read_file(path: &Path) -> Result<Vec<u8>, String> {
121 let before = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
122 if !before.is_file() || before.file_type().is_symlink() || before.len() > MAX_FILE_BYTES {
123 return Err(format!(
124 "artifact file is unsafe or oversized: {}",
125 path.display()
126 ));
127 }
128 #[cfg(unix)]
129 if std::os::unix::fs::MetadataExt::nlink(&before) != 1 {
130 return Err(format!("artifact contains a hardlink: {}", path.display()));
131 }
132 let bytes = fs::read(path).map_err(|error| error.to_string())?;
133 let after = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
134 if bytes.len() as u64 != before.len()
135 || before.len() != after.len()
136 || before.modified().ok() != after.modified().ok()
137 || !after.is_file()
138 || after.file_type().is_symlink()
139 {
140 return Err(format!(
141 "artifact file changed during seal: {}",
142 path.display()
143 ));
144 }
145 Ok(bytes)
146 }
147
148 fn walk(root: &Path) -> Result<BTreeMap<String, PathBuf>, String> {
149 fn visit(
150 root: &Path,
151 directory: &Path,
152 found: &mut BTreeMap<String, PathBuf>,
153 ) -> Result<(), String> {
154 for item in fs::read_dir(directory).map_err(|error| error.to_string())? {
155 let item = item.map_err(|error| error.to_string())?;
156 let path = item.path();
157 let relative = path.strip_prefix(root).map_err(|error| error.to_string())?;
158 let relative = normalized_path(&relative.to_string_lossy())?;
159 if relative == ".git" {
160 continue;
161 }
162 let metadata = fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
163 if metadata.file_type().is_symlink() {
164 return Err(format!("artifact contains a link: {relative}"));
165 }
166 if metadata.is_dir() {
167 visit(root, &path, found)?;
168 } else if metadata.is_file() {
169 if found.insert(relative, path).is_some() || found.len() > MAX_SCANNED_FILES {
170 return Err("artifact file count or path uniqueness limit exceeded".to_string());
171 }
172 } else {
173 return Err(format!("artifact contains a special file: {relative}"));
174 }
175 }
176 Ok(())
177 }
178 let mut found = BTreeMap::new();
179 visit(root, root, &mut found)?;
180 check_paths(found.keys().map(String::as_str))?;
181 Ok(found)
182 }
183
184 impl ArtifactStore {
185 pub(super) fn freeze(repo: &Path, root: &Path) -> Result<Self, String> {
186 fs::create_dir_all(root).map_err(|error| error.to_string())?;
187 fs::create_dir(root.join("blobs")).map_err(|error| error.to_string())?;
188 fs::create_dir(root.join("artifacts")).map_err(|error| error.to_string())?;
189 let listing = git(repo, &["ls-tree", "-r", "--full-tree", "-z", "HEAD"])?.stdout;
190 let mut baseline = Vec::new();
191 let mut total = 0;
192 for record in listing
193 .split(|byte| *byte == 0)
194 .filter(|record| !record.is_empty())
195 {
196 let text = std::str::from_utf8(record).map_err(|error| error.to_string())?;
197 let (header, path) = text.split_once('\t').ok_or("invalid git tree record")?;
198 let mut parts = header.split(' ');
199 let file_mode = parts.next().ok_or("missing git mode")?;
200 let kind = parts.next().ok_or("missing git kind")?;
201 let oid = parts.next().ok_or("missing git blob")?;
202 if kind != "blob" || !matches!(file_mode, "100644" | "100755") {
203 return Err(format!("unsupported baseline tree entry: {path}"));
204 }
205 let path = normalized_path(path)?;
206 let bytes = git(repo, &["cat-file", "blob", oid])?.stdout;
207 if bytes.len() as u64 > MAX_FILE_BYTES {
208 return Err(format!("baseline file exceeds limit: {path}"));
209 }
210 total += bytes.len() as u64;
211 if total > MAX_TREE_BYTES || baseline.len() >= MAX_FILES {
212 return Err("baseline tree exceeds limits".to_string());
213 }
214 let blob_hash = digest(&bytes);
215 let target = root.join("blobs").join(&blob_hash);
216 if !target.exists() {
217 let mut file = OpenOptions::new()
218 .write(true)
219 .create_new(true)
220 .open(&target)
221 .map_err(|error| error.to_string())?;
222 file.write_all(&bytes).map_err(|error| error.to_string())?;
223 file.sync_all().map_err(|error| error.to_string())?;
224 }
225 baseline.push(FileEntry {
226 path,
227 mode: if file_mode == "100755" {
228 0o100755
229 } else {
230 0o100644
231 },
232 size_bytes: bytes.len() as u64,
233 blob_hash,
234 });
235 }
236 baseline.sort_by(|a, b| a.path.cmp(&b.path));
237 check_paths(baseline.iter().map(|entry| entry.path.as_str()))?;
238 let baseline_id = canonical_hash(&baseline)?;
239 let bytes = serde_json::to_vec_pretty(&baseline).map_err(|error| error.to_string())?;
240 fs::write(root.join("baseline.json"), bytes).map_err(|error| error.to_string())?;
241 Ok(Self {
242 root: root.to_path_buf(),
243 baseline,
244 baseline_id,
245 })
246 }
247
248 pub(super) fn baseline_id(&self) -> &str {
249 &self.baseline_id
250 }
251
252 pub(super) fn verify_baseline(&self) -> Result<(), String> {
253 let bytes = fs::read(self.root.join("baseline.json")).map_err(|error| error.to_string())?;
254 let recorded: Vec<FileEntry> =
255 serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
256 if canonical_hash(&recorded)? != self.baseline_id {
257 return Err("frozen baseline manifest changed".to_string());
258 }
259 Ok(())
260 }
261
262 pub(super) fn capture(
263 &self,
264 workspace: &Path,
265 candidate_id: &str,
266 parent_artifact_ids: Vec<String>,
267 protected_paths: &[String],
268 ) -> Result<Artifact, String> {
269 let found = walk(workspace)?;
270 let baseline = self
271 .baseline
272 .iter()
273 .map(|entry| (entry.path.as_str(), entry))
274 .collect::<BTreeMap<_, _>>();
275 let mut tree = Vec::new();
276 let mut changes = Vec::new();
277 let mut excluded_generated_paths = Vec::new();
278 let mut total = 0u64;
279 let mut changed_bytes = 0u64;
280 for (relative, path) in found {
281 let file_mode = mode(&path)?;
282 if !baseline.contains_key(relative.as_str())
283 && generated_output(&relative)
284 && !protected_paths.iter().any(|root| in_scope(&relative, root))
285 && !protected_test_path(&relative)
286 && !protected_git_path(&relative)
287 && !relative.split('/').any(|part| part == ".codewhale")
288 {
289 excluded_generated_paths.push(relative);
290 continue;
291 }
292 let bytes = read_file(&path)?;
293 total += bytes.len() as u64;
294 if total > MAX_TREE_BYTES {
295 return Err("candidate tree exceeds byte limit".to_string());
296 }
297 let blob_hash = digest(&bytes);
298 let entry = FileEntry {
299 path: relative.clone(),
300 mode: file_mode,
301 size_bytes: bytes.len() as u64,
302 blob_hash: blob_hash.clone(),
303 };
304 if baseline
305 .get(relative.as_str())
306 .is_none_or(|old| old.blob_hash != blob_hash || old.mode != file_mode)
307 {
308 changed_bytes += bytes.len() as u64;
309 if changed_bytes > MAX_CHANGE_BYTES {
310 return Err("candidate changes exceed byte limit".to_string());
311 }
312 let target = self.root.join("blobs").join(&blob_hash);
313 if !target.exists() {
314 let mut file = OpenOptions::new()
315 .write(true)
316 .create_new(true)
317 .open(&target)
318 .map_err(|error| error.to_string())?;
319 file.write_all(&bytes).map_err(|error| error.to_string())?;
320 file.sync_all().map_err(|error| error.to_string())?;
321 }
322 changes.push(Change {
323 path: relative,
324 kind: "file".to_string(),
325 mode: Some(file_mode),
326 size_bytes: Some(bytes.len() as u64),
327 blob_hash: Some(blob_hash),
328 });
329 }
330 tree.push(entry);
331 }
332 for entry in &self.baseline {
333 if !tree.iter().any(|current| current.path == entry.path) {
334 changes.push(Change {
335 path: entry.path.clone(),
336 kind: "deleted".to_string(),
337 mode: None,
338 size_bytes: None,
339 blob_hash: None,
340 });
341 }
342 }
343 changes.sort_by(|a, b| a.path.cmp(&b.path));
344 let candidate_tree_hash = canonical_hash(&tree)?;
345 let artifact = Artifact {
346 schema_version: 2,
347 artifact_id: candidate_tree_hash.clone(),
348 baseline_id: self.baseline_id.clone(),
349 candidate_tree_hash,
350 entries: changes,
351 parent_artifact_ids,
352 candidate_id: candidate_id.to_string(),
353 excluded_generated_paths,
354 };
355 let target = self
356 .root
357 .join("artifacts")
358 .join(format!("{candidate_id}.json"));
359 let bytes = serde_json::to_vec_pretty(&artifact).map_err(|error| error.to_string())?;
360 let mut file = OpenOptions::new()
361 .write(true)
362 .create_new(true)
363 .open(target)
364 .map_err(|error| error.to_string())?;
365 file.write_all(&bytes).map_err(|error| error.to_string())?;
366 file.sync_all().map_err(|error| error.to_string())?;
367 Ok(artifact)
368 }
369
370 pub(super) fn load(&self, candidate_id: &str) -> Result<Artifact, String> {
371 let bytes = fs::read(
372 self.root
373 .join("artifacts")
374 .join(format!("{candidate_id}.json")),
375 )
376 .map_err(|error| error.to_string())?;
377 let artifact: Artifact =
378 serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
379 if artifact.schema_version != 2
380 || artifact.candidate_id != candidate_id
381 || artifact.baseline_id != self.baseline_id
382 {
383 return Err("sealed artifact identity mismatch".to_string());
384 }
385 Ok(artifact)
386 }
387
388 pub(super) fn materialize(
389 &self,
390 artifact: &Artifact,
391 destination: &Path,
392 ) -> Result<(), String> {
393 if destination.exists() {
394 return Err("evaluation materialization already exists".to_string());
395 }
396 fs::create_dir(destination).map_err(|error| error.to_string())?;
397 let mut files = self
398 .baseline
399 .iter()
400 .map(|entry| (entry.path.clone(), entry.clone()))
401 .collect::<BTreeMap<_, _>>();
402 let mut previous = None;
403 for change in &artifact.entries {
404 normalized_path(&change.path)?;
405 if previous.is_some_and(|path: &str| path >= change.path.as_str()) {
406 return Err("artifact entries are not strictly sorted".to_string());
407 }
408 previous = Some(&change.path);
409 match change.kind.as_str() {
410 "deleted" if change.blob_hash.is_none() && change.mode.is_none() => {
411 files.remove(&change.path);
412 }
413 "file" => {
414 let entry = FileEntry {
415 path: change.path.clone(),
416 mode: change.mode.ok_or("missing artifact mode")?,
417 size_bytes: change.size_bytes.ok_or("missing artifact size")?,
418 blob_hash: change.blob_hash.clone().ok_or("missing artifact blob")?,
419 };
420 if !matches!(entry.mode, 0o100644 | 0o100755)
421 || entry.size_bytes > MAX_FILE_BYTES
422 || entry.blob_hash.len() != 64
423 || !entry.blob_hash.bytes().all(|byte| byte.is_ascii_hexdigit())
424 {
425 return Err("invalid artifact entry mode or size".to_string());
426 }
427 files.insert(change.path.clone(), entry);
428 }
429 _ => return Err("invalid artifact change kind".to_string()),
430 }
431 }
432 check_paths(files.keys().map(String::as_str))?;
433 let tree = files.values().cloned().collect::<Vec<_>>();
434 if canonical_hash(&tree)? != artifact.candidate_tree_hash
435 || artifact.artifact_id != artifact.candidate_tree_hash
436 {
437 return Err("sealed artifact tree hash mismatch".to_string());
438 }
439 let total = tree.iter().map(|entry| entry.size_bytes).sum::<u64>();
440 if tree.len() > MAX_FILES || total > MAX_TREE_BYTES {
441 return Err("materialized tree exceeds limits".to_string());
442 }
443 for entry in tree {
444 let bytes = fs::read(self.root.join("blobs").join(&entry.blob_hash))
445 .map_err(|error| error.to_string())?;
446 if bytes.len() as u64 != entry.size_bytes || digest(&bytes) != entry.blob_hash {
447 return Err(format!(
448 "sealed artifact blob verification failed: {}",
449 entry.path
450 ));
451 }
452 let target = destination.join(&entry.path);
453 if let Some(parent) = target.parent() {
454 fs::create_dir_all(parent).map_err(|error| error.to_string())?;
455 }
456 fs::write(&target, bytes).map_err(|error| error.to_string())?;
457 #[cfg(unix)]
458 {
459 use std::os::unix::fs::PermissionsExt;
460 fs::set_permissions(&target, fs::Permissions::from_mode(entry.mode & 0o777))
461 .map_err(|error| error.to_string())?;
462 }
463 }
464 Ok(())
465 }
466
467 pub(super) fn review_material(&self, artifact: &Artifact) -> Result<Option<String>, String> {
468 let mut result = String::new();
469 for entry in &artifact.entries {
470 result.push_str(&format!("\nFILE {} {}\n", entry.path, entry.kind));
471 if let Some(previous) = self.baseline.iter().find(|file| file.path == entry.path) {
472 let bytes = fs::read(self.root.join("blobs").join(&previous.blob_hash))
473 .map_err(|error| error.to_string())?;
474 if digest(&bytes) != previous.blob_hash {
475 return Err("review baseline blob hash mismatch".to_string());
476 }
477 let Ok(text) = String::from_utf8(bytes) else {
478 return Ok(None);
479 };
480 result.push_str("BASELINE CONTENT\n");
481 result.push_str(&text);
482 result.push_str("\nCANDIDATE CONTENT\n");
483 }
484 if let Some(blob_hash) = &entry.blob_hash {
485 let bytes = fs::read(self.root.join("blobs").join(blob_hash))
486 .map_err(|error| error.to_string())?;
487 if digest(&bytes) != *blob_hash {
488 return Err("review blob hash mismatch".to_string());
489 }
490 let Ok(text) = String::from_utf8(bytes) else {
491 return Ok(None);
492 };
493 result.push_str(&text);
494 } else {
495 result.push_str("[deleted]\n");
496 }
497 if result.len() > 128 * 1024 {
498 return Ok(None);
499 }
500 }
501 Ok(Some(result))
502 }
503 }
504
504 lines RUST