// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! The routes repository: a bare git repository driven through the `git` binary. //! //! Why the `git` binary (not git2 or gix): pushing to Gitea over HTTPS or SSH is required, //! and gix cannot push yet; git2 would bring libgit2 plus OpenSSL/libssh2 as C dependencies //! into the Nix build, while `git` is one store path Mark already uses, with the same //! behaviour he sees by hand. Control only uses plumbing with fixed arguments: commit ids are //! checked to be hex before they reach a command line, file content goes through stdin, the //! environment is cleared (no user or system git config, no hooks, no prompts), and objects //! and refs are fsync'ed so a crash cannot lose a commit edge already runs. //! //! Control never reads a working tree: trees are read from git objects, so symbolic links or //! files outside the repository cannot be smuggled in. A tree must have exactly the shape //! `ianitor_core::routes` allows. use std::collections::BTreeMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; use ianitor_core::routes::{self, EntryKind, SITE_FILE}; use ianitor_core::{MAX_FILE_BYTES, ValidationError}; #[derive(Debug, thiserror::Error)] pub enum RepoError { #[error("git {op} failed: {message}")] Git { op: String, message: String }, #[error("the routes repository has files that do not belong there")] Shape(Vec), #[error("{0} is not a commit in the routes history")] UnknownCommit(String), #[error("{0}")] Other(String), } /// A commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex digits. pub fn is_commit_id(s: &str) -> bool { (s.len() == 40 || s.len() == 64) && s.bytes() .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) } /// The files of one routes tree: path → content. Paths are exactly `ianitor.toml` and /// `hosts/.toml`. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RouteTree { pub files: BTreeMap, } impl RouteTree { pub fn site(&self) -> &str { self.files.get(SITE_FILE).map_or("", String::as_str) } pub fn host(&self, hostname: &str) -> Option<&str> { self.files .get(&routes::host_path(hostname)) .map(String::as_str) } pub fn hostnames(&self) -> Vec { self.files .keys() .filter_map(|p| p.strip_prefix("hosts/")?.strip_suffix(".toml")) .map(str::to_owned) .collect() } pub fn set_host(&mut self, hostname: &str, contents: String) { self.files.insert(routes::host_path(hostname), contents); } pub fn remove_host(&mut self, hostname: &str) -> bool { self.files.remove(&routes::host_path(hostname)).is_some() } /// Load and validate with core. pub fn model(&self) -> Result { let hosts: Vec = self .files .iter() .filter(|(p, _)| p.as_str() != SITE_FILE) .map(|(p, c)| ianitor_core::SourceFile { name: p, contents: c, }) .collect(); ianitor_core::load( &ianitor_core::SourceFile { name: SITE_FILE, contents: self.site(), }, &hosts, ) } } /// Facts about one commit. #[derive(Debug, Clone)] pub struct CommitInfo { pub id: String, pub parents: Vec, pub time: u64, pub subject: String, } pub struct Repo { git: PathBuf, dir: PathBuf, home: PathBuf, branch: String, cache: Mutex)>>, } fn null_device() -> &'static str { if cfg!(windows) { "NUL" } else { "/dev/null" } } impl Repo { /// Open (or create, with an empty `ianitor.toml`) the bare repository at `dir`. pub fn open(git: &Path, dir: &Path, home: &Path, branch: &str) -> Result { Repo::open_seeded(git, dir, home, branch, "") } /// Like [`Repo::open`]; a new repository starts with `site` as its `ianitor.toml`. pub fn open_seeded( git: &Path, dir: &Path, home: &Path, branch: &str, site: &str, ) -> Result { let repo = Repo { git: git.to_owned(), dir: dir.to_owned(), home: home.to_owned(), branch: branch.to_owned(), cache: Mutex::new(None), }; if !dir.join("HEAD").exists() { std::fs::create_dir_all(dir).map_err(|e| RepoError::Other(e.to_string()))?; repo.run_in( None, &[ "init", "--bare", "--quiet", &format!("--initial-branch={branch}"), ], Some(dir), None, &[], )?; } if repo.head()?.is_none() { let mut t = RouteTree::default(); t.files.insert(SITE_FILE.into(), site.to_owned()); let tree = repo.write_tree(&t, None)?; let c = repo.commit(&tree, &[], "Start the routes repository", "Ianitor control")?; repo.update_ref(&c, None)?; } Ok(repo) } pub fn dir(&self) -> &Path { &self.dir } fn command(&self) -> Command { let mut c = Command::new(&self.git); c.env_clear(); if let Some(p) = std::env::var_os("PATH") { c.env("PATH", p); } #[cfg(windows)] for v in ["SYSTEMROOT", "TEMP", "TMP"] { if let Some(x) = std::env::var_os(v) { c.env(v, x); } } c.env("HOME", &self.home) .env("LC_ALL", "C") .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_CONFIG_GLOBAL", null_device()) .env("GIT_TERMINAL_PROMPT", "0") .args([ "-c", &format!("core.hooksPath={}", null_device()), "-c", "core.fsync=all", "-c", "core.fsyncMethod=fsync", "-c", "protocol.file.allow=always", ]); c } fn run_in( &self, git_dir: Option<&Path>, args: &[&str], cwd: Option<&Path>, stdin: Option<&[u8]>, env: &[(&str, &str)], ) -> Result, RepoError> { let mut c = self.command(); if let Some(d) = git_dir { c.env("GIT_DIR", d); } if let Some(d) = cwd { c.current_dir(d); } for (k, v) in env { c.env(k, v); } c.args(args) .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let op = args.first().copied().unwrap_or("").to_owned(); let mut child = c.spawn().map_err(|e| RepoError::Git { op: op.clone(), message: format!("cannot run {}: {e}", self.git.display()), })?; if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) { si.write_all(data).map_err(|e| RepoError::Git { op: op.clone(), message: e.to_string(), })?; } let out = child.wait_with_output().map_err(|e| RepoError::Git { op: op.clone(), message: e.to_string(), })?; if !out.status.success() { return Err(RepoError::Git { op, message: String::from_utf8_lossy(&out.stderr) .trim() .chars() .take(500) .collect(), }); } Ok(out.stdout) } fn git(&self, args: &[&str], stdin: Option<&[u8]>) -> Result, RepoError> { self.run_in(Some(&self.dir), args, None, stdin, &[]) } fn git_str(&self, args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&self.git(args, None)?) .trim() .to_owned()) } fn reference(&self) -> String { format!("refs/heads/{}", self.branch) } /// The current commit of the branch. pub fn head(&self) -> Result, RepoError> { match self.git( &["rev-parse", "--verify", "--quiet", &self.reference()], None, ) { Ok(out) => { let s = String::from_utf8_lossy(&out).trim().to_owned(); Ok(is_commit_id(&s).then_some(s)) } Err(RepoError::Git { .. }) => Ok(None), Err(e) => Err(e), } } pub fn head_required(&self) -> Result { self.head()? .ok_or_else(|| RepoError::Other("the routes branch has no commit".into())) } /// Is `id` a commit reachable from the branch head? pub fn in_history(&self, id: &str) -> Result { if !is_commit_id(id) { return Ok(false); } let head = self.head_required()?; let mut c = self.command(); c.env("GIT_DIR", &self.dir) .args(["merge-base", "--is-ancestor", id, &head]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); let st = c.status().map_err(|e| RepoError::Git { op: "merge-base".into(), message: e.to_string(), })?; Ok(st.success()) } pub fn info(&self, id: &str) -> Result { if !is_commit_id(id) { return Err(RepoError::UnknownCommit(id.chars().take(64).collect())); } let out = self .git( &[ "show", "-s", "--format=%H%x00%P%x00%at%x00%s", "--end-of-options", id, ], None, ) .map_err(|_| RepoError::UnknownCommit(id.to_owned()))?; let text = String::from_utf8_lossy(&out); let mut f = text.trim_end_matches('\n').split('\0'); let (Some(h), Some(p), Some(t), Some(s)) = (f.next(), f.next(), f.next(), f.next()) else { return Err(RepoError::UnknownCommit(id.to_owned())); }; Ok(CommitInfo { id: h.to_owned(), parents: p .split(' ') .filter(|x| !x.is_empty()) .map(str::to_owned) .collect(), time: t.parse().unwrap_or(0), subject: s.to_owned(), }) } /// Read the tree of a commit, checking its shape. Cached for the last commit read. pub fn tree(&self, commit: &str) -> Result, RepoError> { if !is_commit_id(commit) { return Err(RepoError::UnknownCommit(commit.chars().take(64).collect())); } if let Ok(c) = self.cache.lock() && let Some((id, t)) = c.as_ref() && id == commit { return Ok(t.clone()); } let listing = self.git(&["ls-tree", "-r", "-z", "--full-tree", "-l", commit], None)?; let mut entries = Vec::new(); for rec in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) { let rec = String::from_utf8_lossy(rec); let (meta, path) = rec .split_once('\t') .ok_or_else(|| RepoError::Other("unexpected ls-tree output".into()))?; let mut m = meta.split_whitespace(); let (mode, kind, sha, size) = (m.next(), m.next(), m.next(), m.next()); let entry_kind = match (mode, kind) { (Some("100644"), Some("blob")) => EntryKind::File, (Some("100755"), Some("blob")) => EntryKind::Executable, (Some("120000"), _) => EntryKind::Symlink, _ => EntryKind::Submodule, }; let size: usize = size.and_then(|s| s.parse().ok()).unwrap_or(0); entries.push(( path.to_owned(), entry_kind, sha.unwrap_or("").to_owned(), size, )); } routes::check_tree(entries.iter().map(|(p, k, _, _)| (p.as_str(), *k))) .map_err(RepoError::Shape)?; let mut tree = RouteTree::default(); for (path, _, sha, size) in entries { if size > MAX_FILE_BYTES { return Err(RepoError::Shape(vec![ValidationError::FileTooLarge { file: path, max: MAX_FILE_BYTES, }])); } if !is_commit_id(&sha) { return Err(RepoError::Other("unexpected object id".into())); } let blob = self.git(&["cat-file", "blob", &sha], None)?; let text = String::from_utf8(blob).map_err(|_| { RepoError::Shape(vec![ValidationError::Syntax { file: path.clone(), line: None, message: "the file is not UTF-8 text".into(), }]) })?; tree.files.insert(path, text); } let tree = Arc::new(tree); if let Ok(mut c) = self.cache.lock() { *c = Some((commit.to_owned(), tree.clone())); } Ok(tree) } /// Write the tree objects for `tree`; returns the tree id. pub fn write_tree(&self, tree: &RouteTree, _base: Option<&str>) -> Result { let mut hosts = Vec::new(); let mut root = Vec::new(); for (path, content) in &tree.files { let sha = self.git_str_in(&["hash-object", "-w", "--stdin"], content.as_bytes())?; if let Some(name) = path.strip_prefix("hosts/") { hosts.extend_from_slice(format!("100644 blob {sha}\t{name}\0").as_bytes()); } else { root.extend_from_slice(format!("100644 blob {sha}\t{path}\0").as_bytes()); } } if !hosts.is_empty() { let sub = self.git_str_in(&["mktree", "-z"], &hosts)?; root.extend_from_slice(format!("040000 tree {sub}\thosts\0").as_bytes()); } self.git_str_in(&["mktree", "-z"], &root) } fn git_str_in(&self, args: &[&str], stdin: &[u8]) -> Result { let out = self.git(args, Some(stdin))?; let s = String::from_utf8_lossy(&out).trim().to_owned(); if !is_commit_id(&s) { return Err(RepoError::Other(format!( "git {} gave no object id", args[0] ))); } Ok(s) } /// Create a commit object (not yet on the branch). pub fn commit( &self, tree: &str, parents: &[&str], message: &str, author: &str, ) -> Result { let mut args = vec!["commit-tree", tree]; for p in parents { args.push("-p"); args.push(p); } args.extend(["-F", "-"]); let author: String = author .chars() .filter(|c| !c.is_control() && !"<>".contains(*c)) .take(64) .collect(); let author = if author.trim().is_empty() { "Ianitor control".to_owned() } else { author }; let env = [ ("GIT_AUTHOR_NAME", author.as_str()), ("GIT_AUTHOR_EMAIL", "ianitor@localhost"), ("GIT_COMMITTER_NAME", "Ianitor control"), ("GIT_COMMITTER_EMAIL", "ianitor@localhost"), ]; let out = self.run_in(Some(&self.dir), &args, None, Some(message.as_bytes()), &env)?; let s = String::from_utf8_lossy(&out).trim().to_owned(); if !is_commit_id(&s) { return Err(RepoError::Other("git commit-tree gave no commit id".into())); } Ok(s) } pub fn tree_id(&self, commit: &str) -> Result { if !is_commit_id(commit) { return Err(RepoError::UnknownCommit(commit.to_owned())); } self.git_str(&["rev-parse", "--verify", &format!("{commit}^{{tree}}")]) } /// Move the branch to `new` only if it is still at `old` (compare and swap). pub fn update_ref(&self, new: &str, old: Option<&str>) -> Result<(), RepoError> { let zero = "0".repeat(new.len()); let old = old.unwrap_or(&zero); self.git(&["update-ref", &self.reference(), new, old], None) .map(|_| ()) } /// Number of commits in `to` that are not in `from` (`from` none: all of `to`). pub fn count_between(&self, from: Option<&str>, to: &str) -> Result { let range = match from { Some(f) if is_commit_id(f) => format!("{f}..{to}"), _ => to.to_owned(), }; Ok(self .git_str(&["rev-list", "--count", &range])? .parse() .unwrap_or(0)) } /// Push `commit` to the branch on `remote`. Credentials come through `GIT_ASKPASS` /// (this binary's `askpass` mode), never on a command line or in a file. pub async fn push( &self, remote: &str, commit: &str, askpass: Option<(PathBuf, String, PathBuf)>, timeout: std::time::Duration, ) -> Result<(), RepoError> { if !is_commit_id(commit) { return Err(RepoError::UnknownCommit(commit.to_owned())); } let std_cmd = self.command(); let mut c = tokio::process::Command::from(std_cmd); c.env("GIT_DIR", &self.dir); if let Some((exe, user, file)) = askpass { c.env("GIT_ASKPASS", exe) .env("IANITOR_ASKPASS", "1") .env("IANITOR_ASKPASS_USER", user) .env("IANITOR_ASKPASS_FILE", file); } c.args([ "push", "--porcelain", "--", remote, &format!("{commit}:{}", self.reference()), ]) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); let child = c.spawn().map_err(|e| RepoError::Git { op: "push".into(), message: e.to_string(), })?; let out = tokio::time::timeout(timeout, child.wait_with_output()) .await .map_err(|_| RepoError::Git { op: "push".into(), message: format!("no answer within {} s", timeout.as_secs()), })? .map_err(|e| RepoError::Git { op: "push".into(), message: e.to_string(), })?; if out.status.success() { Ok(()) } else { let text = format!( "{} {}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr) ); Err(RepoError::Git { op: "push".into(), message: text.trim().chars().take(500).collect(), }) } } }