use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio_util::sync::CancellationToken;
use crate::interface::exec::{
capture, Captured, Enforcement, ExecError, ExecProviders, FileSystem, NetworkMode, ProcessSpec,
SandboxPolicy,
};
use crate::permission::ProjectTrust;
pub const ENGINE_GIT_OPTIONS: &[&str] = &[
"-c",
"core.fsmonitor=false",
"-c",
"core.hooksPath=/dev/null",
];
#[derive(Clone)]
pub struct EngineExec {
exec: ExecProviders,
confinement: Confinement,
trust: ProjectTrust,
min_deadline: Duration,
}
#[derive(Debug, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum Confinement {
#[default]
Unconfined,
Sandboxed {
policy: SandboxPolicy,
require_enforcement: bool,
tmpdir: Option<PathBuf>,
},
}
#[derive(Debug, Clone, Copy)]
pub enum GitAccess<'a> {
ReadOnly,
Writes(&'a [PathBuf]),
}
impl<'a> GitAccess<'a> {
fn writable(&self) -> &'a [PathBuf] {
match self {
Self::ReadOnly => &[],
Self::Writes(paths) => paths,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
Run { options: &'static [&'static str] },
Refuse(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Program {
Git,
Helper,
}
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum EngineExecError {
#[error("not run: {0}")]
Refused(String),
#[error("timed out after {0:?}")]
TimedOut(Duration),
#[error(transparent)]
Failed(#[from] ExecError),
}
pub fn admit_git(
trust: ProjectTrust,
_access: &GitAccess<'_>,
confinement: &Confinement,
) -> Admission {
match (confinement, trust) {
(Confinement::Sandboxed { .. }, _)
| (Confinement::Unconfined, ProjectTrust::Trusted | ProjectTrust::NoProject) => {
Admission::Run {
options: ENGINE_GIT_OPTIONS,
}
}
(Confinement::Unconfined, ProjectTrust::Untrusted) => {
Admission::Refuse(UNTRUSTED_UNCONFINED.into())
}
}
}
const UNTRUSTED_UNCONFINED: &str = "the project is not trusted and the engine's git would run \
outside any sandbox, where the programs its repository configuration names would run \
unconfined; trust the project (`project.trust`) or let the sandbox hold the session's commands";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Head {
pub branch: Option<String>,
pub linked: bool,
}
pub async fn read_head(fs: &dyn FileSystem, dir: &Path) -> Option<Head> {
for at in dir.ancestors() {
let dot_git = at.join(".git");
let Ok(meta) = fs.metadata_following_symlinks(&dot_git).await else {
continue;
};
let (git_dir, linked) = if meta.is_dir {
(dot_git, false)
} else {
let link = fs.read_to_string(&dot_git).await.ok()?;
let target = link.lines().next()?.strip_prefix("gitdir:")?.trim();
(at.join(target), true)
};
let head = fs.read_to_string(&git_dir.join("HEAD")).await.ok()?;
let head = head.trim();
let branch = head
.strip_prefix("ref:")
.map(str::trim)
.and_then(|r| r.strip_prefix("refs/heads/"))
.map(str::to_string);
return Some(Head { branch, linked });
}
None
}
impl EngineExec {
pub fn new(exec: ExecProviders, confinement: Confinement, trust: ProjectTrust) -> Self {
Self {
exec,
confinement,
trust,
min_deadline: Duration::ZERO,
}
}
pub fn with_min_deadline(mut self, floor: Duration) -> Self {
self.min_deadline = floor;
self
}
pub fn exec(&self) -> &ExecProviders {
&self.exec
}
pub fn is_sandboxed(&self) -> bool {
matches!(self.confinement, Confinement::Sandboxed { .. })
}
pub fn tmpdir(&self) -> Option<&Path> {
match &self.confinement {
Confinement::Sandboxed { tmpdir, .. } => tmpdir.as_deref(),
Confinement::Unconfined => None,
}
}
pub async fn git(
&self,
cwd: &Path,
access: GitAccess<'_>,
args: &[&str],
deadline: Duration,
) -> Result<Captured, EngineExecError> {
let options = match admit_git(self.trust, &access, &self.confinement) {
Admission::Run { options } => options,
Admission::Refuse(why) => return Err(EngineExecError::Refused(why)),
};
let mut spec = ProcessSpec::new("git", cwd)
.args(options.iter().copied())
.args(args.iter().copied());
spec.env.extend([
("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
("GIT_ASKPASS".to_string(), String::new()),
]);
self.run(spec, access.writable(), Program::Git, deadline)
.await
}
pub async fn helper(
&self,
spec: ProcessSpec,
writable: &[PathBuf],
deadline: Duration,
) -> Result<Captured, EngineExecError> {
self.run(spec, writable, Program::Helper, deadline).await
}
async fn run(
&self,
spec: ProcessSpec,
writable: &[PathBuf],
program: Program,
deadline: Duration,
) -> Result<Captured, EngineExecError> {
let spec = self.confine(spec, writable, program)?;
let deadline = deadline.max(self.min_deadline);
let captured = tokio::time::timeout(
deadline,
capture(&*self.exec.process, spec, CancellationToken::new()),
)
.await
.map_err(|_| EngineExecError::TimedOut(deadline))??;
Ok(captured)
}
fn confine(
&self,
spec: ProcessSpec,
writable: &[PathBuf],
program: Program,
) -> Result<ProcessSpec, EngineExecError> {
let Confinement::Sandboxed {
policy,
require_enforcement,
tmpdir,
} = &self.confinement
else {
return Ok(spec);
};
let mut policy = policy.clone();
policy.only_additional_writable = true;
policy.network_mode = NetworkMode::DenyAll;
policy.additional_writable = tmpdir.iter().chain(writable).cloned().collect();
let mut confined = self.exec.sandbox.confine(spec.clone(), &policy);
if confined.enforcement == Enforcement::None {
let unmet = confined.unmet.join("; ");
if *require_enforcement {
return Err(EngineExecError::Refused(format!(
"the session's commands are sandboxed and `sandbox.require` \
is on, but {} cannot be sandboxed here ({unmet})",
spec.program
)));
}
if program == Program::Git && self.trust.is_untrusted() {
return Err(EngineExecError::Refused(format!(
"{UNTRUSTED_UNCONFINED} ({unmet})"
)));
}
warn_unconfined_once(&unmet);
return Ok(spec);
}
if let Some(tmp) = tmpdir {
confined
.spec
.env
.push(("TMPDIR".to_string(), tmp.display().to_string()));
}
Ok(confined.spec)
}
}
impl std::fmt::Debug for EngineExec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EngineExec")
.field("confinement", &self.confinement)
.field("trust", &self.trust)
.finish_non_exhaustive()
}
}
fn warn_unconfined_once(unmet: &str) {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(
unmet,
"the engine's own subprocesses run unsandboxed: the sandbox cannot hold them \
on this build or platform"
);
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interface::exec::in_process::{NoSandbox, ScriptedProcess, ScriptedRun};
use crate::interface::exec::{Confined, Sandbox};
use std::sync::{Arc, Mutex};
const DEADLINE: Duration = Duration::from_secs(5);
fn with_process(process: ScriptedProcess) -> ExecProviders {
ExecProviders {
process: Arc::new(process),
..ExecProviders::in_process()
}
}
fn git_key(args: &str) -> String {
format!("git {} {args}", ENGINE_GIT_OPTIONS.join(" "))
}
#[tokio::test]
async fn git_runs_through_the_sessions_process_with_the_engines_options() {
let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok("clean"));
let engine = EngineExec::new(
with_process(process.clone()),
Confinement::Unconfined,
ProjectTrust::Trusted,
);
let out = engine
.git(
Path::new("/repo"),
GitAccess::ReadOnly,
&["status"],
DEADLINE,
)
.await
.unwrap();
assert_eq!(out.stdout_lossy(), "clean");
assert_eq!(process.seen(), [git_key("status")]);
}
#[derive(Default)]
struct RecordingSandbox(Mutex<Vec<SandboxPolicy>>);
impl Sandbox for RecordingSandbox {
fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined {
self.0.lock().unwrap().push(policy.clone());
let mut wrapped = ProcessSpec::new("boxed", spec.cwd.clone()).arg(spec.program);
wrapped.args.extend(spec.args);
wrapped.env = spec.env;
Confined {
spec: wrapped,
mode: crate::interface::exec::SandboxMode::LinuxBwrap,
enforcement: Enforcement::Full,
unmet: Vec::new(),
}
}
}
#[tokio::test]
async fn a_sandboxed_git_writes_only_what_it_names_and_reaches_no_network() {
let sandbox = Arc::new(RecordingSandbox::default());
let process = ScriptedProcess::new().with(
format!("boxed {}", git_key("worktree prune")),
ScriptedRun::ok(""),
);
let exec = ExecProviders {
sandbox: sandbox.clone(),
..with_process(process.clone())
};
let engine = EngineExec::new(
exec,
Confinement::Sandboxed {
policy: SandboxPolicy {
additional_writable: vec![PathBuf::from("/elsewhere")],
..Default::default()
},
require_enforcement: true,
tmpdir: Some(PathBuf::from("/tmp/session")),
},
ProjectTrust::Trusted,
);
let writable = [PathBuf::from("/repo/.git")];
engine
.git(
Path::new("/repo"),
GitAccess::Writes(&writable),
&["worktree", "prune"],
DEADLINE,
)
.await
.unwrap();
let policy = sandbox.0.lock().unwrap()[0].clone();
assert!(policy.only_additional_writable);
assert_eq!(policy.network_mode, NetworkMode::DenyAll);
assert_eq!(
policy.additional_writable,
[PathBuf::from("/tmp/session"), PathBuf::from("/repo/.git")]
);
}
#[tokio::test]
async fn a_git_the_sandbox_cannot_hold_is_refused_only_when_one_is_required() {
let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
let exec = ExecProviders {
sandbox: Arc::new(NoSandbox),
..with_process(process.clone())
};
let engine = |require_enforcement| {
EngineExec::new(
exec.clone(),
Confinement::Sandboxed {
policy: SandboxPolicy::default(),
require_enforcement,
tmpdir: None,
},
ProjectTrust::Trusted,
)
};
let refused = engine(true)
.git(
Path::new("/repo"),
GitAccess::ReadOnly,
&["status"],
DEADLINE,
)
.await
.unwrap_err();
assert!(
matches!(refused, EngineExecError::Refused(_)),
"{refused:?}"
);
assert!(process.seen().is_empty(), "git ran anyway");
engine(false)
.git(
Path::new("/repo"),
GitAccess::ReadOnly,
&["status"],
DEADLINE,
)
.await
.unwrap();
assert_eq!(process.seen(), [git_key("status")]);
}
#[test]
fn only_an_untrusted_projects_git_outside_any_sandbox_is_refused() {
let sandboxed = Confinement::Sandboxed {
policy: SandboxPolicy::default(),
require_enforcement: false,
tmpdir: None,
};
for trust in [
ProjectTrust::NoProject,
ProjectTrust::Trusted,
ProjectTrust::Untrusted,
] {
assert!(
matches!(
admit_git(trust, &GitAccess::ReadOnly, &sandboxed),
Admission::Run { .. }
),
"{trust:?} in a sandbox"
);
let unconfined = admit_git(trust, &GitAccess::ReadOnly, &Confinement::Unconfined);
assert_eq!(
matches!(unconfined, Admission::Refuse(_)),
trust == ProjectTrust::Untrusted,
"{trust:?} unconfined: {unconfined:?}"
);
}
}
#[tokio::test]
async fn an_untrusted_projects_git_a_sandbox_cannot_hold_does_not_run() {
let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
let exec = ExecProviders {
sandbox: Arc::new(NoSandbox),
..with_process(process.clone())
};
let engine = EngineExec::new(
exec,
Confinement::Sandboxed {
policy: SandboxPolicy::default(),
require_enforcement: false,
tmpdir: None,
},
ProjectTrust::Untrusted,
);
let refused = engine
.git(
Path::new("/repo"),
GitAccess::ReadOnly,
&["status"],
DEADLINE,
)
.await
.unwrap_err();
assert!(
matches!(refused, EngineExecError::Refused(_)),
"{refused:?}"
);
assert!(process.seen().is_empty(), "git ran anyway");
}
#[tokio::test]
async fn read_head_follows_a_gitdir_link_and_walks_up() {
use crate::interface::exec::in_process::InMemoryFileSystem;
let fs = InMemoryFileSystem::new();
fs.write_str(Path::new("/repo/.git/HEAD"), "ref: refs/heads/feature/x\n")
.await
.unwrap();
fs.create_dir_all(Path::new("/repo/src/deep"))
.await
.unwrap();
assert_eq!(
read_head(&fs, Path::new("/repo/src/deep")).await,
Some(Head {
branch: Some("feature/x".into()),
linked: false
})
);
fs.write_str(Path::new("/wt/.git"), "gitdir: /repo/.git/worktrees/wt\n")
.await
.unwrap();
fs.write_str(
Path::new("/repo/.git/worktrees/wt/HEAD"),
"0123456789abcdef0123456789abcdef01234567\n",
)
.await
.unwrap();
assert_eq!(
read_head(&fs, Path::new("/wt")).await,
Some(Head {
branch: None,
linked: true
})
);
fs.write_str(Path::new("/sub/.git"), "gitdir: ../repo/.git\n")
.await
.unwrap();
assert_eq!(
read_head(&fs, Path::new("/sub"))
.await
.and_then(|h| h.branch),
Some("feature/x".into())
);
fs.create_dir_all(Path::new("/plain")).await.unwrap();
assert_eq!(read_head(&fs, Path::new("/plain")).await, None);
}
#[tokio::test]
async fn a_helper_is_not_given_the_engines_git_options() {
let process = ScriptedProcess::new().with("pdftotext a.pdf -", ScriptedRun::ok("text"));
let engine = EngineExec::new(
with_process(process),
Confinement::Unconfined,
ProjectTrust::Trusted,
);
let out = engine
.helper(
ProcessSpec::new("pdftotext", "/").args(["a.pdf", "-"]),
&[],
DEADLINE,
)
.await
.unwrap();
assert_eq!(out.stdout_lossy(), "text");
}
}