interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / diff_gate.rs

581 lines · 20879 bytes Raw Blame History
1//! Real-diff gate for the ratifier.
2//!
3//! The ratifier never trusts the file name a proposal declares. It builds the
4//! candidate commit off to the side (temporary index, no checkout, no branch
5//! moved), asks git for the actual changed entries between the base commit and
6//! the candidate commit, and runs every protected-file check on that real list.
7//!
8//! Rules, all fail closed:
9//! - a path must be relative, non-empty, valid UTF-8, without `\`, NUL, `..`,
10//! or a `.git` component;
11//! - a path must sit inside one of the declared roots;
12//! - a changed entry must be a regular file (mode 100644 or 100755) on both
13//! sides; symlinks (120000) and submodules (160000) are refused;
14//! - the real changed set must be exactly the declared target file;
15//! - `RootOfTrust::validate_declared_files` and
16//! `SecurityLayer::evaluate_candidate` run on the real paths and real patch.
17//!
18//! There is no flag, tier, or environment variable that skips these checks.
19
20use crate::evaluator::SecurityLayer;
21use crate::isolation::RootOfTrust;
22use std::path::Path;
23use std::process::{Command, Stdio};
24
25/// The tier the ratifier evaluates at. Root-of-trust files need tier 2; the
26/// ratifier never grants it, so protected files always need a human change.
27pub const RATIFIER_TIER: u8 = 1;
28
29/// Roots a proposal may touch when the config does not say otherwise.
30pub const DEFAULT_RATIFY_ROOTS: &[&str] = &["README.md", "CONTRIBUTING.md", "docs", "src"];
31
32pub fn default_ratify_roots() -> Vec<String> {
33 DEFAULT_RATIFY_ROOTS.iter().map(|s| s.to_string()).collect()
34}
35
36/// Normalizes a repository-relative path and refuses anything that could
37/// point outside the repository or into git's own metadata.
38pub fn normalize_repo_path(raw: &str) -> Result<String, String> {
39 if raw.is_empty() {
40 return Err("empty path".to_string());
41 }
42 if raw.contains('\0') {
43 return Err(format!("path contains NUL: {:?}", raw));
44 }
45 if raw.contains('\\') {
46 return Err(format!("path contains backslash: {:?}", raw));
47 }
48 if raw.starts_with('/') {
49 return Err(format!("absolute path refused: {:?}", raw));
50 }
51 let mut parts: Vec<&str> = Vec::new();
52 for comp in raw.split('/') {
53 match comp {
54 "" | "." => continue,
55 ".." => return Err(format!("parent-directory component refused: {:?}", raw)),
56 c if c.eq_ignore_ascii_case(".git") => {
57 return Err(format!("git metadata path refused: {:?}", raw))
58 }
59 c => parts.push(c),
60 }
61 }
62 if parts.is_empty() {
63 return Err(format!("path names the repository root: {:?}", raw));
64 }
65 Ok(parts.join("/"))
66}
67
68/// True when `path` (already normalized) equals a root or sits below it,
69/// compared whole component by whole component.
70pub fn within_roots(path: &str, roots: &[String]) -> bool {
71 let p: Vec<&str> = path.split('/').collect();
72 roots.iter().any(|root| match normalize_repo_path(root) {
73 Ok(r) => {
74 let r: Vec<&str> = r.split('/').collect();
75 p.len() >= r.len() && p[..r.len()] == r[..]
76 }
77 Err(_) => false,
78 })
79}
80
81/// Checks a declared target before anything is staged or written.
82pub fn check_declared_target(target_file: &str, roots: &[String]) -> Result<String, String> {
83 let normalized = normalize_repo_path(target_file)?;
84 if !within_roots(&normalized, roots) {
85 return Err(format!(
86 "target {:?} is outside the declared roots {:?}",
87 normalized, roots
88 ));
89 }
90 RootOfTrust::assert_patch_permitted(&normalized, RATIFIER_TIER)?;
91 Ok(normalized)
92}
93
94/// One changed entry reported by `git diff-tree --raw`.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct ChangedEntry {
97 pub old_mode: String,
98 pub new_mode: String,
99 pub status: char,
100 pub path: String,
101}
102
103fn git(repo: &Path) -> Command {
104 let mut c = Command::new("git");
105 c.arg("-C").arg(repo);
106 // A repo-local hook or config must not run code during ratification.
107 c.args(["-c", "core.hooksPath=/dev/null"]);
108 c
109}
110
111fn run(mut cmd: Command, what: &str) -> Result<String, String> {
112 let out = cmd
113 .stdin(Stdio::null())
114 .output()
115 .map_err(|e| format!("{}: {}", what, e))?;
116 if !out.status.success() {
117 return Err(format!(
118 "{} failed: {}",
119 what,
120 String::from_utf8_lossy(&out.stderr).trim()
121 ));
122 }
123 Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
124}
125
126/// Parses `git diff-tree -r -z --raw --no-renames` output.
127pub fn parse_raw_diff(raw: &[u8]) -> Result<Vec<ChangedEntry>, String> {
128 let mut entries = Vec::new();
129 let mut fields = raw.split(|b| *b == 0).filter(|f| !f.is_empty());
130 while let Some(meta) = fields.next() {
131 let meta = std::str::from_utf8(meta).map_err(|_| "non-UTF-8 diff header".to_string())?;
132 let meta = meta
133 .strip_prefix(':')
134 .ok_or_else(|| format!("unexpected diff header {:?}", meta))?;
135 let cols: Vec<&str> = meta.split(' ').collect();
136 if cols.len() != 5 {
137 return Err(format!("unexpected diff header {:?}", meta));
138 }
139 let status = cols[4]
140 .chars()
141 .next()
142 .ok_or_else(|| "empty diff status".to_string())?;
143 let path = fields
144 .next()
145 .ok_or_else(|| "diff entry without a path".to_string())?;
146 let path = std::str::from_utf8(path)
147 .map_err(|_| "non-UTF-8 path in diff".to_string())?
148 .to_string();
149 entries.push(ChangedEntry {
150 old_mode: cols[0].to_string(),
151 new_mode: cols[1].to_string(),
152 status,
153 path,
154 });
155 }
156 Ok(entries)
157}
158
159/// Asks git for the real changed entries between two commits.
160pub fn real_diff(repo: &Path, base: &str, head: &str) -> Result<Vec<ChangedEntry>, String> {
161 let out = git(repo)
162 .args(["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head])
163 .stdin(Stdio::null())
164 .output()
165 .map_err(|e| format!("git diff-tree: {}", e))?;
166 if !out.status.success() {
167 return Err(format!(
168 "git diff-tree failed: {}",
169 String::from_utf8_lossy(&out.stderr).trim()
170 ));
171 }
172 parse_raw_diff(&out.stdout)
173}
174
175/// Unified diff text of the real change, used for the content checks.
176pub fn real_patch_text(repo: &Path, base: &str, head: &str) -> Result<String, String> {
177 let mut c = git(repo);
178 c.args([
179 "diff",
180 "--no-ext-diff",
181 "--no-textconv",
182 "--no-color",
183 base,
184 head,
185 ]);
186 run(c, "git diff")
187}
188
189fn is_regular_mode(mode: &str) -> bool {
190 mode == "100644" || mode == "100755"
191}
192
193/// Every check on the real diff. Returns the list of violations; empty means pass.
194pub fn check_real_diff(
195 entries: &[ChangedEntry],
196 patch_text: &str,
197 declared_target: &str,
198 roots: &[String],
199) -> Vec<String> {
200 let mut violations = Vec::new();
201 if entries.is_empty() {
202 violations.push("real diff is empty; nothing to propose".to_string());
203 }
204 let mut real_paths = Vec::new();
205 for e in entries {
206 let normalized = match normalize_repo_path(&e.path) {
207 Ok(p) => p,
208 Err(err) => {
209 violations.push(format!("real diff path refused: {}", err));
210 continue;
211 }
212 };
213 if normalized != e.path {
214 violations.push(format!("real diff path is not canonical: {:?}", e.path));
215 }
216 if !within_roots(&normalized, roots) {
217 violations.push(format!(
218 "real diff touches {:?}, outside the declared roots {:?}",
219 normalized, roots
220 ));
221 }
222 let old_ok = e.old_mode == "000000" || is_regular_mode(&e.old_mode);
223 let new_ok = e.new_mode == "000000" || is_regular_mode(&e.new_mode);
224 if !old_ok || !new_ok {
225 violations.push(format!(
226 "real diff entry {:?} is not a regular file (mode {} -> {}); symlinks and submodules are refused",
227 normalized, e.old_mode, e.new_mode
228 ));
229 }
230 if e.new_mode == "000000" || e.status == 'D' {
231 violations.push(format!(
232 "real diff deletes {:?}; deletions are refused",
233 normalized
234 ));
235 }
236 real_paths.push(normalized);
237 }
238 if real_paths.len() != 1 || real_paths[0] != declared_target {
239 violations.push(format!(
240 "real diff paths {:?} differ from the declared target {:?}",
241 real_paths, declared_target
242 ));
243 }
244 if let Err(errs) = RootOfTrust::validate_declared_files(&real_paths, RATIFIER_TIER) {
245 violations.extend(errs);
246 }
247 // Content checks look at what the change adds, not at unchanged context lines.
248 let added: String = patch_text
249 .lines()
250 .filter(|l| l.starts_with('+') && !l.starts_with("+++"))
251 .map(|l| format!("{}\n", &l[1..]))
252 .collect();
253 let sec = SecurityLayer::evaluate_candidate(&real_paths, &added, RATIFIER_TIER);
254 if !sec.passed {
255 violations.extend(sec.violations);
256 }
257 violations
258}
259
260/// The candidate built off to the side.
261#[derive(Debug, Clone)]
262pub struct StagedCandidate {
263 pub base: String,
264 pub commit: String,
265 pub entries: Vec<ChangedEntry>,
266 pub patch_text: String,
267}
268
269/// Builds the candidate commit with a temporary index. Nothing in the working
270/// tree, the real index, or any branch changes. The commit object is left
271/// unreferenced until the caller decides to create a review branch.
272pub fn stage_candidate_commit(
273 repo: &Path,
274 target_path: &str,
275 contents: &[u8],
276 author_name: &str,
277 author_email: &str,
278 message: &str,
279) -> Result<StagedCandidate, String> {
280 let mut c = git(repo);
281 c.args(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
282 let base = run(c, "resolve base commit")?;
283 if base.is_empty() {
284 return Err("target repository has no base commit".to_string());
285 }
286
287 // Keep the existing executable bit; refuse a symlink or submodule target,
288 // and refuse a target whose parent directory is a symlink in the base tree.
289 let mut mode = "100644".to_string();
290 let parts: Vec<&str> = target_path.split('/').collect();
291 for i in 1..=parts.len() {
292 let prefix = parts[..i].join("/");
293 let mut c = git(repo);
294 c.args(["ls-tree", "-z", &base, "--", &prefix]);
295 let listing = run(c, "inspect base tree")?;
296 if let Some(entry) = listing.split('\0').find(|l| !l.is_empty()) {
297 let entry_mode = entry.split(' ').next().unwrap_or("");
298 if entry_mode == "120000" || entry_mode == "160000" {
299 return Err(format!(
300 "{:?} is a symlink or submodule in the base tree; refused",
301 prefix
302 ));
303 }
304 if i == parts.len() && is_regular_mode(entry_mode) {
305 mode = entry_mode.to_string();
306 }
307 }
308 }
309
310 let tmp = tempfile::tempdir().map_err(|e| format!("temp index dir: {}", e))?;
311 let index = tmp.path().join("index");
312
313 let mut c = git(repo);
314 c.env("GIT_INDEX_FILE", &index).args(["read-tree", &base]);
315 run(c, "read base tree into temporary index")?;
316
317 let mut child = git(repo)
318 .args(["hash-object", "-w", "--no-filters", "--stdin"])
319 .stdin(Stdio::piped())
320 .stdout(Stdio::piped())
321 .stderr(Stdio::piped())
322 .spawn()
323 .map_err(|e| format!("git hash-object: {}", e))?;
324 {
325 use std::io::Write;
326 let mut stdin = child.stdin.take().ok_or("hash-object stdin")?;
327 stdin
328 .write_all(contents)
329 .map_err(|e| format!("write blob: {}", e))?;
330 }
331 let out = child
332 .wait_with_output()
333 .map_err(|e| format!("git hash-object: {}", e))?;
334 if !out.status.success() {
335 return Err(format!(
336 "git hash-object failed: {}",
337 String::from_utf8_lossy(&out.stderr).trim()
338 ));
339 }
340 let blob = String::from_utf8_lossy(&out.stdout).trim().to_string();
341
342 let mut c = git(repo);
343 c.env("GIT_INDEX_FILE", &index).args([
344 "update-index",
345 "--add",
346 "--cacheinfo",
347 &format!("{},{},{}", mode, blob, target_path),
348 ]);
349 run(c, "add blob to temporary index")?;
350
351 let mut c = git(repo);
352 c.env("GIT_INDEX_FILE", &index).args(["write-tree"]);
353 let tree = run(c, "write candidate tree")?;
354
355 let mut c = git(repo);
356 c.env("GIT_AUTHOR_NAME", author_name)
357 .env("GIT_AUTHOR_EMAIL", author_email)
358 .env("GIT_COMMITTER_NAME", author_name)
359 .env("GIT_COMMITTER_EMAIL", author_email)
360 .args(["commit-tree", &tree, "-p", &base, "-m", message]);
361 let commit = run(c, "create candidate commit")?;
362
363 let entries = real_diff(repo, &base, &commit)?;
364 let patch_text = real_patch_text(repo, &base, &commit)?;
365 Ok(StagedCandidate {
366 base,
367 commit,
368 entries,
369 patch_text,
370 })
371}
372
373/// Branch names the ratifier must never write to.
374pub fn default_branch_names(repo: &Path) -> Vec<String> {
375 let mut names = vec!["main".to_string(), "master".to_string()];
376 let mut c = git(repo);
377 c.args(["symbolic-ref", "--quiet", "--short", "HEAD"]);
378 if let Ok(h) = run(c, "current branch") {
379 if !h.is_empty() {
380 names.push(h);
381 }
382 }
383 let mut c = git(repo);
384 c.args([
385 "symbolic-ref",
386 "--quiet",
387 "--short",
388 "refs/remotes/origin/HEAD",
389 ]);
390 if let Ok(h) = run(c, "origin default branch") {
391 if let Some(b) = h.strip_prefix("origin/") {
392 names.push(b.to_string());
393 }
394 }
395 let mut c = git(repo);
396 c.args(["config", "--get", "init.defaultBranch"]);
397 if let Ok(h) = run(c, "init.defaultBranch") {
398 if !h.is_empty() {
399 names.push(h);
400 }
401 }
402 names
403}
404
405/// Review branch name for a proposal id. Only `[A-Za-z0-9_-]` ids are accepted.
406pub fn review_branch_name(proposal_id: &str) -> Result<String, String> {
407 if proposal_id.is_empty()
408 || proposal_id.len() > 100
409 || !proposal_id
410 .chars()
411 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
412 {
413 return Err(format!(
414 "proposal id {:?} is not usable in a branch name",
415 proposal_id
416 ));
417 }
418 Ok(format!("rsi/{}", proposal_id))
419}
420
421/// Creates the review branch at `commit`. Refuses to touch a default branch,
422/// and refuses to move a branch that already exists (create-only update).
423pub fn create_review_branch(repo: &Path, branch: &str, commit: &str) -> Result<(), String> {
424 let short = branch.trim_start_matches("refs/heads/");
425 if default_branch_names(repo).iter().any(|d| d == short) {
426 return Err(format!("refusing to write default branch {:?}", short));
427 }
428 let full = format!("refs/heads/{}", short);
429 let mut c = git(repo);
430 c.args(["check-ref-format", &full]);
431 run(c, "check branch name")?;
432 let mut c = git(repo);
433 // Empty old value: the ref must not exist yet.
434 c.args(["update-ref", "-m", "rsi: review branch", &full, commit, ""]);
435 run(c, "create review branch")?;
436 Ok(())
437}
438
439/// Mailbox-format patch of the review commit, ready for a PR or `git am`.
440pub fn format_patch(repo: &Path, commit: &str) -> Result<String, String> {
441 let mut c = git(repo);
442 c.args(["format-patch", "-1", "--stdout", "--no-color", commit]);
443 run(c, "format patch")
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 fn roots() -> Vec<String> {
451 default_ratify_roots()
452 }
453
454 #[test]
455 fn normalization_rejects_escape_forms() {
456 assert_eq!(normalize_repo_path("./docs//a.md").unwrap(), "docs/a.md");
457 assert!(normalize_repo_path("../x").is_err());
458 assert!(normalize_repo_path("docs/../Cargo.toml").is_err());
459 assert!(normalize_repo_path("/etc/passwd").is_err());
460 assert!(normalize_repo_path("docs\\..\\Cargo.toml").is_err());
461 assert!(normalize_repo_path(".git/hooks/pre-commit").is_err());
462 assert!(normalize_repo_path("docs/.GIT/config").is_err());
463 assert!(normalize_repo_path("docs/a\0b").is_err());
464 assert!(normalize_repo_path("./").is_err());
465 assert!(normalize_repo_path("").is_err());
466 }
467
468 #[test]
469 fn roots_match_whole_components_only() {
470 assert!(within_roots("docs/a.md", &roots()));
471 assert!(within_roots("README.md", &roots()));
472 assert!(!within_roots("docsx/a.md", &roots()));
473 assert!(!within_roots("README.md.bak", &roots()));
474 assert!(!within_roots("Cargo.toml", &roots()));
475 assert!(!within_roots(".github/workflows/ci.yml", &roots()));
476 }
477
478 #[test]
479 fn declared_target_check_refuses_protected_and_outside() {
480 assert!(check_declared_target("README.md", &roots()).is_ok());
481 assert!(check_declared_target("Cargo.toml", &roots()).is_err());
482 assert!(check_declared_target("src/isolation/root_of_trust.rs", &roots()).is_err());
483 assert!(check_declared_target("src/../Cargo.toml", &roots()).is_err());
484 assert!(check_declared_target("scripts/run.sh", &roots()).is_err());
485 }
486
487 #[test]
488 fn raw_diff_parser_reads_modes_and_paths() {
489 let raw =
490 b":100644 120000 aaaa bbbb T\0docs/link\0:000000 100644 0000 cccc A\0docs/new.md\0";
491 let e = parse_raw_diff(raw).unwrap();
492 assert_eq!(e.len(), 2);
493 assert_eq!(e[0].new_mode, "120000");
494 assert_eq!(e[0].path, "docs/link");
495 assert_eq!(e[1].status, 'A');
496 }
497
498 #[test]
499 fn real_diff_check_catches_symlink_and_extra_files() {
500 let link = vec![ChangedEntry {
501 old_mode: "000000".into(),
502 new_mode: "120000".into(),
503 status: 'A',
504 path: "docs/link".into(),
505 }];
506 assert!(!check_real_diff(&link, "", "docs/link", &roots()).is_empty());
507
508 let extra = vec![
509 ChangedEntry {
510 old_mode: "100644".into(),
511 new_mode: "100644".into(),
512 status: 'M',
513 path: "README.md".into(),
514 },
515 ChangedEntry {
516 old_mode: "100644".into(),
517 new_mode: "100644".into(),
518 status: 'M',
519 path: "Cargo.toml".into(),
520 },
521 ];
522 let v = check_real_diff(&extra, "", "README.md", &roots());
523 assert!(v.iter().any(|m| m.contains("Cargo.toml")));
524 }
525
526 #[test]
527 fn real_diff_check_alone_refuses_protected_file() {
528 // Even if the declared check were skipped and roots listed it.
529 let roots = vec!["Cargo.toml".to_string()];
530 let e = vec![ChangedEntry {
531 old_mode: "100644".into(),
532 new_mode: "100644".into(),
533 status: 'M',
534 path: "Cargo.toml".into(),
535 }];
536 let v = check_real_diff(&e, "", "Cargo.toml", &roots);
537 assert!(v.iter().any(|m| m.contains("protected")), "{:?}", v);
538 }
539
540 #[test]
541 fn real_diff_check_runs_root_of_trust_itself_not_only_via_security_layer() {
542 // A protected file inside a default root ("src"). Both the gate's own
543 // RootOfTrust call and the SecurityLayer must refuse it, independently.
544 // The SecurityLayer wraps its finding as "Root-of-trust violation: ...";
545 // the gate's direct call reports "SECURITY VIOLATION: ..." unwrapped.
546 // Removing the direct RootOfTrust call in check_real_diff fails this test.
547 let path = "src/isolation/container.rs";
548 assert!(within_roots(path, &roots()));
549 let e = vec![ChangedEntry {
550 old_mode: "100644".into(),
551 new_mode: "100644".into(),
552 status: 'M',
553 path: path.into(),
554 }];
555 let v = check_real_diff(&e, "", path, &roots());
556 let direct: Vec<&String> = v
557 .iter()
558 .filter(|m| m.starts_with("SECURITY VIOLATION:") && m.contains(path))
559 .collect();
560 assert_eq!(
561 direct.len(),
562 1,
563 "gate's own root-of-trust refusal missing: {:?}",
564 v
565 );
566 assert!(
567 v.iter()
568 .any(|m| m.starts_with("Root-of-trust violation:") && m.contains(path)),
569 "security layer refusal missing: {:?}",
570 v
571 );
572 }
573
574 #[test]
575 fn branch_names_are_sanitized() {
576 assert_eq!(review_branch_name("prop-abc").unwrap(), "rsi/prop-abc");
577 assert!(review_branch_name("../main").is_err());
578 assert!(review_branch_name("a b").is_err());
579 assert!(review_branch_name("").is_err());
580 }
581}