1use 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
23pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
25
26const TIMEOUT: Duration = Duration::from_secs(60);
28
29fn refused(message: impl Into<String>) -> AdkError {
30 AdkError::config(message.into())
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct FileChange {
37 pub path: String,
39 pub removed: bool,
41}
42
43pub fn is_commit_id(id: &str) -> bool {
54 matches!(id.len(), 40 | 64) && id.bytes().all(|b| b.is_ascii_hexdigit())
55}
56
57fn 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#[async_trait]
77pub trait CommitSource: Send + Sync {
78 fn name(&self) -> &str;
80
81 async fn read(&self, repository: &str, commit: &str, path: &str) -> Result<Option<Bytes>>;
89
90 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
106pub 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#[derive(Debug, Clone)]
145pub struct LocalGitSource {
146 dir: PathBuf,
147 fetch: Option<String>,
148}
149
150impl LocalGitSource {
151 pub fn new(dir: impl Into<PathBuf>) -> Self {
153 Self { dir: dir.into(), fetch: None }
154 }
155
156 #[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 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 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 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
261fn 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#[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 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 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 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}