use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::time::Duration;
use openmoat_core::{Policy, SecretCommand};
use super::Place;
use super::command::Program;
const LIMIT: Duration = Duration::from_secs(10);
pub fn scratch() -> tempfile::TempDir {
let exe = std::env::current_exe().unwrap();
tempfile::Builder::new()
.prefix("cmd-source-")
.tempdir_in(exe.parent().unwrap())
.unwrap()
}
pub struct Stand {
_dir: tempfile::TempDir,
pub root: String,
state: tempfile::TempDir,
pub policy: Policy,
}
impl Stand {
pub fn new() -> Self {
let dir = scratch();
let root = std::fs::canonicalize(dir.path())
.unwrap()
.to_string_lossy()
.into_owned();
let policy = Policy::parse(&format!(
"version: 1\ndeny:\n - id: credential-programs\n fs.write: ['{root}/**']\n"
))
.unwrap();
Self {
_dir: dir,
root,
state: scratch(),
policy,
}
}
pub fn place(&self) -> Place<'_> {
Place {
home: &self.root,
state: self.state.path(),
writable: &[],
}
}
pub fn state(&self) -> &Path {
self.state.path()
}
pub fn script(&self, name: &str, body: &str) -> PathBuf {
let path = Path::new(&self.root).join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
pub fn source(run: &[&str]) -> SecretCommand {
SecretCommand {
run: run.iter().map(|w| (*w).to_owned()).collect(),
lifetime: "15m".into(),
refresh_before: None,
home: openmoat_core::SecretCommandHome::Private,
}
}
pub fn program(&self, path: &Path, policy: &Policy) -> anyhow::Result<Program> {
let path = path.to_string_lossy();
Program::prepare(
"t",
&Self::source(&[&path, "--print"]),
policy,
&self.place(),
)
.map(|p| p.with_time_limit(LIMIT))
}
pub fn shell(&self, body: &str) -> Program {
self.shell_with(&Self::source(&["/bin/sh", "-c", body, "sh", "--print"]))
}
pub fn shell_with(&self, source: &SecretCommand) -> Program {
let open = Policy::parse("version: 1\n").unwrap();
Program::prepare("t", source, &open, &self.place())
.unwrap()
.with_time_limit(LIMIT)
}
}