Skip to main content

greensummit/
notes.rs

1//! The notes refs as origin's mirror (SPEC.md, "Which refs are read").
2
3use std::path::Path;
4use std::process::{Command, Stdio};
5
6use crate::format::{Names, WRITE};
7use crate::git;
8
9/// What became of one notes ref. SPEC.md, "Lookup".
10///
11/// `refs/notes/greensummit[-inputs]` are ORIGIN'S MIRROR, and origin is the
12/// only place an attestation can be revoked, so only a mirror that is
13/// origin's ref right now — or a repository with no origin at all, which is
14/// for fixtures and local use — is judged.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub enum Mirror {
17    /// Fetched: the mirror is origin's ref.
18    Fresh,
19    /// No remote named origin: the local ref is judged as it is.
20    NoOrigin,
21    /// Origin answered and has no such ref: the mirror was deleted.
22    Deleted,
23    /// As `Deleted`, but the delete failed: the stale mirror is not judged.
24    Undeletable,
25    /// Origin is configured and did not answer: not judged.
26    Unreachable,
27    /// As `Unreachable`, because the deadline cut the call off.
28    TimedOut,
29    /// Origin's copy was fetched but could not be made the local ref (a
30    /// stale lock, say): the stale local copy is not judged.
31    Unwritable,
32}
33
34impl Mirror {
35    pub fn as_str(self) -> &'static str {
36        match self {
37            Mirror::Fresh => "fetched",
38            Mirror::NoOrigin => "no-origin",
39            Mirror::Deleted => "absent",
40            Mirror::Undeletable => "undeletable",
41            Mirror::Unreachable | Mirror::TimedOut => "unreachable",
42            Mirror::Unwritable => "unwritable",
43        }
44    }
45    pub fn judged(self) -> bool {
46        matches!(self, Mirror::Fresh | Mirror::NoOrigin)
47    }
48}
49
50/// Delete the mirror of `notes_ref` because origin has none.
51fn drop_mirror(root: &Path, loud: &mut Vec<String>, notes_ref: &str) -> Mirror {
52    let full = format!("refs/notes/{notes_ref}");
53    let Some(oid) = git::stdout_in(root, &["rev-parse", "--verify", "--quiet", &full]) else {
54        return Mirror::Deleted;
55    };
56    if git::succeeds_in(root, &["update-ref", "-d", &full, &oid]) {
57        loud.push(format!(
58            "origin has no {full}; deleted the local mirror (was {oid}); restore: git update-ref {full} {oid}"
59        ));
60        Mirror::Deleted
61    } else {
62        Mirror::Undeletable
63    }
64}
65
66/// Where fetches land before they become the mirror: outside `refs/notes/`,
67/// one directory per process id, so no notes push or pruning fetch ever
68/// touches them.
69pub(crate) const TMP_NS: &str = "refs/greensummit-tmp/";
70
71/// Remove the throwaways of runs killed before their cleanup — only those
72/// whose process is gone, so a concurrent run in the same clone keeps its
73/// own. Where liveness cannot be asked, nothing is swept: a leftover outside
74/// `refs/notes/` is inert.
75fn sweep_tmp_refs(root: &Path) {
76    let Some(refs) = git::stdout_in(root, &["for-each-ref", "--format=%(refname)", TMP_NS]) else {
77        return;
78    };
79    let me = std::process::id().to_string();
80    for r in refs.lines() {
81        let Some(pid) = r
82            .strip_prefix(TMP_NS)
83            .and_then(|rest| rest.split('/').next())
84            .filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
85        else {
86            continue;
87        };
88        if pid != me && process_gone(pid) {
89            let _ = git::succeeds_in(root, &["update-ref", "-d", r]);
90        }
91    }
92}
93
94/// True only on a positive "no such process" (read in the C locale); any
95/// other answer, or none, counts as alive, so nothing live is swept.
96fn process_gone(pid: &str) -> bool {
97    if !cfg!(unix) {
98        return false;
99    }
100    Command::new("kill")
101        .args(["-0", pid])
102        .env("LC_ALL", "C")
103        .stdin(Stdio::null())
104        .stdout(Stdio::null())
105        .stderr(Stdio::piped())
106        .output()
107        .is_ok_and(|o| {
108            !o.status.success()
109                && String::from_utf8_lossy(&o.stderr)
110                    .to_lowercase()
111                    .contains("no such process")
112        })
113}
114
115/// Make the fetched copy in `tmp` the mirror of `notes_ref`, by a
116/// compare-and-swap against `old` (what was there before the fetch). A kill
117/// can only ever half-write the throwaway, never the mirror. When the swap
118/// fails, the mirror is judged only if it now holds EXACTLY origin's copy (a
119/// concurrent run got there first, or origin is unchanged under a lock).
120fn adopt(root: &Path, notes_ref: &str, tmp: &str, old: Option<&str>) -> Mirror {
121    let full = format!("refs/notes/{notes_ref}");
122    let Some(new) = git::stdout_in(root, &["rev-parse", "--verify", "--quiet", tmp]) else {
123        return Mirror::Unwritable;
124    };
125    if git::succeeds_in(root, &["update-ref", &full, &new, old.unwrap_or("")]) {
126        return Mirror::Fresh;
127    }
128    match git::stdout_in(root, &["rev-parse", "--verify", "--quiet", &full]) {
129        Some(now) if now == new => Mirror::Fresh,
130        _ => Mirror::Unwritable,
131    }
132}
133
134/// Bring both mirrors of the written names ([`WRITE`]) in line with origin:
135/// one fetch of both refs into
136/// throwaways and, when that fails without timing out, one `ls-remote` to
137/// tell "origin has no such ref" from "origin did not answer" — then, if some
138/// refs exist, one more fetch of those. A silent origin costs one call (15 s
139/// at most), a dead one two (30 s), the worst case three (45 s).
140pub fn sync_mirrors(root: &Path, loud: &mut Vec<String>) -> (Mirror, Mirror) {
141    let synced = sync_mirrors_of(root, &WRITE);
142    loud.extend(synced.loud);
143    (synced.notes, synced.inputs)
144}
145
146/// What one name set's sync came to: the state of its notes ref and of its
147/// inputs ref, and the lines that report a change to the repository's refs
148/// (a mirror deleted, with how to restore it).
149#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151pub struct Synced {
152    pub notes: Mirror,
153    pub inputs: Mirror,
154    pub loud: Vec<String>,
155}
156
157impl Synced {
158    /// How origin failed to answer for this set, if it did not: `TimedOut`
159    /// when a deadline cut any call off, `Unreachable` when both refs are.
160    /// Another set's sync would only wait again, so it takes this state.
161    pub fn origin_silent(&self) -> Option<Mirror> {
162        if self.notes == Mirror::TimedOut || self.inputs == Mirror::TimedOut {
163            Some(Mirror::TimedOut)
164        } else if self.notes == Mirror::Unreachable && self.inputs == Mirror::Unreachable {
165            Some(Mirror::Unreachable)
166        } else {
167            None
168        }
169    }
170}
171
172/// [`sync_mirrors`] for the name set's two refs. A ref origin does not have
173/// (before a repository's first greensummit note) is `Deleted`, which judges nothing and
174/// changes no verdict, never `Unreachable`.
175pub fn sync_mirrors_of(root: &Path, names: &Names) -> Synced {
176    // Every line this sync has to say goes into `loud`, returned with the
177    // mirrors: the helpers below borrow it, nothing outside does.
178    let mut loud = Vec::new();
179    if !git::succeeds_in(root, &["remote", "get-url", "origin"]) {
180        return Synced {
181            notes: Mirror::NoOrigin,
182            inputs: Mirror::NoOrigin,
183            loud,
184        };
185    }
186    sweep_tmp_refs(root);
187    let pid = std::process::id();
188    let full = |r: &str| format!("refs/notes/{r}");
189    let tmp = |r: &str| format!("{TMP_NS}{pid}/{r}");
190    let spec = |r: &str| format!("+{}:{}", full(r), tmp(r));
191    // Our own throwaways, and any lock a dead run with our pid left on them.
192    // Known limits: a remove that fails leaves the fetch to fail and read as
193    // unreachable (safe: nothing judged); a killed fetch's lock with no ref
194    // beside it is not swept, only replaced when its pid comes round again.
195    for r in [names.notes_ref, names.inputs_ref] {
196        let _ = git::succeeds_in(root, &["update-ref", "-d", &tmp(r)]);
197        if let Some(lock) = git::stdout_in(
198            root,
199            &["rev-parse", "--git-path", &format!("{}.lock", tmp(r))],
200        ) {
201            // `--git-path` answers relative to where git ran.
202            let _ = std::fs::remove_file(root.join(lock));
203        }
204    }
205    let old_main = git::stdout_in(
206        root,
207        &["rev-parse", "--verify", "--quiet", &full(names.notes_ref)],
208    );
209    let old_inputs = git::stdout_in(
210        root,
211        &["rev-parse", "--verify", "--quiet", &full(names.inputs_ref)],
212    );
213    let adopt_both = || {
214        (
215            adopt(
216                root,
217                names.notes_ref,
218                &tmp(names.notes_ref),
219                old_main.as_deref(),
220            ),
221            adopt(
222                root,
223                names.inputs_ref,
224                &tmp(names.inputs_ref),
225                old_inputs.as_deref(),
226            ),
227        )
228    };
229    let states = match git::remote(
230        root,
231        &[
232            "fetch",
233            "--quiet",
234            "origin",
235            &spec(names.notes_ref),
236            &spec(names.inputs_ref),
237        ],
238    ) {
239        git::Remote::Done(0, _) => adopt_both(),
240        // Origin did not answer; asking again would only double the wait.
241        git::Remote::TimedOut => (Mirror::TimedOut, Mirror::TimedOut),
242        _ => match git::remote(
243            root,
244            &[
245                "ls-remote",
246                "--exit-code",
247                "origin",
248                &full(names.notes_ref),
249                &full(names.inputs_ref),
250            ],
251        ) {
252            git::Remote::Done(0, listing) => {
253                let listed = |r: &str| {
254                    let f = full(r);
255                    listing
256                        .lines()
257                        .any(|l| l.split_whitespace().nth(1) == Some(f.as_str()))
258                };
259                let (has_main, has_inputs) = (listed(names.notes_ref), listed(names.inputs_ref));
260                let mut want = Vec::new();
261                if has_main {
262                    want.push(spec(names.notes_ref));
263                }
264                if has_inputs {
265                    want.push(spec(names.inputs_ref));
266                }
267                let fetched = if want.is_empty() {
268                    None
269                } else {
270                    let mut args = vec!["fetch", "--quiet", "origin"];
271                    args.extend(want.iter().map(String::as_str));
272                    Some(git::remote(root, &args))
273                };
274                let one = |present: bool, r: &str, old: Option<&str>, loud: &mut Vec<String>| {
275                    if !present {
276                        return drop_mirror(root, loud, r);
277                    }
278                    match &fetched {
279                        Some(git::Remote::Done(0, _)) => adopt(root, r, &tmp(r), old),
280                        Some(git::Remote::TimedOut) => Mirror::TimedOut,
281                        _ => Mirror::Unreachable,
282                    }
283                };
284                let notes_mirror = one(has_main, names.notes_ref, old_main.as_deref(), &mut loud);
285                let inputs_mirror = one(
286                    has_inputs,
287                    names.inputs_ref,
288                    old_inputs.as_deref(),
289                    &mut loud,
290                );
291                (notes_mirror, inputs_mirror)
292            }
293            git::Remote::Done(2, _) => (
294                drop_mirror(root, &mut loud, names.notes_ref),
295                drop_mirror(root, &mut loud, names.inputs_ref),
296            ),
297            git::Remote::TimedOut => (Mirror::TimedOut, Mirror::TimedOut),
298            _ => (Mirror::Unreachable, Mirror::Unreachable),
299        },
300    };
301    for r in [names.notes_ref, names.inputs_ref] {
302        let _ = git::succeeds_in(root, &["update-ref", "-d", &tmp(r)]);
303    }
304    let (notes, inputs) = states;
305    Synced {
306        notes,
307        inputs,
308        loud,
309    }
310}
311
312// ---------------------------------------------------------------------------
313// Publishing (SPEC.md, "Producing")
314// ---------------------------------------------------------------------------
315
316/// How a publish is carried out. Every producer and every signed-notes ref
317/// (attestations, their inputs, provenance) goes through the same loop.
318pub struct Publish<'a> {
319    /// The remote to publish to.
320    pub remote: &'a str,
321    /// How many fetch-append-push rounds before a lost race is given up.
322    pub attempts: u32,
323    /// Wait between rounds, growing with the attempt (`sign.sh` in CI); a
324    /// hook on the commit path does not wait.
325    pub pause: bool,
326    /// The committer of the notes commit, for a runner with no identity of
327    /// its own; `None` uses the repository's.
328    pub identity: Option<(&'a str, &'a str)>,
329    /// Extra environment for the push itself (amont marks its own notes push
330    /// so its pre-push hook yields).
331    pub push_env: &'a [(&'a str, &'a str)],
332}
333
334/// What a publish came to.
335#[derive(Debug, Clone, PartialEq, Eq)]
336#[non_exhaustive]
337pub enum Published {
338    /// The remote now holds every block.
339    Pushed,
340    /// Every block was already there: nothing was pushed.
341    AlreadyPresent,
342    /// Written to the local ref only (see [`publish_local`]).
343    Local,
344    /// The push failed, after retries if the failure was a lost race.
345    PushFailed,
346    /// A note could not be written at all.
347    Error,
348}
349
350/// Why a push that exited non-zero failed, read from git's stderr.
351///
352/// A lost race is worth one more fetch-and-try; an unreachable remote says
353/// nothing about the push itself; everything else is a refusal to report
354/// verbatim. An unrecognised message is `Refused`, the direction that never
355/// claims a push was merely unlucky.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357#[non_exhaustive]
358pub enum PushFailure {
359    Raced,
360    Unreachable,
361    Refused,
362}
363
364/// The markers behind [`PushFailure`]. Raced wins over Unreachable: a
365/// message naming both is a race that happened on a reachable remote. A
366/// hook's own output rides the same stream, so Unreachable is read only from
367/// the lines git and ssh themselves print.
368pub fn classify_push(stderr: &str) -> PushFailure {
369    const RACED: [&str; 5] = [
370        "non-fast-forward",
371        "fetch first",
372        "stale info",
373        "cannot lock ref",
374        "failed to lock",
375    ];
376    const UNREACHABLE: [&str; 5] = [
377        "Could not resolve host",
378        "Connection refused",
379        "Connection timed out",
380        "unable to access",
381        "Could not read from remote repository",
382    ];
383    let own = |l: &&str| {
384        let l = l.trim_start();
385        l.starts_with("fatal:") || l.starts_with("ssh:") || l.starts_with("error:")
386    };
387    if RACED.iter().any(|m| stderr.contains(m)) {
388        PushFailure::Raced
389    } else if stderr
390        .lines()
391        .filter(own)
392        .any(|l| UNREACHABLE.iter().any(|m| l.contains(m)))
393    {
394        PushFailure::Unreachable
395    } else {
396        PushFailure::Refused
397    }
398}
399
400/// `git notes` writes a commit on the notes ref, and needs an identity.
401fn notes_git(root: &Path, identity: Option<(&str, &str)>) -> Command {
402    let mut cmd = Command::new("git");
403    cmd.current_dir(root).stdin(Stdio::null());
404    if let Some((name, email)) = identity {
405        cmd.args([
406            "-c",
407            &format!("user.name={name}"),
408            "-c",
409            &format!("user.email={email}"),
410        ]);
411    }
412    cmd
413}
414
415/// Append `block` to the note on `object` in `notes_ref`, unless that exact
416/// block is already there. `Some(true)` when it appended, `Some(false)` when
417/// the block was present, `None` when the note could not be written.
418fn append(
419    root: &Path,
420    identity: Option<(&str, &str)>,
421    notes_ref: &str,
422    object: &str,
423    block: &str,
424) -> Option<bool> {
425    let existing =
426        git::stdout_in(root, &["notes", "--ref", notes_ref, "show", object]).unwrap_or_default();
427    if existing.contains(block.trim_end()) {
428        return Some(false);
429    }
430    notes_git(root, identity)
431        .args(["notes", "--ref", notes_ref, "append", "-m", block, object])
432        .stdout(Stdio::null())
433        .stderr(Stdio::null())
434        .status()
435        .ok()?
436        .success()
437        .then_some(true)
438}
439
440/// Attach each `(object, block)` on the REMOTE's copy of `notes_ref` (short
441/// name, under `refs/notes/`) and push. Never `notes add -f`, which erases
442/// every other producer's block, and never a push of the local ref, which
443/// would re-publish a block origin revoked:
444///
445/// 1. fetch the remote's ref into a temporary ref;
446/// 2. append each block that is not already there (ed25519 signatures are
447///    deterministic, so a re-run produces the same bytes);
448/// 3. push the temporary ref; a lost race goes back to 1.
449///
450/// After a push to `origin` the local ref is set to what was published;
451/// another remote's content never enters it. The temporary ref is removed on
452/// every path. `log` gets one line per retry or refusal, credentials in a
453/// remote URL removed.
454pub fn publish(
455    root: &Path,
456    how: &Publish,
457    notes_ref: &str,
458    items: &[(String, String)],
459    log: &mut Vec<String>,
460) -> Published {
461    let full = format!("refs/notes/{notes_ref}");
462    let tref = format!("greensummit-publish-{}-{notes_ref}", std::process::id());
463    let tfull = format!("refs/notes/{tref}");
464    let mut attempt = 0;
465    let outcome = loop {
466        attempt += 1;
467        let _ = git::succeeds_in(root, &["update-ref", "-d", &tfull]);
468        // A remote with no such ref yet fails the fetch, harmlessly: append
469        // then creates the note from nothing.
470        let _ = git::succeeds_in(
471            root,
472            &["fetch", "--quiet", how.remote, &format!("+{full}:{tfull}")],
473        );
474        let mut appended = false;
475        for (object, block) in items {
476            match append(root, how.identity, &tref, object, block) {
477                Some(true) => appended = true,
478                Some(false) => {}
479                None => return cleanup(root, &tfull, Published::Error),
480            }
481        }
482        if !appended {
483            break Published::AlreadyPresent;
484        }
485        let out = Command::new("git")
486            .current_dir(root)
487            .args(["push", "--quiet", how.remote, &format!("{tfull}:{full}")])
488            .envs(how.push_env.iter().copied())
489            .stdin(Stdio::null())
490            .stdout(Stdio::null())
491            .output();
492        let Ok(out) = out else {
493            log.push(format!("push of {full} could not run git"));
494            break Published::PushFailed;
495        };
496        if out.status.success() {
497            if how.remote == "origin" {
498                let _ = git::succeeds_in(root, &["update-ref", &full, &tfull]);
499            }
500            break Published::Pushed;
501        }
502        let why = scrub(&String::from_utf8_lossy(&out.stderr));
503        match classify_push(&why) {
504            PushFailure::Raced if attempt < how.attempts => {
505                log.push(format!(
506                    "push of {full} rejected, another job attested this tree meanwhile; retrying"
507                ));
508                if how.pause {
509                    std::thread::sleep(std::time::Duration::from_secs(
510                        u64::from(attempt) + u64::from(std::process::id() % 3),
511                    ));
512                }
513            }
514            PushFailure::Raced => {
515                log.push(format!("gave up on {full} after {attempt} attempts: {why}"));
516                break Published::PushFailed;
517            }
518            _ => {
519                log.push(format!("push of {full} refused: {why}"));
520                break Published::PushFailed;
521            }
522        }
523    };
524    cleanup(root, &tfull, outcome)
525}
526
527fn cleanup(root: &Path, tfull: &str, outcome: Published) -> Published {
528    let _ = git::succeeds_in(root, &["update-ref", "-d", tfull]);
529    outcome
530}
531
532/// git's stderr on one line, with any `user:token@` in a remote URL removed.
533pub(crate) fn scrub(stderr: &str) -> String {
534    let mut out = String::new();
535    for word in stderr.split_whitespace() {
536        if !out.is_empty() {
537            out.push(' ');
538        }
539        match word.find("://") {
540            Some(i) => {
541                let (scheme, rest) = word.split_at(i + 3);
542                let host_start = match rest.find('/') {
543                    Some(slash) => rest[..slash].rfind('@').map(|a| a + 1).unwrap_or(0),
544                    None => rest.rfind('@').map(|a| a + 1).unwrap_or(0),
545                };
546                out.push_str(scheme);
547                out.push_str(&rest[host_start..]);
548            }
549            None => out.push_str(word),
550        }
551    }
552    out
553}
554
555/// The same, into the local `notes_ref` only, with no remote involved: what
556/// `sign --no-push` writes under `refs/notes/greensummit-local/`.
557pub fn publish_local(
558    root: &Path,
559    identity: Option<(&str, &str)>,
560    notes_ref: &str,
561    items: &[(String, String)],
562) -> Published {
563    let mut appended = false;
564    for (object, block) in items {
565        match append(root, identity, notes_ref, object, block) {
566            Some(true) => appended = true,
567            Some(false) => {}
568            None => return Published::Error,
569        }
570    }
571    if appended {
572        Published::Local
573    } else {
574        Published::AlreadyPresent
575    }
576}