use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use isoloom_manifest::{Delivery, SecretSlot};
use crate::Result;
use crate::error::Error;
use crate::executor::{Cx, Echo, call, slot_value, stdout_of};
use crate::ssh::{self, Login};
use crate::store::Transient;
use isoloom_manifest::contract::{DELIVERED, SECRETS_DIR};
fn receive() -> String {
format!(
"set -e; umask 077; d={SECRETS_DIR}; mkdir -p \"$d\"; chmod 700 \"$d\"; \
while read -r n v; do case \"$n\" in ''|*[!A-Za-z0-9_-]*) echo \"isothrum: a secret's name is refused\" >&2; exit 2;; esac; \
printf %s \"$v\" | base64 -d > \"$d/$n.new\"; mv -f \"$d/$n.new\" \"$d/$n\"; done; touch {DELIVERED}"
)
}
const PATIENCE: Duration = Duration::from_secs(900);
const TRY_LIMIT: Duration = Duration::from_secs(120);
pub(crate) async fn deliver(cx: &mut Cx<'_>, after: Option<&str>) -> Result<()> {
let mut by_machine = due(cx, after);
by_machine.retain(|machine, _| !cx.set_up.contains(machine));
if by_machine.is_empty() {
return Ok(());
}
let outputs = cx.run.read_outputs(cx).await?.values;
let output = |name: &str| outputs.iter().find(|o| o.name == name).and_then(|o| o.revealed().map(str::to_owned));
for (machine, lines) in by_machine {
let login = ssh::machine_login(output, &machine, cx.ssh_jump.as_deref())?.ok_or_else(|| Error::Malformed {
at: format!("the guest delivery to `{machine}`"),
reason: format!("no `{}` output gives the machine's address", ssh::address_output(&machine)),
})?;
to_machine(cx, &machine, &login, &lines).await?;
}
Ok(())
}
fn due(cx: &Cx<'_>, after: Option<&str>) -> BTreeMap<String, String> {
due_lines(&cx.run.manifest().secrets, |slot| slot_value(cx, slot), after)
}
fn due_lines<'a>(slots: &'a [SecretSlot], value: impl Fn(&'a SecretSlot) -> Option<&'a str>, after: Option<&str>) -> BTreeMap<String, String> {
let mut out: BTreeMap<String, String> = BTreeMap::new();
for slot in slots {
let value = value(slot);
for d in &slot.deliver {
let Delivery::Guest { machine, during_step, .. } = d else {
continue;
};
if during_step.as_ref().map(isoloom_manifest::StepId::as_str) != after {
continue;
}
let lines = out.entry(machine.to_string()).or_default();
let Some(v) = value else { continue };
let encoded = crate::encoding::base64(v.as_bytes());
lines.push_str(slot.name.as_str());
lines.push(' ');
lines.push_str(&encoded);
lines.push('\n');
}
}
out
}
async fn to_machine(cx: &Cx<'_>, machine: &str, login: &Login, lines: &str) -> Result<()> {
let id = format!("guest-{machine}");
let note = format!("Delivering {machine}'s secrets…");
cx.events
.stepped(&id, Some(¬e), async {
let input = Transient::write(cx.state_dir().join(format!("{id}.in")), lines.as_bytes(), "a guest delivery's input file")?;
let done = deliver_retrying(cx, &id, login, input.path()).await;
input.remove_after(done)
})
.await
}
async fn deliver_retrying(cx: &Cx<'_>, id: &str, login: &Login, input: &Path) -> Result<()> {
let mut spec = ssh::spec(cx, login, &format!("sudo sh -c {}", crate::console::sh_quote(&receive())), Vec::new())?;
spec.stdin = Some(input.to_path_buf());
let wait = ssh::Wait {
limit: PATIENCE,
login: login.target.clone(),
};
let mut retrying = ssh::Retrying::new(&wait);
let out = loop {
let out = call(cx, id, &spec, TRY_LIMIT, Echo::Quiet).await?;
if !retrying.again(ssh::Try::unreachable(&out), || {}).await {
break out;
}
};
let out = retrying.answered(cx, id, out)?;
stdout_of(cx, id, None, &out).map(drop)
}
#[cfg(test)]
mod tests {
use super::due_lines;
fn slots() -> Vec<isoloom_manifest::SecretSlot> {
crate::testing::solo_web_aws_manifest().secrets
}
#[test]
fn a_given_value_goes_to_its_machine_in_base64() {
let due = due_lines(&slots(), |s| (s.name.as_str() == "DEMO_SECRET").then_some("token-x"), None);
assert_eq!(due["web"], format!("DEMO_SECRET {}\n", crate::encoding::base64(b"token-x")));
}
#[test]
fn a_machine_whose_values_are_all_unset_still_gets_its_delivery() {
let due = due_lines(&slots(), |_| None, None);
assert_eq!(due.get("web").map(String::as_str), Some(""));
}
#[test]
fn a_delivery_waits_for_its_step() {
assert!(due_lines(&slots(), |_| Some("x"), Some("some-step")).is_empty());
}
}