use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use anyhow::{bail, Context, Result};
pub(crate) fn host_git(repo: &Path) -> Result<Command> {
check_repo(repo)?;
Ok(git_command(repo))
}
pub(crate) fn host_git_bare(dir: &Path) -> Result<Command> {
check_dirs(dir, dir, dir)?;
let mut cmd = Command::new("git");
cmd.args(SAFE_ARGS).args(filter_args()).arg("--git-dir").arg(dir);
Ok(safe_env(cmd))
}
pub(crate) fn host_git_new(dir: &Path) -> Result<Command> {
if !dir.is_dir() {
bail!("refusing to run git in {}: not a directory", dir.display());
}
if dir.join(".git").symlink_metadata().is_ok() {
bail!("refusing to run git in {}: it holds a .git already", dir.display());
}
Ok(git_command(dir))
}
const SAFE_ARGS: [&str; 4] = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"];
fn git_command(repo: &Path) -> Command {
let mut cmd = Command::new("git");
cmd.args(SAFE_ARGS).args(filter_args()).arg("-C").arg(repo);
safe_env(cmd)
}
fn safe_env(mut cmd: Command) -> Command {
cmd.stdin(Stdio::null())
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_LFS_SKIP_SMUDGE", "1")
.envs(FILTER_VALUES);
for var in ["GIT_DIR", "GIT_COMMON_DIR", "GIT_WORK_TREE"] {
cmd.env_remove(var);
}
cmd
}
fn filter_args() -> &'static [String] {
static ARGS: OnceLock<Vec<String>> = OnceLock::new();
ARGS.get_or_init(|| neutral_filter_args(&user_filter_names(&[])))
}
const FILTER_VALUES: [(&str, &str); 3] =
[("DEVSANDBOX_GIT_EMPTY", ""), ("DEVSANDBOX_GIT_CAT", "cat"), ("DEVSANDBOX_GIT_FALSE", "false")];
fn neutral_filter_args(names: &BTreeSet<String>) -> Vec<String> {
let [(empty, _), (cat, _), (no, _)] = FILTER_VALUES;
names
.iter()
.flat_map(|name| {
[("smudge", cat), ("clean", cat), ("process", empty), ("required", no)]
.map(|(key, var)| format!("--config-env=filter.{name}.{key}={var}"))
})
.collect()
}
fn user_filter_names(env: &[(&str, &std::ffi::OsStr)]) -> BTreeSet<String> {
let mut names = BTreeSet::new();
for scope in ["--global", "--system"] {
let mut cmd = safe_env(Command::new("git"));
cmd.args(["config", scope, "--includes", "-z", "--name-only", "--get-regexp", r"^filter\."])
.current_dir("/")
.envs(env.iter().copied())
.stderr(Stdio::null());
if let Some(out) = cmd.output().ok().filter(|out| out.status.success()) {
names.extend(parse_filter_names(&out.stdout));
}
}
names
}
fn parse_filter_names(out: &[u8]) -> BTreeSet<String> {
out.split(|b| *b == 0)
.filter_map(|key| String::from_utf8_lossy(key).strip_prefix("filter.")?.rsplit_once('.').map(|(name, _)| name.to_string()))
.filter(|name| !name.is_empty())
.collect()
}
pub(crate) fn check_repo(repo: &Path) -> Result<()> {
let (gitdir, common) = git_dirs(repo)?;
check_dirs(repo, &gitdir, &common)
}
pub(crate) struct Origin {
pub common: PathBuf,
pub url: Option<String>,
}
pub(crate) fn read_origin(repo: &Path) -> Result<Origin> {
let (gitdir, common) = git_dirs(repo)?;
check_dirs(repo, &gitdir, &common)?;
let config = common.join("config");
let url = match std::fs::read(&config) {
Ok(bytes) => {
let entries = parse_config(&String::from_utf8_lossy(&bytes))
.map_err(|why| anyhow::anyhow!("cannot parse {} ({why})", config.display()))?;
origin_url(&entries)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(e).with_context(|| format!("cannot read {}", config.display())),
};
let common = common.canonicalize().with_context(|| format!("cannot resolve {}", common.display()))?;
Ok(Origin { common, url })
}
const MAX_CONFIG: u64 = 1 << 20;
pub(crate) fn read_remotes(repo: &Path, keep: impl Fn(&str) -> bool) -> Result<Vec<crate::state::FolderRemote>> {
let (_, common) = git_dirs(repo)?;
let config = common.join("config");
let bytes = match read_regular(&config) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e).with_context(|| format!("cannot read {}", config.display())),
};
let entries = parse_config(&String::from_utf8_lossy(&bytes))
.map_err(|why| anyhow::anyhow!("cannot parse {} ({why})", config.display()))?;
Ok(remotes_of(&entries, keep))
}
fn read_regular(path: &Path) -> std::io::Result<Vec<u8>> {
use std::io::{Error, ErrorKind, Read};
let mut options = std::fs::File::options();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW | libc::O_NONBLOCK);
#[cfg(not(unix))]
if std::fs::symlink_metadata(path)?.is_symlink() {
return Err(Error::other("a symlink"));
}
let file = options.open(path)?;
let meta = file.metadata()?;
if !meta.is_file() {
return Err(Error::other("not a regular file"));
}
if meta.len() > MAX_CONFIG {
return Err(Error::new(ErrorKind::InvalidData, format!("bigger than {MAX_CONFIG} bytes")));
}
let mut bytes = Vec::new();
file.take(MAX_CONFIG + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_CONFIG {
return Err(Error::new(ErrorKind::InvalidData, format!("bigger than {MAX_CONFIG} bytes")));
}
Ok(bytes)
}
fn remotes_of(entries: &[Entry], keep: impl Fn(&str) -> bool) -> Vec<crate::state::FolderRemote> {
let mut out: Vec<crate::state::FolderRemote> = Vec::new();
for e in entries.iter().filter(|e| e.section == "remote") {
let (Some(name), Some(value)) = (&e.subsection, e.value.as_deref().filter(|v| !v.is_empty())) else {
continue;
};
if !matches!(e.key.as_str(), "url" | "pushurl") || !keep(value) {
continue;
}
let i = match out.iter().position(|r| &r.name == name) {
Some(i) => i,
None => {
out.push(crate::state::FolderRemote { name: name.clone(), ..Default::default() });
out.len() - 1
}
};
let list = if e.key == "url" { &mut out[i].urls } else { &mut out[i].pushurls };
list.push(value.to_string());
}
out
}
fn origin_url(entries: &[Entry]) -> Option<String> {
entries
.iter()
.find(|e| e.section == "remote" && e.subsection.as_deref() == Some("origin") && e.key == "url")
.and_then(|e| e.value.clone())
}
fn check_dirs(repo: &Path, gitdir: &Path, common: &Path) -> Result<()> {
let refuse = |what: String| -> anyhow::Error {
anyhow::anyhow!("refusing to run git on {}: {what}", repo.display())
};
let shown = |p: &Path| p.strip_prefix(repo).unwrap_or(p).display().to_string();
let commondir = gitdir.join("commondir");
if gitdir == common && commondir.symlink_metadata().is_ok() {
return Err(refuse(format!(
"{} exists in a main git dir, which points host git at another repo; a sandbox may \
have written it — review and remove it",
shown(&commondir)
)));
}
if let Some(link) = symlink_refusal(gitdir, common).map_err(|e| refuse(format!("{e:#}")))? {
return Err(refuse(format!(
"{} is a symlink, which points host git at files outside the repo; a sandbox may \
have written it — review and remove it",
shown(&link)
)));
}
let alternates = common.join("objects/info/alternates");
if alternates.symlink_metadata().is_ok() {
return Err(refuse(format!(
"{} exists, which points host git at another object store; a sandbox may have \
written it — review and remove it",
shown(&alternates)
)));
}
for file in config_files(gitdir, common).map_err(|e| refuse(format!("{e:#}")))? {
let bytes = match std::fs::read(&file) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(refuse(format!("cannot read {}: {e}", shown(&file)))),
};
let entries = parse_config(&String::from_utf8_lossy(&bytes)).map_err(|why| {
refuse(format!("cannot parse {} ({why}); review and fix it by hand", shown(&file)))
})?;
if let Some(what) = entries.iter().find_map(refusal) {
return Err(refuse(format!(
"{} sets {what}, which can run commands on the host; a sandbox may have \
written it — review and remove it",
shown(&file)
)));
}
}
Ok(())
}
fn git_dirs(repo: &Path) -> Result<(PathBuf, PathBuf)> {
let refuse = |what: String| anyhow::anyhow!("refusing to run git on {}: {what}", repo.display());
let dotgit = repo.join(".git");
let meta = std::fs::symlink_metadata(&dotgit).map_err(|_| refuse("no .git found".into()))?;
if meta.is_symlink() {
return Err(refuse(
".git is a symlink, which points host git at another repo; a sandbox may have written \
it — review and remove it"
.into(),
));
}
if meta.is_dir() {
return Ok((dotgit.clone(), dotgit));
}
let text = std::fs::read_to_string(&dotgit).with_context(|| format!("cannot read {}", dotgit.display()))?;
let Some(path) = text.strip_prefix("gitdir:").map(str::trim) else {
bail!("refusing to run git on {}: .git is not a `gitdir:` file", repo.display());
};
let unlinked = |why: &str| {
refuse(format!(
".git points at {path}, {why}; a sandbox may have written it — review and remove it"
))
};
let gitdir = repo
.join(path)
.canonicalize()
.map_err(|e| unlinked(&format!("which cannot be resolved ({e})")))?;
let common = match gitdir.parent() {
Some(worktrees) if worktrees.file_name().is_some_and(|n| n == "worktrees") => worktrees.parent(),
_ => None,
}
.ok_or_else(|| unlinked("which is not a linked worktree's `<repo>/worktrees/<name>` dir"))?
.to_path_buf();
let resolves_to = |file: &str, want: &Path| -> bool {
std::fs::read_to_string(gitdir.join(file))
.ok()
.and_then(|text| gitdir.join(text.trim()).canonicalize().ok())
.is_some_and(|p| p == want)
};
let this = dotgit.canonicalize().with_context(|| format!("cannot resolve {}", dotgit.display()))?;
if !resolves_to("gitdir", &this) {
return Err(unlinked("whose `gitdir` back-pointer does not name this checkout"));
}
if !resolves_to("commondir", &common) {
return Err(unlinked(&format!("whose `commondir` does not name {}", common.display())));
}
Ok((gitdir, common))
}
fn symlink_refusal(gitdir: &Path, common: &Path) -> Result<Option<PathBuf>> {
let mut dirs = std::collections::VecDeque::from([(gitdir.to_path_buf(), false)]);
if common != gitdir {
dirs.push_back((common.to_path_buf(), false));
}
for sub in ["objects", "objects/info", "objects/pack"] {
dirs.push_back((common.join(sub), false));
}
for sub in ["refs", "logs"] {
dirs.push_back((gitdir.join(sub), true));
if common != gitdir {
dirs.push_back((common.join(sub), true));
}
}
while let Some((dir, recurse)) = dirs.pop_front() {
let entries = match std::fs::read_dir(&dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e).with_context(|| format!("cannot list {}", dir.display())),
};
for entry in entries {
let entry = entry.with_context(|| format!("cannot list {}", dir.display()))?;
let kind = entry.file_type().with_context(|| format!("cannot stat {}", entry.path().display()))?;
if kind.is_symlink() {
return Ok(Some(entry.path()));
}
if recurse && kind.is_dir() {
dirs.push_back((entry.path(), true));
}
}
}
Ok(None)
}
fn config_files(gitdir: &Path, common: &Path) -> Result<Vec<PathBuf>> {
let mut files = std::collections::BTreeSet::new();
files.insert(common.join("config"));
files.insert(common.join("config.worktree"));
files.insert(gitdir.join("config.worktree"));
let worktrees = common.join("worktrees");
match std::fs::read_dir(&worktrees) {
Ok(dir) => {
for entry in dir {
let entry = entry.with_context(|| format!("cannot list {}", worktrees.display()))?;
files.insert(entry.path().join("config.worktree"));
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e).with_context(|| format!("cannot list {}", worktrees.display())),
}
Ok(files.into_iter().collect())
}
#[derive(Debug, PartialEq)]
struct Entry {
section: String,
subsection: Option<String>,
key: String,
value: Option<String>,
}
impl Entry {
fn name(&self) -> String {
match &self.subsection {
Some(sub) => format!("{}.{sub}.{}", self.section, self.key),
None => format!("{}.{}", self.section, self.key),
}
}
}
fn refusal(e: &Entry) -> Option<String> {
let key = e.key.as_str();
let value = e.value.as_deref().unwrap_or("").trim_start();
let ext_url = || value.to_ascii_lowercase().starts_with("ext::");
let allowed = match (e.section.as_str(), e.subsection.as_deref()) {
("core", None) => matches!(
key,
"repositoryformatversion"
| "filemode"
| "bare"
| "logallrefupdates"
| "ignorecase"
| "precomposeunicode"
| "symlinks"
| "autocrlf"
| "eol"
| "safecrlf"
),
("extensions" | "worktree" | "rerere" | "color" | "advice", _) => true,
("remote", Some(_)) => match key {
"url" | "pushurl" if ext_url() => return Some(format!("{} to an ext:: URL", e.name())),
"url" | "pushurl" | "fetch" | "tagopt" | "prune" | "mirror" => true,
_ => false,
},
("branch", Some(_)) => {
matches!(
key,
"remote" | "merge" | "rebase" | "pushremote" | "description" | "vscode-merge-base"
) || key.starts_with("github-pr-")
}
("user", None) => matches!(key, "name" | "email"),
("init", None) => key == "defaultbranch",
("pull", None) => matches!(key, "rebase" | "ff"),
("push", None) => matches!(key, "default" | "autosetupremote"),
("fetch", None) => key == "prune",
("gc", _) => !key.contains("hook"),
("lfs", sub) => {
let sub = sub.unwrap_or("").to_ascii_lowercase();
!(key == "standalonetransferagent"
|| sub.starts_with("customtransfer")
|| sub.starts_with("extension"))
}
("submodule", Some(_)) => match key {
"url" if ext_url() => return Some(format!("{} to an ext:: URL", e.name())),
"update" if value.starts_with('!') => {
return Some(format!("{} to a `!command`", e.name()))
}
"url" | "active" | "update" => true,
_ => false,
},
_ => false,
};
(!allowed).then(|| e.name())
}
fn parse_config(text: &str) -> std::result::Result<Vec<Entry>, String> {
let s: Vec<char> = text.strip_prefix('\u{feff}').unwrap_or(text).chars().collect();
let mut p = Parser { s: &s, i: 0, line: 1 };
let mut section: Option<(String, Option<String>)> = None;
let mut entries = Vec::new();
while let Some(c) = p.peek() {
match c {
c if c.is_whitespace() => p.bump(),
'#' | ';' => p.skip_comment(),
'[' => {
p.bump();
section = Some(p.header()?);
}
c if c.is_ascii_alphabetic() => {
let Some((sec, sub)) = §ion else {
return Err(p.err("key before any [section]"));
};
let key = p.key();
p.skip_blanks();
let value = match p.peek() {
Some('=') => {
p.bump();
Some(p.value()?)
}
None | Some('\n' | '\r' | '#' | ';') => None,
Some(c) => return Err(p.err(&format!("unexpected `{c}` after key `{key}`"))),
};
entries.push(Entry { section: sec.clone(), subsection: sub.clone(), key, value });
}
c => return Err(p.err(&format!("unexpected `{c}`"))),
}
}
Ok(entries)
}
struct Parser<'a> {
s: &'a [char],
i: usize,
line: usize,
}
impl Parser<'_> {
fn peek(&self) -> Option<char> {
self.s.get(self.i).copied()
}
fn bump(&mut self) {
if self.peek() == Some('\n') {
self.line += 1;
}
self.i += 1;
}
fn err(&self, why: &str) -> String {
format!("line {}: {why}", self.line)
}
fn skip_comment(&mut self) {
while self.peek().is_some_and(|c| c != '\n') {
self.bump();
}
}
fn skip_blanks(&mut self) {
while matches!(self.peek(), Some(' ' | '\t')) {
self.bump();
}
}
fn header(&mut self) -> std::result::Result<(String, Option<String>), String> {
let mut name = String::new();
while let Some(c) = self.peek().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.')) {
name.push(c.to_ascii_lowercase());
self.bump();
}
if name.is_empty() {
return Err(self.err("empty section name"));
}
match self.peek() {
Some(']') => {
self.bump();
Ok(match name.split_once('.') {
Some((sec, sub)) => (sec.to_string(), Some(sub.to_string())),
None => (name, None),
})
}
Some(' ' | '\t') => {
self.skip_blanks();
if self.peek() != Some('"') {
return Err(self.err("expected `\"` in section header"));
}
self.bump();
let mut sub = String::new();
loop {
match self.peek() {
None | Some('\n') => return Err(self.err("unterminated subsection")),
Some('"') => break,
Some('\\') => {
self.bump();
match self.peek() {
None | Some('\n') => return Err(self.err("unterminated subsection")),
Some(c) => sub.push(c),
}
}
Some(c) => sub.push(c),
}
self.bump();
}
self.bump();
if self.peek() != Some(']') {
return Err(self.err("expected `]` after subsection"));
}
self.bump();
Ok((name, Some(sub)))
}
_ => Err(self.err("malformed section header")),
}
}
fn key(&mut self) -> String {
let mut key = String::new();
while let Some(c) = self.peek().filter(|c| c.is_ascii_alphanumeric() || *c == '-') {
key.push(c.to_ascii_lowercase());
self.bump();
}
key
}
fn value(&mut self) -> std::result::Result<String, String> {
self.skip_blanks();
let (mut v, mut keep, mut quoted) = (String::new(), 0, false);
loop {
match self.peek() {
None | Some('\n') if quoted => return Err(self.err("unterminated quote")),
None | Some('\n') => break,
Some('#' | ';') if !quoted => {
self.skip_comment();
break;
}
Some('"') => quoted = !quoted,
Some('\\') => {
self.bump();
match self.peek() {
Some('\n') => {}
Some('\r') if self.s.get(self.i + 1) == Some(&'\n') => self.bump(),
Some(c @ ('n' | 't' | 'b' | '\\' | '"')) => {
v.push(match c {
'n' => '\n',
't' => '\t',
'b' => '\u{8}',
c => c,
});
keep = v.len();
}
_ => return Err(self.err("invalid escape in value")),
}
}
Some(c @ (' ' | '\t' | '\r')) if !quoted => v.push(c),
Some(c) => {
v.push(c);
keep = v.len();
}
}
self.bump();
}
v.truncate(keep);
Ok(v)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(section: &str, sub: Option<&str>, key: &str, value: Option<&str>) -> Entry {
Entry {
section: section.into(),
subsection: sub.map(Into::into),
key: key.into(),
value: value.map(Into::into),
}
}
#[test]
fn parses_git_config_syntax() {
let text = "\u{feff}# comment\n\
[Core]\n\
\trepositoryFormatVersion = 0\n\
\tBare\n\
; another\n\
[remote \"Or\\\"ig\\\\in\"]\n\
\turl = git@h:o/r.git # trailing comment\n\
\tfetch = \"+refs/heads/*:refs/remotes/origin/*\" \n\
[branch.Main] remote = origin\n\
[user]\n\
\tname = \"a ; b\" c\\\n\
d\n\
\temail=x\\t@y\r\n";
let got = parse_config(text).unwrap();
assert_eq!(
got,
[
entry("core", None, "repositoryformatversion", Some("0")),
entry("core", None, "bare", None),
entry("remote", Some("Or\"ig\\in"), "url", Some("git@h:o/r.git")),
entry("remote", Some("Or\"ig\\in"), "fetch", Some("+refs/heads/*:refs/remotes/origin/*")),
entry("branch", Some("main"), "remote", Some("origin")),
entry("user", None, "name", Some("a ; b cd")),
entry("user", None, "email", Some("x\t@y")),
]
);
}
#[test]
fn unparseable_config_errors() {
for bad in [
"bare = true\n",
"[core\n",
"[]\n",
"[remote \"x]\n",
"[remote x]\n",
"[core]\n\tname = \"open\n",
"[core]\n\tname = bad\\q\n",
"[core]\n\t!key = 1\n",
"[core]\n\tkey value\n",
] {
assert!(parse_config(bad).is_err(), "{bad:?}");
}
assert_eq!(parse_config("[core]\n\tx = \"a\n").unwrap_err(), "line 2: unterminated quote");
}
#[test]
fn allowlist_accepts_and_refuses() {
let cases: &[(&str, Option<&str>)] = &[
("[core]\nrepositoryformatversion = 0\nfilemode\nbare = false\nlogallrefupdates = true", None),
("[Core]\nIgnoreCase = true\nsymlinks = false\nautocrlf = input\neol = lf", None),
("[extensions]\nworktreeConfig = true\nobjectFormat = sha256", None),
("[remote \"origin\"]\nurl = git@github.com:o/r.git\nfetch = +refs/heads/*:refs/remotes/origin/*\nprune = true", None),
("[branch \"main\"]\nremote = origin\nmerge = refs/heads/main\nvscode-merge-base = origin/main\ngithub-pr-owner-number = o#r#1", None),
("[user]\nname = a\nemail = b", None),
("[init]\ndefaultBranch = main\n[pull]\nrebase = true\n[push]\nautoSetupRemote = true\n[fetch]\nprune = true", None),
("[gc]\nauto = 0\n[gc \"refs/x\"]\nreflogExpire = never", None),
("[lfs]\nrepositoryformatversion = 0\n[lfs \"https://h/r.git/info/lfs\"]\naccess = basic", None),
("[submodule \"s\"]\nurl = ../s.git\nactive = true\nupdate = rebase", None),
("[worktree]\nguessRemote = true\n[rerere]\nenabled = true\n[color]\nui = auto\n[advice]\ndetachedHead = false", None),
("[core]\nfsmonitor = /tmp/x", Some("core.fsmonitor")),
("[CORE]\nFsMonitor = true", Some("core.fsmonitor")),
("[core]\nsshCommand = sh", Some("core.sshcommand")),
("[core]\nhooksPath = /tmp", Some("core.hookspath")),
("[core]\nalternateRefsCommand = x", Some("core.alternaterefscommand")),
("[core \"x\"]\nbare = false", Some("core.x.bare")),
("[include]\npath = /tmp/evil", Some("include.path")),
("[includeIf \"gitdir:x\"]\npath = /tmp/evil", Some("includeif.gitdir:x.path")),
("[filter \"lfs\"]\nprocess = git-lfs filter-process", Some("filter.lfs.process")),
("[diff \"x\"]\ntextconv = sh", Some("diff.x.textconv")),
("[credential]\nhelper = !sh", Some("credential.helper")),
("[url \"ext::sh\"]\ninsteadOf = https://", Some("url.ext::sh.insteadof")),
("[remote \"origin\"]\nurl = ext::sh -c x", Some("remote.origin.url to an ext:: URL")),
("[remote \"origin\"]\npushurl = EXT::sh", Some("remote.origin.pushurl to an ext:: URL")),
("[remote \"origin\"]\nuploadpack = sh", Some("remote.origin.uploadpack")),
("[remote]\npushDefault = origin", Some("remote.pushdefault")),
("[branch \"main\"]\nsomething = x", Some("branch.main.something")),
("[gc]\npreAutoHook = x", Some("gc.preautohook")),
("[lfs \"customtransfer.x\"]\npath = sh", Some("lfs.customtransfer.x.path")),
("[lfs \"extension.x\"]\nclean = sh", Some("lfs.extension.x.clean")),
("[lfs]\nstandalonetransferagent = x", Some("lfs.standalonetransferagent")),
("[submodule \"s\"]\nupdate = !sh -c x", Some("submodule.s.update to a `!command`")),
("[submodule \"s\"]\nurl = ext::sh", Some("submodule.s.url to an ext:: URL")),
("[http]\nproxy = x", Some("http.proxy")),
];
for (text, want) in cases {
let entries = parse_config(text).unwrap();
assert_eq!(entries.iter().find_map(refusal).as_deref(), *want, "{text}");
}
}
#[test]
fn origin_url_is_the_first_url_of_remote_origin() {
let url = |text: &str| origin_url(&parse_config(text).unwrap());
assert_eq!(url("[core]\nbare = false"), None);
assert_eq!(url("[remote \"upstream\"]\nurl = /u\n[remote \"Origin\"]\nurl = /x"), None);
assert_eq!(url("[remote \"origin\"]\nfetch = x\nURL = /a\nurl = /b\n[remote \"origin\"]\nurl = /c"), Some("/a".into()));
assert_eq!(url("[remote.ORIGIN]\nurl = /legacy\n[remote \"origin\"]\nurl = /b"), Some("/legacy".into()));
}
#[test]
fn read_origin_keys_checkouts_by_canonical_common_dir() {
let root = temp("origin");
let (base, wt) = base_and_worktree(&root);
let none = read_origin(&base).unwrap();
assert_eq!((none.common, none.url), (base.join(".git").canonicalize().unwrap(), None));
git_in(&base, &["remote", "add", "origin", "/srv/repo.git"]);
for repo in [&base, &wt] {
let o = read_origin(repo).unwrap();
assert_eq!((o.common, o.url.as_deref()), (base.join(".git").canonicalize().unwrap(), Some("/srv/repo.git")));
}
std::fs::write(base.join(".git/config.worktree"), "[core]\n\tfsmonitor = x\n").unwrap();
assert!(read_origin(&base).is_err(), "refused like check_repo");
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn wrapper_disables_hooks_fsmonitor_filters_and_prompts() {
let cmd = git_command(Path::new("/r"));
assert_eq!(cmd.get_program(), "git");
let args: Vec<_> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
let mut want = vec!["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"];
want.extend(filter_args().iter().map(String::as_str));
want.extend(["-C", "/r"]);
assert_eq!(args, want);
let envs: Vec<_> = cmd.get_envs().collect();
assert!(envs.contains(&("GIT_TERMINAL_PROMPT".as_ref(), Some("0".as_ref()))));
assert!(envs.contains(&("GIT_LFS_SKIP_SMUDGE".as_ref(), Some("1".as_ref()))));
assert!(envs.contains(&("DEVSANDBOX_GIT_EMPTY".as_ref(), Some("".as_ref()))));
assert!(envs.contains(&("GIT_DIR".as_ref(), None)));
}
#[test]
fn filter_names_and_overrides() {
let names = parse_filter_names(b"filter.lfs.process\0filter.lfs.smudge\0filter.a.b.clean\0filter.x=y.required\0filter..smudge\0core.x\0");
assert_eq!(names.iter().map(String::as_str).collect::<Vec<_>>(), ["a.b", "lfs", "x=y"]);
let args = neutral_filter_args(&BTreeSet::from(["x=y".to_string()]));
assert_eq!(
args,
[
"--config-env=filter.x=y.smudge=DEVSANDBOX_GIT_CAT",
"--config-env=filter.x=y.clean=DEVSANDBOX_GIT_CAT",
"--config-env=filter.x=y.process=DEVSANDBOX_GIT_EMPTY",
"--config-env=filter.x=y.required=DEVSANDBOX_GIT_FALSE",
]
);
}
const LFS_POINTER: &str = "version https://git-lfs.github.com/spec/v1\n\
oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 12345\n";
#[cfg(unix)]
fn repo_with_user_filters(root: &Path) -> (PathBuf, PathBuf) {
use std::os::unix::fs::PermissionsExt;
let script = root.join("filter.sh");
std::fs::write(&script, format!("#!/bin/sh\ntouch {}/marker\ncat\n", root.display())).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let section = |name: &str| {
let s = script.display();
format!("[filter \"{name}\"]\n\tsmudge = {s}\n\tclean = {s}\n\tprocess = {s}\n\trequired = true\n")
};
std::fs::write(root.join("included"), section("my.dot")).unwrap();
let global = root.join("global");
let include = format!("[include]\n\tpath = {}\n", root.join("included").display());
std::fs::write(&global, section("lfs") + §ion("x=y") + &include).unwrap();
let base = root.join("base");
std::fs::create_dir_all(&base).unwrap();
git_in(&base, &["init", "-q", "-b", "main"]);
std::fs::write(base.join(".gitattributes"), "*.bin filter=lfs\n*.txt filter=my.dot\n*.dat filter=x=y\n").unwrap();
std::fs::write(base.join("big.bin"), LFS_POINTER).unwrap();
std::fs::write(base.join("a.txt"), "a\n").unwrap();
std::fs::write(base.join("b.dat"), "b\n").unwrap();
git_in(&base, &["add", "."]);
git_in(&base, &["commit", "-q", "-m", "x"]);
(base, global)
}
#[cfg(unix)]
#[test]
fn host_checkouts_never_run_user_filters() {
let root = temp("filters");
let (base, global) = repo_with_user_filters(&root);
let env = [("GIT_CONFIG_GLOBAL", global.as_os_str())];
let names = user_filter_names(&env);
for name in ["lfs", "my.dot", "x=y"] {
assert!(names.contains(name), "{name}: {names:?}");
}
let marker = root.join("marker");
let git = |repo: &Path, args: &[&str]| {
let ok = host_git(repo)
.unwrap()
.args(neutral_filter_args(&names))
.envs(env)
.args(args)
.status()
.unwrap()
.success();
assert!(ok, "git {args:?}");
};
let checked_out = |dir: &Path| {
assert!(!marker.exists(), "a filter ran");
assert_eq!(std::fs::read_to_string(dir.join("big.bin")).unwrap(), LFS_POINTER);
assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "a\n");
assert_eq!(std::fs::read_to_string(dir.join("b.dat")).unwrap(), "b\n");
};
let wt = root.join("wt");
git(&base, &["worktree", "add", "-q", wt.to_str().unwrap()]);
checked_out(&wt);
for f in ["big.bin", "a.txt", "b.dat"] {
std::fs::remove_file(wt.join(f)).unwrap();
}
git(&wt, &["reset", "-q", "--hard"]);
checked_out(&wt);
git(&wt, &["status", "--porcelain"]);
assert!(!marker.exists(), "a filter ran");
std::fs::remove_file(wt.join("a.txt")).unwrap();
let ran = Command::new("git").arg("-C").arg(&wt).args(["reset", "-q", "--hard"]).envs(env).status().unwrap();
assert!(marker.exists(), "control: filter not run ({ran})");
std::fs::remove_dir_all(&root).unwrap();
}
fn temp(tag: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!("devsandbox-git-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
root
}
fn git_in(dir: &Path, args: &[&str]) {
let ok = Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.arg("-C")
.arg(dir)
.args(args)
.status()
.unwrap()
.success();
assert!(ok, "git {args:?}");
}
fn base_and_worktree(root: &Path) -> (PathBuf, PathBuf) {
let (base, wt) = (root.join("base"), root.join("wt"));
std::fs::create_dir_all(&base).unwrap();
git_in(&base, &["init", "-q", "-b", "main"]);
std::fs::write(base.join("f"), "x\n").unwrap();
git_in(&base, &["add", "f"]);
git_in(&base, &["commit", "-q", "-m", "x"]);
git_in(&base, &["worktree", "add", "-q", "-b", "wt", wt.to_str().unwrap()]);
(base, wt)
}
fn refusal_of(repo: &Path) -> String {
format!("{:#}", check_repo(repo).unwrap_err())
}
#[test]
fn git_dirs_for_checkout_and_linked_worktree() {
let root = temp("dirs");
let (base, wt) = base_and_worktree(&root);
let common = base.join(".git").canonicalize().unwrap();
assert_eq!(git_dirs(&base).unwrap(), (base.join(".git"), base.join(".git")));
assert_eq!(git_dirs(&wt).unwrap(), (common.join("worktrees/wt"), common.clone()));
check_repo(&wt).unwrap();
std::fs::write(wt.join(".git"), "gitdir: ../base/.git/worktrees/wt\n").unwrap();
std::fs::write(common.join("worktrees/wt/gitdir"), "../../../../wt/.git\n").unwrap();
assert_eq!(git_dirs(&wt).unwrap().0, common.join("worktrees/wt"));
assert!(git_dirs(&root).is_err(), "no .git");
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn redirected_gitdir_and_commondir_refuse() {
let root = temp("redirect");
let (base, wt) = base_and_worktree(&root);
let other = root.join("other");
std::fs::create_dir_all(&other).unwrap();
git_in(&other, &["init", "-q"]);
let checkout = root.join("checkout");
std::fs::create_dir_all(&checkout).unwrap();
std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", other.join(".git").display())).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains("not a linked worktree's"), "{err}");
let admin = base.join(".git/worktrees/wt");
std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains("back-pointer does not name this checkout"), "{err}");
let fake = other.join(".git/worktrees/x");
std::fs::create_dir_all(&fake).unwrap();
std::fs::write(fake.join("commondir"), "../..\n").unwrap();
std::fs::write(fake.join("gitdir"), format!("{}\n", wt.join(".git").display())).unwrap();
std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", fake.display())).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains("back-pointer does not name this checkout"), "{err}");
std::fs::write(fake.join("gitdir"), format!("{}\n", checkout.join(".git").display())).unwrap();
std::fs::remove_file(fake.join("commondir")).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains("`commondir` does not name"), "{err}");
std::fs::write(admin.join("commondir"), format!("{}\n", other.join(".git").display())).unwrap();
let err = refusal_of(&wt);
assert!(err.contains("`commondir` does not name"), "{err}");
std::fs::write(admin.join("commondir"), "../..\n").unwrap();
check_repo(&wt).unwrap();
std::fs::write(base.join(".git/commondir"), format!("{}\n", other.join(".git").display())).unwrap();
let err = refusal_of(&base);
assert!(err.contains(".git/commondir exists in a main git dir"), "{err}");
std::fs::remove_dir_all(&root).unwrap();
}
#[cfg(unix)]
#[test]
fn symlinks_in_git_dirs_refuse() {
use std::os::unix::fs::symlink;
let root = temp("symlinks");
let (base, wt) = base_and_worktree(&root);
let elsewhere = root.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
let git = base.join(".git");
for (rel, is_dir) in [("refs/heads", true), ("objects", true), ("index", false), ("refs/heads/main", false), ("objects/pack", true), ("logs/HEAD", false)] {
let p = git.join(rel);
let saved = root.join("saved");
std::fs::rename(&p, &saved).unwrap();
let target = if is_dir { elsewhere.clone() } else { elsewhere.join("f") };
symlink(&target, &p).unwrap();
for repo in [&base, &wt] {
let err = refusal_of(repo);
assert!(err.contains(&format!("{rel} is a symlink")), "{rel}: {err}");
}
std::fs::remove_file(&p).unwrap();
std::fs::rename(&saved, &p).unwrap();
check_repo(&base).unwrap();
}
symlink(elsewhere.join("f"), git.join("worktrees/wt/index.lock")).unwrap();
let err = refusal_of(&wt);
assert!(err.contains("worktrees/wt/index.lock is a symlink"), "{err}");
std::fs::remove_file(git.join("worktrees/wt/index.lock")).unwrap();
let checkout = root.join("checkout");
std::fs::create_dir_all(&checkout).unwrap();
symlink(&git, checkout.join(".git")).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains(".git is a symlink"), "{err}");
std::fs::remove_file(checkout.join(".git")).unwrap();
symlink(wt.join(".git"), checkout.join(".git")).unwrap();
let err = refusal_of(&checkout);
assert!(err.contains(".git is a symlink"), "{err}");
let via = root.join("via");
symlink(&root, &via).unwrap();
check_repo(&via.join("base")).unwrap();
check_repo(&via.join("wt")).unwrap();
std::fs::remove_dir_all(&root).unwrap();
}
#[cfg(unix)]
#[test]
fn bare_repo_refuses_symlinks_and_commondir() {
use std::os::unix::fs::symlink;
let root = temp("bare");
let cache = root.join("c.git");
std::fs::create_dir_all(&cache).unwrap();
git_in(&cache, &["init", "-q", "--bare"]);
host_git_bare(&cache).unwrap();
symlink(root.join("x"), cache.join("refs/heads/main")).unwrap();
let err = format!("{:#}", host_git_bare(&cache).unwrap_err());
assert!(err.contains("refs/heads/main is a symlink"), "{err}");
std::fs::remove_file(cache.join("refs/heads/main")).unwrap();
std::fs::write(cache.join("commondir"), "/elsewhere\n").unwrap();
let err = format!("{:#}", host_git_bare(&cache).unwrap_err());
assert!(err.contains("commondir exists in a main git dir"), "{err}");
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn check_repo_reads_every_config_and_alternates() {
let root = temp("check");
let git = |args: &[&str]| {
let ok = Command::new("git").arg("-C").arg(&root).args(args).status().unwrap().success();
assert!(ok, "git {args:?}");
};
git(&["init", "-q", "-b", "main"]);
check_repo(&root).unwrap();
let wtconf = root.join(".git/worktrees/x/config.worktree");
std::fs::create_dir_all(wtconf.parent().unwrap()).unwrap();
std::fs::write(&wtconf, "[core]\n\tfsmonitor = /tmp/pwn\n").unwrap();
let err = check_repo(&root).unwrap_err().to_string();
assert!(err.contains(".git/worktrees/x/config.worktree sets core.fsmonitor"), "{err}");
std::fs::remove_file(&wtconf).unwrap();
std::fs::write(root.join(".git/config.worktree"), "[core\n").unwrap();
let err = check_repo(&root).unwrap_err().to_string();
assert!(err.contains("cannot parse .git/config.worktree (line 1:"), "{err}");
std::fs::remove_file(root.join(".git/config.worktree")).unwrap();
std::fs::write(root.join(".git/objects/info/alternates"), "/elsewhere\n").unwrap();
let err = check_repo(&root).unwrap_err().to_string();
assert!(err.contains(".git/objects/info/alternates exists"), "{err}");
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
#[ignore]
fn real_repo_passes() {
check_repo(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
}
fn remote(name: &str, urls: &[&str], pushurls: &[&str]) -> crate::state::FolderRemote {
crate::state::FolderRemote {
name: name.into(),
urls: urls.iter().map(|u| u.to_string()).collect(),
pushurls: pushurls.iter().map(|u| u.to_string()).collect(),
}
}
#[test]
fn reads_every_remote_url_and_pushurl() {
let text = "[remote \"origin\"]\n\
\turl = \"git@github.com:o/r.git\" ; quoted\n\
\tpushurl = https://github.com/o/r\n\
\turl = /home/u/mirror\n\
\tfetch = +refs/heads/*:refs/remotes/origin/*\n\
[include]\n\tpath = /etc/evil\n\
[includeIf \"gitdir:/\"]\n\tpath = x\n\
[branch \"main\"]\n\tremote = https://github.com/planted/x\n\
[remote \"Up\\\"stream\"]\n\turl =\n\turl = https://github.com/u/r\n\tpushurl = file:///x\n\
[remote \"local\"]\n\turl = ../other\n\
[remote.Legacy]\n\turl = https://gitlab.com/l/r\n\
[remote \"origin\"]\n\tpushurl = git@gitlab.com:o/r\n";
let entries = parse_config(text).unwrap();
let keep = |u: &str| crate::credentials::fence::parse(u).is_some();
assert_eq!(
remotes_of(&entries, keep),
[
remote("origin", &["git@github.com:o/r.git"], &["https://github.com/o/r", "git@gitlab.com:o/r"]),
remote("Up\"stream", &["https://github.com/u/r"], &[]),
remote("legacy", &["https://gitlab.com/l/r"], &[]),
]
);
}
#[test]
fn read_remotes_refuses_a_symlinked_or_huge_config() {
let root = temp("remotes");
let repo = root.join("repo");
std::fs::create_dir_all(&repo).unwrap();
git_in(&repo, &["init", "-q"]);
git_in(&repo, &["remote", "add", "origin", "https://github.com/o/r"]);
let all = |_: &str| true;
assert_eq!(read_remotes(&repo, all).unwrap(), [remote("origin", &["https://github.com/o/r"], &[])]);
let config = repo.join(".git/config");
let elsewhere = root.join("elsewhere");
std::fs::write(&elsewhere, "[remote \"x\"]\n\turl = https://github.com/x/y\n").unwrap();
std::fs::remove_file(&config).unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(&elsewhere, &config).unwrap();
let err = read_remotes(&repo, all).unwrap_err();
assert!(format!("{err:#}").contains("cannot read"), "{err:#}");
std::fs::remove_file(&config).unwrap();
let ok = Command::new("mkfifo").arg(&config).status().unwrap().success();
assert!(ok);
assert!(read_remotes(&repo, all).is_err(), "a FIFO is refused, not waited on");
std::fs::remove_file(&config).unwrap();
}
assert!(read_remotes(&repo, all).unwrap().is_empty(), "no config: no remotes");
std::fs::write(&config, format!("[core]\n#{}\n", "x".repeat(MAX_CONFIG as usize))).unwrap();
assert!(read_remotes(&repo, all).is_err());
std::fs::write(&config, "[remote \"origin\"]\n\turl = https://github.com/o/r\n").unwrap();
let (base, wt) = base_and_worktree(&root.join("wt"));
git_in(&base, &["remote", "add", "origin", "git@github.com:b/r"]);
assert_eq!(read_remotes(&wt, all).unwrap(), [remote("origin", &["git@github.com:b/r"], &[])]);
std::fs::remove_dir_all(&root).unwrap();
}
}