git.delta.rocks / jrsonnet / refs/commits / 453e81eb3dff

difftreelog

source

cmds/fleet/src/keys.rs1.9 KiBsourcehistory
1use std::str::FromStr;23use age::Recipient;4use anyhow::{anyhow, Result};5use futures::{StreamExt, TryStreamExt};6use itertools::Itertools;7use tracing::warn;89use crate::host::Config;1011impl Config {12	pub fn cached_key(&self, host: &str) -> Option<String> {13		let data = self.data();14		let key = data.hosts.get(host).map(|h| &h.encryption_key);15		if let Some(key) = key {16			if key.is_empty() {17				return None;18			}19		}20		key.cloned()21	}22	pub fn update_key(&self, host: &str, key: String) {23		let mut data = self.data_mut();24		let host = data.hosts.entry(host.to_string()).or_default();25		host.encryption_key = key.trim().to_string();26	}2728	pub async fn key(&self, host: &str) -> anyhow::Result<String> {29		if let Some(key) = self.cached_key(host) {30			Ok(key)31		} else {32			warn!("Loading key for {}", host);33			let host = self.host(host).await?;34			let mut cmd = host.cmd("cat").await?;35			cmd.arg("/etc/ssh/ssh_host_ed25519_key.pub");36			let key = cmd.run_string().await?;37			self.update_key(&host.name, key.clone());38			Ok(key)39		}40	}41	/// Insecure, requires root42	pub async fn recipient(&self, host: &str) -> anyhow::Result<impl Recipient> {43		let key = self.key(host).await?;44		age::ssh::Recipient::from_str(&key).map_err(|e| anyhow!("parse recipient error: {:?}", e))45	}4647	pub async fn recipients(&self, hosts: Vec<String>) -> Result<Vec<impl Recipient>> {48		futures::stream::iter(hosts.iter())49			.then(|m| self.recipient(m.as_ref()))50			.try_collect::<Vec<_>>()51			.await52	}5354	#[allow(dead_code)]55	pub async fn orphaned_data(&self) -> Result<Vec<String>> {56		let mut out = Vec::new();57		let host_names = self58			.list_hosts()59			.await?60			.into_iter()61			.map(|h| h.name)62			.collect_vec();63		for hostname in self64			.data()65			.hosts66			.iter()67			.filter(|(_, host)| !host.encryption_key.is_empty())68			.map(|(n, _)| n)69		{70			if !host_names.contains(hostname) {71				out.push(hostname.to_owned())72			}73		}7475		Ok(out)76	}77}