Skip to main content

adk_website/repository/
source.rs

1//! Reading a pushed commit's files (spec 3.5 §7.8.2 "Files and git"): the [`CommitSource`]
2//! trait, a local git repository ([`LocalGitSource`]) and a forge's raw-file endpoint over
3//! HTTP ([`HttpCommitSource`]). No forge SDK: the local source runs the `git` program, the
4//! HTTP source fills a URL template the owner writes for their forge.
5//!
6//! | Source | Reads | Lists a push's changes |
7//! |---|---|---|
8//! | [`LocalGitSource`] | `git cat-file` in a repository on this machine, fetching from a remote first when the commit is missing | `git diff --name-status` between the push's two commits |
9//! | [`HttpCommitSource`] | `GET` on a URL template such as `https://raw.githubusercontent.com/{repository}/{commit}/{path}` | No: the push's own lists |
10//!
11//! Every source refuses a commit id that is not 40 or 64 hexadecimal digits and a path that
12//! is absolute, climbs with `..` or is longer than 1,024 bytes, and reads at most
13//! [`MAX_FILE_BYTES`] of one file. Implementations run [`commit_source_conformance`].
14
15use std::path::{Path, PathBuf};
16use std::time::Duration;
17
18use adk_core::{AdkError, CredentialSecret, Result};
19use async_trait::async_trait;
20use bytes::Bytes;
21use serde::{Deserialize, Serialize};
22
23/// The most bytes read of one file.
24pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
25
26/// How long one `git` command or HTTP request may take.
27const TIMEOUT: Duration = Duration::from_secs(60);
28
29fn refused(message: impl Into<String>) -> AdkError {
30    AdkError::config(message.into())
31}
32
33/// One file a push changes.
34#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct FileChange {
37    /// The path, relative to the repository root.
38    pub path: String,
39    /// Whether the push removes it.
40    pub removed: bool,
41}
42
43/// Whether `id` is a full commit id: 40 (SHA-1) or 64 (SHA-256) hexadecimal digits.
44///
45/// # Example
46///
47/// ```rust
48/// use adk_website::repository::source::is_commit_id;
49///
50/// assert!(is_commit_id(&"a".repeat(40)));
51/// assert!(!is_commit_id("HEAD") && !is_commit_id("--upload-pack=x"));
52/// ```
53pub fn is_commit_id(id: &str) -> bool {
54    matches!(id.len(), 40 | 64) && id.bytes().all(|b| b.is_ascii_hexdigit())
55}
56
57/// Refuses a commit id or path a source must not read.
58fn checked<'a>(commit: &str, path: &'a str) -> Result<&'a str> {
59    if !is_commit_id(commit) {
60        return Err(refused(format!("`{commit}` is not a full commit id")));
61    }
62    let bad = path.is_empty()
63        || path.len() > 1024
64        || path.starts_with('/')
65        || path.starts_with('-')
66        || path.contains('\\')
67        || path.contains('\0')
68        || path.split('/').any(|part| part.is_empty() || part == "." || part == "..");
69    if bad {
70        return Err(refused(format!("`{path}` is not a relative path in the repository")));
71    }
72    Ok(path)
73}
74
75/// Reads files from a pushed commit (spec 3.5 §7.8.2 "Files and git").
76#[async_trait]
77pub trait CommitSource: Send + Sync {
78    /// The source's name, for logs.
79    fn name(&self) -> &str;
80
81    /// The file at `path` in `commit` of `repository`; `None` when the commit holds no such
82    /// file.
83    ///
84    /// # Errors
85    ///
86    /// A commit id or path the source refuses, a file over [`MAX_FILE_BYTES`], or a source
87    /// that cannot be read, such as a commit the repository does not have.
88    async fn read(&self, repository: &str, commit: &str, path: &str) -> Result<Option<Bytes>>;
89
90    /// The files `commit` changes against `before`, when the source can list them; `None`
91    /// leaves the push's own lists, which a forge may cut short.
92    ///
93    /// # Errors
94    ///
95    /// As [`read`](Self::read).
96    async fn changes(
97        &self,
98        _repository: &str,
99        _before: Option<&str>,
100        _commit: &str,
101    ) -> Result<Option<Vec<FileChange>>> {
102        Ok(None)
103    }
104}
105
106/// The checks every [`CommitSource`] passes: `present` reads back as its bytes from
107/// `commit`, `absent` reads as `None`, and a short commit id and a climbing path are refused.
108///
109/// # Panics
110///
111/// When the source fails a check.
112pub async fn commit_source_conformance(
113    source: &dyn CommitSource,
114    repository: &str,
115    commit: &str,
116    present: (&str, &[u8]),
117    absent: &str,
118) {
119    let (path, bytes) = present;
120    let read = source.read(repository, commit, path).await.expect("a present file reads");
121    assert_eq!(read.as_deref(), Some(bytes), "{} reads {path} at {commit}", source.name());
122    let missing = source.read(repository, commit, absent).await.expect("an absent file reads");
123    assert_eq!(missing, None, "{} reads {absent} as absent", source.name());
124    assert!(source.read(repository, &commit[..7], path).await.is_err(), "a short id is refused");
125    assert!(source.read(repository, "HEAD", path).await.is_err(), "a ref name is refused");
126    assert!(
127        source.read(repository, commit, "../site.toml").await.is_err(),
128        "a climbing path is refused"
129    );
130    assert!(source.read(repository, commit, "/etc/passwd").await.is_err(), "an absolute path");
131}
132
133/// A git repository on this machine, read with the `git` program: the content repository
134/// itself, or a mirror of the forge's (spec 3.5 §7.8.2).
135///
136/// # Example
137///
138/// ```rust
139/// use adk_website::repository::source::{CommitSource, LocalGitSource};
140///
141/// let source = LocalGitSource::new("/srv/site-content.git").with_fetch("origin");
142/// assert_eq!(source.name(), "git");
143/// ```
144#[derive(Debug, Clone)]
145pub struct LocalGitSource {
146    dir: PathBuf,
147    fetch: Option<String>,
148}
149
150impl LocalGitSource {
151    /// The repository at `dir`, a working copy or a bare repository.
152    pub fn new(dir: impl Into<PathBuf>) -> Self {
153        Self { dir: dir.into(), fetch: None }
154    }
155
156    /// Fetches from `remote` before reading a commit the repository does not have yet.
157    #[must_use]
158    pub fn with_fetch(mut self, remote: impl Into<String>) -> Self {
159        self.fetch = Some(remote.into());
160        self
161    }
162
163    /// The repository's directory.
164    pub fn dir(&self) -> &Path {
165        &self.dir
166    }
167
168    async fn git(&self, args: &[&str]) -> Result<std::process::Output> {
169        let mut command = tokio::process::Command::new("git");
170        command
171            .arg("-C")
172            .arg(&self.dir)
173            .args(args)
174            .env("GIT_TERMINAL_PROMPT", "0")
175            .stdin(std::process::Stdio::null())
176            .kill_on_drop(true);
177        tokio::time::timeout(TIMEOUT, command.output())
178            .await
179            .map_err(|_| refused(format!("git {} timed out", args.first().unwrap_or(&""))))?
180            .map_err(|e| refused(format!("cannot run git in {}: {e}", self.dir.display())))
181    }
182
183    async fn has_commit(&self, commit: &str) -> Result<bool> {
184        Ok(self.git(&["cat-file", "-e", &format!("{commit}^{{commit}}")]).await?.status.success())
185    }
186
187    /// Makes sure `commit` is in the repository, fetching once when a remote is set.
188    async fn ensure(&self, commit: &str) -> Result<()> {
189        if self.has_commit(commit).await? {
190            return Ok(());
191        }
192        if let Some(remote) = &self.fetch {
193            let fetched = self.git(&["fetch", "--quiet", "--no-tags", "--", remote]).await?;
194            if !fetched.status.success() {
195                tracing::warn!(repository.remote = %remote, "git fetch failed");
196            }
197            if self.has_commit(commit).await? {
198                return Ok(());
199            }
200        }
201        Err(refused(format!("the repository in {} has no commit {commit}", self.dir.display())))
202    }
203}
204
205#[async_trait]
206impl CommitSource for LocalGitSource {
207    fn name(&self) -> &str {
208        "git"
209    }
210
211    async fn read(&self, _repository: &str, commit: &str, path: &str) -> Result<Option<Bytes>> {
212        let path = checked(commit, path)?;
213        self.ensure(commit).await?;
214        let listed = self.git(&["ls-tree", "--name-only", commit, "--", path]).await?;
215        if !listed.status.success() || listed.stdout.is_empty() {
216            return Ok(None);
217        }
218        let object = format!("{commit}:{path}");
219        let size = self.git(&["cat-file", "-s", &object]).await?;
220        let size: usize = String::from_utf8_lossy(&size.stdout).trim().parse().unwrap_or(0);
221        if size > MAX_FILE_BYTES {
222            return Err(refused(format!("{path} is {size} bytes, over {MAX_FILE_BYTES}")));
223        }
224        let blob = self.git(&["cat-file", "blob", &object]).await?;
225        if !blob.status.success() {
226            // A path that names a directory or a submodule is not a file.
227            return Ok(None);
228        }
229        Ok(Some(Bytes::from(blob.stdout)))
230    }
231
232    async fn changes(
233        &self,
234        _repository: &str,
235        before: Option<&str>,
236        commit: &str,
237    ) -> Result<Option<Vec<FileChange>>> {
238        let Some(before) = before.filter(|before| is_commit_id(before)) else { return Ok(None) };
239        if !is_commit_id(commit) {
240            return Err(refused(format!("`{commit}` is not a full commit id")));
241        }
242        self.ensure(commit).await?;
243        if !self.has_commit(before).await? {
244            return Ok(None);
245        }
246        let diff =
247            self.git(&["diff", "--name-status", "--no-renames", "-z", before, commit]).await?;
248        if !diff.status.success() {
249            return Ok(None);
250        }
251        let text = String::from_utf8_lossy(&diff.stdout);
252        let mut fields = text.split('\0').filter(|field| !field.is_empty());
253        let mut changes = Vec::new();
254        while let (Some(status), Some(path)) = (fields.next(), fields.next()) {
255            changes.push(FileChange { path: path.to_string(), removed: status.starts_with('D') });
256        }
257        Ok(Some(changes))
258    }
259}
260
261/// Escapes `text` for a URL: every byte but the unreserved ones, and `/` when `keep_slash`.
262fn escape(text: &str, keep_slash: bool) -> String {
263    let mut out = String::with_capacity(text.len());
264    for byte in text.bytes() {
265        if byte.is_ascii_alphanumeric()
266            || matches!(byte, b'-' | b'.' | b'_' | b'~')
267            || (keep_slash && byte == b'/')
268        {
269            out.push(char::from(byte));
270        } else {
271            out.push_str(&format!("%{byte:02X}"));
272        }
273    }
274    out
275}
276
277/// A forge's raw-file endpoint over HTTP (spec 3.5 §7.8.2): `GET` on a URL template, `404`
278/// for a file the commit does not hold.
279///
280/// | Placeholder | Becomes |
281/// |---|---|
282/// | `{repository}`, `{path}` | The repository's and the file's names, `/` kept |
283/// | `{repository_escaped}`, `{path_escaped}` | The same with `/` escaped, for APIs that take one path segment |
284/// | `{commit}` | The full commit id |
285///
286/// | Forge | Template |
287/// |---|---|
288/// | GitHub | `https://raw.githubusercontent.com/{repository}/{commit}/{path}` |
289/// | GitLab | `https://gitlab.com/api/v4/projects/{repository_escaped}/repository/files/{path_escaped}/raw?ref={commit}` |
290///
291/// Redirects are not followed, so a credential never reaches another host.
292///
293/// # Example
294///
295/// ```rust
296/// use adk_website::repository::source::{CommitSource, HttpCommitSource};
297///
298/// let source = HttpCommitSource::new("https://raw.githubusercontent.com/{repository}/{commit}/{path}")?;
299/// let url = source.url("juniper/site", &"a".repeat(40), "content/pages/hours/en.md")?;
300/// assert!(url.ends_with("/juniper/site/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/content/pages/hours/en.md"));
301/// # Ok::<(), adk_core::AdkError>(())
302/// ```
303#[derive(Clone)]
304pub struct HttpCommitSource {
305    template: String,
306    auth: Option<(reqwest::header::HeaderName, CredentialSecret)>,
307    client: reqwest::Client,
308}
309
310impl std::fmt::Debug for HttpCommitSource {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        f.debug_struct("HttpCommitSource")
313            .field("template", &self.template)
314            .field("auth", &self.auth.as_ref().map(|(header, _)| header.as_str()))
315            .finish_non_exhaustive()
316    }
317}
318
319impl HttpCommitSource {
320    /// A source reading `template`, which names `{commit}` and `{path}` (or `{path_escaped}`).
321    ///
322    /// # Errors
323    ///
324    /// A template without those placeholders, or not an `http` or `https` URL.
325    pub fn new(template: impl Into<String>) -> Result<Self> {
326        let template = template.into();
327        let names_path = template.contains("{path}") || template.contains("{path_escaped}");
328        if !names_path || !template.contains("{commit}") {
329            return Err(refused(format!(
330                "the source URL `{template}` must name {{commit}} and {{path}} (or {{path_escaped}})"
331            )));
332        }
333        if !(template.starts_with("https://") || template.starts_with("http://")) {
334            return Err(refused(format!("the source URL `{template}` is not http or https")));
335        }
336        let client = reqwest::Client::builder()
337            .redirect(reqwest::redirect::Policy::none())
338            .timeout(TIMEOUT)
339            .build()
340            .map_err(|e| refused(e.to_string()))?;
341        Ok(Self { template, auth: None, client })
342    }
343
344    /// Sends `value` in `header` with every request, such as `Authorization` or GitLab's
345    /// `PRIVATE-TOKEN`.
346    ///
347    /// # Errors
348    ///
349    /// A header name that is not valid.
350    pub fn with_auth(mut self, header: &str, value: CredentialSecret) -> Result<Self> {
351        let header = reqwest::header::HeaderName::from_bytes(header.as_bytes())
352            .map_err(|e| refused(format!("`{header}` is not a header name: {e}")))?;
353        self.auth = Some((header, value));
354        Ok(self)
355    }
356
357    /// The URL a file is read from.
358    ///
359    /// # Errors
360    ///
361    /// A commit id or path the source refuses.
362    pub fn url(&self, repository: &str, commit: &str, path: &str) -> Result<String> {
363        let path = checked(commit, path)?;
364        if repository.split('/').any(|part| part == "..") {
365            return Err(refused(format!("`{repository}` is not a repository name")));
366        }
367        Ok(self
368            .template
369            .replace("{repository_escaped}", &escape(repository, false))
370            .replace("{repository}", &escape(repository, true))
371            .replace("{path_escaped}", &escape(path, false))
372            .replace("{path}", &escape(path, true))
373            .replace("{commit}", commit))
374    }
375}
376
377#[async_trait]
378impl CommitSource for HttpCommitSource {
379    fn name(&self) -> &str {
380        "http"
381    }
382
383    async fn read(&self, repository: &str, commit: &str, path: &str) -> Result<Option<Bytes>> {
384        let url = self.url(repository, commit, path)?;
385        let mut request = self.client.get(&url);
386        if let Some((header, value)) = &self.auth {
387            let mut value = reqwest::header::HeaderValue::from_str(value.expose())
388                .map_err(|_| refused("the source's credential is not a header value"))?;
389            value.set_sensitive(true);
390            request = request.header(header.clone(), value);
391        }
392        let mut response = request
393            .send()
394            .await
395            .map_err(|e| refused(format!("cannot read {path} at {commit}: {e}")))?;
396        match response.status() {
397            status if status.is_success() => {}
398            reqwest::StatusCode::NOT_FOUND => return Ok(None),
399            status => {
400                return Err(refused(format!("reading {path} at {commit} answered {status}")));
401            }
402        }
403        if response.content_length().is_some_and(|len| len > MAX_FILE_BYTES as u64) {
404            return Err(refused(format!("{path} is over {MAX_FILE_BYTES} bytes")));
405        }
406        let mut body = Vec::new();
407        while let Some(chunk) =
408            response.chunk().await.map_err(|e| refused(format!("reading {path}: {e}")))?
409        {
410            if body.len() + chunk.len() > MAX_FILE_BYTES {
411                return Err(refused(format!("{path} is over {MAX_FILE_BYTES} bytes")));
412            }
413            body.extend_from_slice(&chunk);
414        }
415        Ok(Some(Bytes::from(body)))
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn templates_escape_names_for_each_forge() {
425        let commit = "0123456789abcdef0123456789abcdef01234567";
426        let gitlab = HttpCommitSource::new(
427            "https://gitlab.example/api/v4/projects/{repository_escaped}/repository/files/{path_escaped}/raw?ref={commit}",
428        )
429        .unwrap();
430        assert_eq!(
431            gitlab.url("news/site", commit, "content/articles/a b/en.md").unwrap(),
432            format!(
433                "https://gitlab.example/api/v4/projects/news%2Fsite/repository/files/content%2Farticles%2Fa%20b%2Fen.md/raw?ref={commit}"
434            )
435        );
436        assert!(gitlab.url("news/site", "main", "content/x/en.md").is_err());
437        assert!(gitlab.url("../site", commit, "content/x/en.md").is_err());
438        assert!(HttpCommitSource::new("https://example/{repository}/{path}").is_err());
439        assert!(HttpCommitSource::new("file:///{commit}/{path}").is_err());
440    }
441
442    #[test]
443    fn only_relative_paths_inside_the_repository_are_read() {
444        let commit = "a".repeat(64);
445        for path in ["content/pages/a/en.md", "README.md"] {
446            assert!(checked(&commit, path).is_ok(), "{path}");
447        }
448        for path in ["", "/etc/passwd", "../x", "content/../x", "a//b", "-c", "a\\b", "a/./b"] {
449            assert!(checked(&commit, path).is_err(), "{path}");
450        }
451    }
452}