Skip to main content

surjection_core/sources/
detect.rs

1//! Changes to a repository that make trust lapse (#24): its followed branch
2//! was rewritten (force-push), or it was renamed or transferred (the host
3//! redirects). Callers fetch with the system git and hand its output here.
4
5use std::ffi::OsStr;
6use std::time::{Duration, UNIX_EPOCH};
7
8use crate::error::{CoreError, ErrorCode};
9use crate::model::sources::LapseReason;
10use crate::remote::git::RunOutput;
11use crate::store::utc_datetime;
12
13use super::SourceRef;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum SourceChangeKind {
17    /// The commit installed last is no longer in the followed branch.
18    HistoryRewritten,
19    /// The repository answers from another location.
20    Moved,
21}
22
23impl SourceChangeKind {
24    pub const fn as_str(self) -> &'static str {
25        self.reason().as_str()
26    }
27
28    pub const fn reason(self) -> LapseReason {
29        match self {
30            SourceChangeKind::HistoryRewritten => LapseReason::HistoryRewritten,
31            SourceChangeKind::Moved => LapseReason::Moved,
32        }
33    }
34}
35
36/// What changed about a source since it was last fetched.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct SourceChange {
39    pub kind: SourceChangeKind,
40    /// [`SourceChangeKind::Moved`]: the key of the new location.
41    pub detail: Option<String>,
42}
43
44/// What git prints, with `LC_ALL=C` and without `--quiet`, when an HTTP
45/// host redirects a repository (`remote-curl.c`).
46const REDIRECT_WARNING: &str = "warning: redirecting to ";
47
48/// The URL in git's `warning: redirecting to <url>` (an HTTP redirect of a
49/// renamed or transferred repository), if `stderr` of a clone or fetch of
50/// `url` has one. Only an `http(s)://` URL can redirect, and only a line
51/// that starts with the warning counts: the remote's own messages
52/// (`remote: ...`, or an SSH server's stderr) never do.
53pub fn redirect_target(url: &str, stderr: &str) -> Option<String> {
54    let scheme = url.split_once("://")?.0;
55    if !scheme.eq_ignore_ascii_case("https") && !scheme.eq_ignore_ascii_case("http") {
56        return None;
57    }
58    stderr.lines().find_map(|line| {
59        let rest = line.strip_prefix(REDIRECT_WARNING)?;
60        let url = rest.trim().trim_end_matches('/');
61        let url = url.strip_suffix("/info/refs").unwrap_or(url);
62        (!url.is_empty()).then(|| url.to_owned())
63    })
64}
65
66/// The repository `redirect` (a [`redirect_target`]) names, when its key
67/// differs from `source`'s: the repository moved.
68pub fn target_of(source: &SourceRef, redirect: &str) -> Option<SourceRef> {
69    SourceRef::from_git_url(redirect)
70        .ok()
71        .filter(|target| target.key() != source.key())
72}
73
74/// [`SourceChangeKind::Moved`] to `target` (a [`target_of`]).
75pub fn moved_to(target: &SourceRef) -> SourceChange {
76    SourceChange {
77        kind: SourceChangeKind::Moved,
78        detail: Some(target.key().to_owned()),
79    }
80}
81
82/// [`SourceChangeKind::Moved`] when git's output of a clone or fetch of
83/// `source` shows a redirect to another repository key than `source`'s.
84pub fn moved(source: &SourceRef, output: &RunOutput) -> Option<SourceChange> {
85    let redirect = redirect_target(source.url(), &output.stderr)?;
86    target_of(source, &redirect).map(|target| moved_to(&target))
87}
88
89/// Git in one repository (a cache clone): runs `args`, returns the output.
90pub type GitIn<'a> = dyn Fn(&[&OsStr]) -> Result<RunOutput, CoreError> + 'a;
91
92/// Margin below the old commit's date when deepening a shallow clone, for
93/// clock skew between the commits in between.
94const SHALLOW_MARGIN: Duration = Duration::from_secs(86_400);
95
96fn run_ok(git: &GitIn<'_>, args: &[&str]) -> Result<RunOutput, CoreError> {
97    let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
98    git(&args)
99}
100
101/// Whether `new` (just fetched from `url`, following `git_ref` or the
102/// default branch) no longer contains `old`, the commit installed last:
103/// the branch was rewritten. A shallow clone is deepened first (to the old
104/// commit's date, or completely when the old commit is not in it), so a
105/// fast-forward is never mistaken for a rewrite; anything not proven a
106/// fast-forward is a rewrite. A deepening fetch that fails while the
107/// source answers (`git ls-remote`) is a rewrite too: the branch was
108/// rolled back to a commit older than the deepening date. One that fails
109/// because the source does not answer is `source_unreachable`.
110pub fn history_rewritten(
111    git: &GitIn<'_>,
112    url: &str,
113    git_ref: Option<&str>,
114    old: &str,
115    new: &str,
116) -> Result<bool, CoreError> {
117    if old.eq_ignore_ascii_case(new) {
118        return Ok(false);
119    }
120    let hex =
121        |text: &str| (4..=64).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_hexdigit());
122    if !hex(old) || !hex(new) {
123        // Not a commit id git can be asked about (a hand-edited record).
124        return Ok(true);
125    }
126    let shallow = run_ok(git, &["rev-parse", "--is-shallow-repository"])?;
127    if shallow.success && shallow.stdout.trim() == "true" {
128        let date = run_ok(
129            git,
130            &["show", "-s", "--format=%ct", &format!("{old}^{{commit}}")],
131        )?;
132        let seconds = date
133            .success
134            .then(|| date.stdout.trim().parse::<u64>().ok())
135            .flatten();
136        let deepen = match seconds {
137            Some(seconds) => {
138                let since = (UNIX_EPOCH + Duration::from_secs(seconds))
139                    .checked_sub(SHALLOW_MARGIN)
140                    .unwrap_or(UNIX_EPOCH);
141                format!("--shallow-since={}", utc_datetime(since))
142            }
143            None => "--unshallow".to_owned(),
144        };
145        let mut args = vec!["fetch", "--quiet", &deepen, "--", url];
146        if let Some(git_ref) = git_ref {
147            args.push(git_ref);
148        }
149        let output = run_ok(git, &args)?;
150        if !output.success {
151            let answers = run_ok(git, &["ls-remote", "--quiet", "--", url])?;
152            if answers.success {
153                return Ok(true);
154            }
155            let shown = SourceRef::from_git_url(url).map_or_else(
156                |_| "of this skill".to_owned(),
157                |source| source.url().to_owned(),
158            );
159            return Err(CoreError::new(
160                ErrorCode::SourceUnreachable,
161                SourceRef::redact_userinfo(&format!(
162                    "the source {shown} cannot be reached to check its history: {}",
163                    output
164                        .stderr
165                        .lines()
166                        .rev()
167                        .find(|line| !line.trim().is_empty())
168                        .unwrap_or("git failed")
169                        .trim()
170                )),
171            ));
172        }
173    }
174    let ancestor = run_ok(git, &["merge-base", "--is-ancestor", old, new])?;
175    Ok(!ancestor.success)
176}