Skip to main content

greengate_runtime/
gate_identity.rs

1//! What a stamp token says it was made by.
2//!
3//! A gate stamp is keyed by the git TREE, so it proves the content has not
4//! changed since a check passed. It said nothing about WHICH check passed:
5//! upgrade the tool a declared check runs (a new `node`, a reinstalled
6//! `cargo`) and the old pass still skipped the new run. The tree already
7//! covers everything in the repository, the manifest and the lockfiles
8//! included, so this adds only what lives OUTSIDE it.
9//!
10//! A token is `<name>@<identity>`, and only the complete token authorizes a
11//! skip (`hooks.gate-stamp-key`, ADR-0010):
12//!
13//! - **a declared check**: its full command line, its flags, and the identity
14//!   of the program it runs. A program found on `PATH` is identified by the
15//!   resolved binary's path, size and modification time, which a package
16//!   manager's upgrade changes and which needs no command run (a script's own
17//!   `--version` could do anything). A program named by a path inside the
18//!   repository is the tree's business and adds nothing.
19//! - **a built-in**: its name and amont's own version.
20//!
21//! An identity that cannot be worked out — the program is missing, git would
22//! not hash the material — is `None`, and `None` is a cache miss everywhere:
23//! no token is written, none is honoured, the gate runs. Never a skip on a
24//! guess.
25
26use crate::check::Stage;
27use crate::manifest::{External, Kind, RunsOn};
28use std::collections::HashMap;
29use std::sync::{Mutex, OnceLock};
30
31/// How much of the hash a token carries. Sixteen hex digits is far more than
32/// a few dozen gates on one machine can collide in, and keeps a note line
33/// readable.
34const WIDTH: usize = 16;
35
36/// The token for the gate called `name`, whether that is a declared check
37/// (looked up by id, then by a pre-commit short name) or a built-in.
38pub fn token(externals: &[External], name: &str) -> Option<String> {
39    match declared(externals, name) {
40        Some(ext) => external_token(ext, name),
41        None => builtin_token(name),
42    }
43}
44
45/// The declared check called `name`: by id, then by a pre-commit short name.
46fn declared<'a>(externals: &'a [External], name: &str) -> Option<&'a External> {
47    externals.iter().find(|e| e.id == name).or_else(|| {
48        externals
49            .iter()
50            .find(|e| e.stage == Stage::PreCommit && e.short_name == name)
51    })
52}
53
54/// Is the gate called `name` a declared command whose program is not
55/// installed here (ADR-0018)? Such a gate has no identity, so no stamp or
56/// record can ever answer for it. Any other reason a token cannot be made (a
57/// hash git would not compute, a built-in) is not this: those gates stay owed.
58pub fn program_missing(externals: &[External], name: &str) -> bool {
59    match declared(externals, name).map(|ext| &ext.kind) {
60        Some(Kind::Runnable { program, .. }) => binary_identity(program).is_none(),
61        Some(Kind::Unusable { .. }) | None => false,
62    }
63}
64
65/// The token for one declared check, written under `name` (the script name at
66/// commit time, the id at push time).
67pub fn external_token(ext: &External, name: &str) -> Option<String> {
68    let Kind::Runnable {
69        program,
70        args,
71        files,
72        docs_skip,
73        runs_on,
74        ..
75    } = &ext.kind
76    else {
77        return None;
78    };
79    let binary = binary_identity(program)?;
80    // A pre-commit pass recorded before a declared command could find the
81    // index being committed (`GREENGATE_INDEX_FILE`) may have judged the old one
82    // under `commit -a`, through any wrapper: none of them counts, so each
83    // pre-commit gate runs once more. `index` changes what the gate reads
84    // again, so it is part of the token too. Pre-push tokens are unchanged.
85    let commit_index = match (ext.stage, runs_on) {
86        (Stage::PreCommit, RunsOn::Here { reads_index: true }) => "\0commit-index-v1\0index",
87        (Stage::PreCommit, RunsOn::Here { reads_index: false } | RunsOn::AnyPlatform) => {
88            "\0commit-index-v1"
89        }
90        (Stage::PrePush, _) => "",
91    };
92    let material = format!(
93        "declared\0{name}\0{program}\0{}\0files={files}\0docs-skip={docs_skip}\0{binary}{commit_index}",
94        args.join("\u{1f}")
95    );
96    seal(name, &material)
97}
98
99/// The versioned contract between amont and the gate-runner image: the Job
100/// shape, the `fetch` protocol, the verdict rules (ADR-0016). A change to any
101/// of them bumps this, which invalidates every cluster token at once.
102pub const CLUSTER_CONTRACT: &str = "amont-cluster-v1";
103
104/// The token a CLUSTER pass of one declared check is written under, in
105/// `refs/notes/amont-gate-cluster` (ADR-0016). Separate from
106/// [`external_token`] on purpose: the program runs in the pinned image, not
107/// on this laptop, so the laptop's executable is never inspected — the image
108/// digest stands where the binary identity stands there. `None` for a check
109/// that is not runnable, or a hash git would not make.
110pub(crate) fn cluster_token(
111    ext: &External,
112    name: &str,
113    prepare: Option<&str>,
114    image_digest: &str,
115) -> Option<String> {
116    let Kind::Runnable {
117        program,
118        args,
119        files,
120        docs_skip,
121        ..
122    } = &ext.kind
123    else {
124        return None;
125    };
126    let material = format!(
127        "{CLUSTER_CONTRACT}\0{name}\0{program}\0{}\0files={files}\0docs-skip={docs_skip}\0\
128         prepare={}\0image={image_digest}",
129        args.join("\u{1f}"),
130        prepare.unwrap_or("")
131    );
132    seal(name, &material)
133}
134
135/// A built-in gate's token.
136pub fn builtin_token(name: &str) -> Option<String> {
137    seal(
138        name,
139        &format!("builtin\0{name}\0{}", env!("CARGO_PKG_VERSION")),
140    )
141}
142
143/// The name a token was written under, for display and accounting only.
144pub fn base(token: &str) -> &str {
145    token.split_once('@').map_or(token, |(name, _)| name)
146}
147
148fn seal(name: &str, material: &str) -> Option<String> {
149    static MEMO: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
150    seal_with(
151        MEMO.get_or_init(Default::default),
152        name,
153        material,
154        crate::tree_cache::hash,
155    )
156}
157
158fn seal_with(
159    memo: &Mutex<HashMap<String, Option<String>>>,
160    name: &str,
161    material: &str,
162    hasher: impl Fn(&str) -> Option<String>,
163) -> Option<String> {
164    let cached = memo
165        .lock()
166        .unwrap_or_else(|p| p.into_inner())
167        .get(material)
168        .cloned();
169    let hash = match cached.flatten() {
170        Some(h) => h,
171        None => {
172            // Only an answer is remembered. A failed hash is a cache miss for
173            // this call alone; the next ask tries git again.
174            let h = hasher(material)?;
175            memo.lock()
176                .unwrap_or_else(|p| p.into_inner())
177                .insert(material.to_string(), Some(h.clone()));
178            h
179        }
180    };
181    Some(format!("{name}@{}", hash.get(..WIDTH).unwrap_or(&hash)))
182}
183
184/// Who a program is, as far as a skip needs to know.
185fn binary_identity(program: &str) -> Option<String> {
186    if program.contains('/') && !std::path::Path::new(program).is_absolute() {
187        // Relative to the repository: its content is in the tree.
188        return Some("in-tree".to_string());
189    }
190    let path = if program.contains('/') {
191        std::path::PathBuf::from(program)
192    } else {
193        which(program)?
194    };
195    let canonical = std::fs::canonicalize(&path).ok()?;
196    let meta = std::fs::metadata(&canonical).ok()?;
197    let modified = meta
198        .modified()
199        .ok()?
200        .duration_since(std::time::UNIX_EPOCH)
201        .ok()?
202        .as_secs();
203    Some(format!("{}:{}:{modified}", canonical.display(), meta.len()))
204}
205
206/// The first executable called `program` on `PATH`.
207fn which(program: &str) -> Option<std::path::PathBuf> {
208    let path = std::env::var_os("PATH")?;
209    for dir in std::env::split_paths(&path) {
210        for suffix in ["", ".exe", ".cmd", ".bat"] {
211            let candidate = dir.join(format!("{program}{suffix}"));
212            if is_executable(&candidate) {
213                return Some(candidate);
214            }
215        }
216    }
217    None
218}
219
220#[cfg(unix)]
221fn is_executable(p: &std::path::Path) -> bool {
222    use std::os::unix::fs::PermissionsExt;
223    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
224}
225
226#[cfg(not(unix))]
227fn is_executable(p: &std::path::Path) -> bool {
228    p.is_file()
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn a_token_names_its_gate_and_is_stable() {
237        let a = builtin_token("pre-push-cargo-test").expect("git hashes");
238        let b = builtin_token("pre-push-cargo-test").expect("git hashes");
239        assert_eq!(a, b);
240        assert!(a.starts_with("pre-push-cargo-test@"));
241        assert_eq!(base(&a), "pre-push-cargo-test");
242        assert_eq!(a.len(), "pre-push-cargo-test@".len() + WIDTH);
243    }
244
245    #[test]
246    fn different_gates_do_not_share_an_identity() {
247        let a = builtin_token("pre-push-cargo-test").expect("hash");
248        let b = builtin_token("pre-push-run-tests-js").expect("hash");
249        assert_ne!(
250            a.split_once('@').map(|x| x.1),
251            b.split_once('@').map(|x| x.1)
252        );
253    }
254
255    /// One failed hash (a fork the scheduler refused) must not decide this
256    /// gate's identity for the rest of the process: the next ask tries again.
257    #[test]
258    fn a_failed_hash_is_not_remembered() {
259        let memo = Mutex::new(HashMap::new());
260        let calls = std::cell::Cell::new(0);
261        let flaky = |_: &str| {
262            calls.set(calls.get() + 1);
263            (calls.get() > 1).then(|| "0123456789abcdef0123".to_string())
264        };
265        assert_eq!(seal_with(&memo, "gate", "m", flaky), None);
266        assert_eq!(
267            seal_with(&memo, "gate", "m", flaky).as_deref(),
268            Some("gate@0123456789abcdef")
269        );
270        // A good answer IS remembered: no third hash.
271        assert!(seal_with(&memo, "gate", "m", flaky).is_some());
272        assert_eq!(calls.get(), 2);
273    }
274
275    /// The cluster identity follows the image digest and the prepare command,
276    /// and never needs the program on this machine.
277    #[test]
278    fn a_cluster_token_follows_the_image_and_needs_no_local_binary() {
279        let ext = crate::manifest::parse(
280            "pre-commit lint * block platform=any definitely-not-a-program-xyz --x\n",
281        )
282        .pop()
283        .expect("one check");
284        assert_eq!(external_token(&ext, "lint"), None, "no local binary");
285        let a = cluster_token(&ext, "pre-commit-lint", None, "sha256:aa").expect("hash");
286        let b = cluster_token(&ext, "pre-commit-lint", None, "sha256:bb").expect("hash");
287        let c = cluster_token(&ext, "pre-commit-lint", Some("make deps"), "sha256:aa").expect("h");
288        assert!(a.starts_with("pre-commit-lint@"));
289        assert_ne!(a, b);
290        assert_ne!(a, c);
291        assert_eq!(
292            cluster_token(&ext, "pre-commit-lint", None, "sha256:aa"),
293            Some(a)
294        );
295    }
296
297    /// A pre-commit pass from before amont told a gate the index being
298    /// committed does not count (it may have judged the old index), and the
299    /// `index` marker changes what the gate reads again: both are in the
300    /// token. A pre-push gate keeps the token it had.
301    #[test]
302    fn a_commit_time_token_follows_what_the_gate_could_read() {
303        let one = |line: &str| crate::manifest::parse(line).pop().expect("one check");
304        let plain = one("pre-commit lint * block sh -c true\n");
305        let marked = one("pre-commit lint * block index sh -c true\n");
306        let pushed = one("pre-push lint * block sh -c true\n");
307        let plain_token = external_token(&plain, "lint").expect("sh is there");
308        let marked_token = external_token(&marked, "lint").expect("sh is there");
309        assert_ne!(plain_token, marked_token);
310        let binary = binary_identity("sh").expect("sh is there");
311        let before = seal(
312            "lint",
313            &format!("declared\0lint\0sh\0-c\u{1f}true\0files=false\0docs-skip=false\0{binary}"),
314        )
315        .expect("hash");
316        assert_ne!(
317            plain_token, before,
318            "a blind pass recorded before no longer counts"
319        );
320        assert_eq!(
321            external_token(&pushed, "lint").expect("sh is there"),
322            before,
323            "a pre-push token is unchanged"
324        );
325    }
326
327    /// Only a declared command whose program cannot be found is "missing":
328    /// a built-in, or an installed program, is not, whatever its token does.
329    #[test]
330    fn only_a_declared_program_that_is_not_there_is_missing() {
331        let externals = crate::manifest::parse(
332            "pre-push gone * block definitely-not-a-program-xyz --x\n\
333             pre-push here * block sh -c true\n\
334             pre-push broken * nonsense sh -c true\n",
335        );
336        assert!(
337            externals
338                .iter()
339                .any(|e| e.id == "pre-push-broken" && matches!(e.kind, Kind::Unusable { .. })),
340            "the fixture's third line is unusable"
341        );
342        assert!(!program_missing(&externals, "pre-push-broken"));
343        assert!(program_missing(&externals, "pre-push-gone"));
344        assert!(!program_missing(&externals, "pre-push-here"));
345        assert!(!program_missing(&externals, "pre-push-cargo-test"));
346        assert!(!program_missing(&externals, "no-such-gate"));
347    }
348
349    #[test]
350    fn a_bare_name_has_no_namespace() {
351        assert_eq!(base("typecheck"), "typecheck");
352        assert_eq!(base("typecheck@abc"), "typecheck");
353    }
354
355    #[test]
356    fn a_program_that_is_not_there_has_no_identity() {
357        assert_eq!(binary_identity("definitely-not-a-program-xyz"), None);
358    }
359
360    #[test]
361    #[cfg(unix)]
362    fn a_program_on_path_is_identified_by_its_binary() {
363        let a = binary_identity("sh").expect("sh is on every PATH");
364        assert!(a.contains("sh"), "{a}");
365        assert_eq!(binary_identity("sh"), Some(a));
366    }
367
368    #[test]
369    fn a_repo_relative_script_is_the_trees_business() {
370        assert_eq!(
371            binary_identity("scripts/gate.sh").as_deref(),
372            Some("in-tree")
373        );
374    }
375}