use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context as _, Result};
use openmoat_core::Policy;
use openmoat_core::mint::Helper;
use crate::home::write_private;
use crate::sandbox::git_env::{self, Lookup};
const AWS_REMOVED: [&str; 4] = [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_DEFAULT_PROFILE",
];
#[derive(Debug, Default)]
pub struct Helpers {
dir: Option<PathBuf>,
vars: Vec<(String, String)>,
removed: Vec<&'static str>,
}
fn quoted(text: &str) -> String {
format!("'{}'", text.replace('\'', r"'\''"))
}
pub fn git_entries(policy: &Policy, moat: &str) -> Vec<(String, String)> {
policy
.secrets
.iter()
.filter(|s| matches!(s.helper, Some(Helper::Git { .. })))
.flat_map(|s| {
let key = format!("credential.https://{}.helper", s.host);
let helper = format!("!{} credential git {}", quoted(moat), quoted(&s.id));
[(key.clone(), String::new()), (key, helper)]
})
.collect()
}
pub fn aws_config(policy: &Policy, moat: &str) -> Option<(String, Option<String>)> {
let ids: Vec<&str> = policy
.secrets
.iter()
.filter(|s| s.helper == Some(Helper::Aws))
.map(|s| s.id.as_str())
.collect();
let mut text = String::from("# Written by `openmoat run` for this run only (ADR-118).\n");
for id in &ids {
let _ = write!(
text,
"[profile openmoat-{id}]\ncredential_process = \"{moat}\" credential aws {id}\n"
);
}
match ids.as_slice() {
[] => None,
[one] => Some((text, Some(format!("openmoat-{one}")))),
_ => Some((text, None)),
}
}
impl Helpers {
pub fn for_run(
policy: &Policy,
run_temp: Option<String>,
git: &[(String, String)],
) -> Result<Self> {
let temp = match run_temp {
Some(temp) => PathBuf::from(temp),
None => std::fs::canonicalize(std::env::temp_dir())
.context("resolving the temp directory for the credential helpers")?,
};
let lookup = |var: &str| {
git.iter()
.find(|(name, _)| name == var)
.map(|(_, value)| value.clone())
.or_else(|| std::env::var(var).ok())
};
Self::prepare(policy, &temp, &lookup)
}
pub fn prepare(policy: &Policy, temp: &Path, git: Lookup) -> Result<Self> {
let has_helper = policy.secrets.iter().any(|s| s.helper.is_some());
if !has_helper {
return Ok(Self::default());
}
let moat = std::env::current_exe()
.and_then(std::fs::canonicalize)
.context("locating the openmoat binary for the credential helpers")?;
let moat = crate::context::path_string(&moat);
let mut helpers = Self {
dir: None,
vars: git_env::append(git, git_entries(policy, &moat))?,
removed: Vec::new(),
};
if let Some((config, profile)) = aws_config(policy, &moat) {
let dir = temp.join(format!("moat-run-{}-helpers", std::process::id()));
let config_file = dir.join("aws-config");
let credentials_file = dir.join("aws-credentials");
helpers.dir = Some(dir);
write_private(&config_file, config.as_bytes())?;
write_private(&credentials_file, b"")?;
let path = |p: &Path| crate::context::path_string(p);
helpers
.vars
.push(("AWS_CONFIG_FILE".into(), path(&config_file)));
helpers.vars.push((
"AWS_SHARED_CREDENTIALS_FILE".into(),
path(&credentials_file),
));
match profile {
Some(profile) => helpers.vars.push(("AWS_PROFILE".into(), profile)),
None => helpers.removed.push("AWS_PROFILE"),
}
helpers.removed.extend(AWS_REMOVED);
}
Ok(helpers)
}
pub fn dir(&self) -> Option<String> {
self.dir.as_deref().map(crate::context::path_string)
}
pub fn apply(&self, command: &mut Command) {
for name in &self.removed {
command.env_remove(name);
}
command.envs(self.vars.iter().map(|(k, v)| (k, v)));
}
}
impl Drop for Helpers {
fn drop(&mut self) {
if let Some(dir) = &self.dir {
let _ = std::fs::remove_dir_all(dir);
}
}
}
#[cfg(test)]
mod tests;