git.delta.rocks / jrsonnet / refs/commits / b05f31720fbc

difftreelog

source

src/db/keys.rs1.3 KiBsourcehistory
1use std::{collections::BTreeMap, process::Command};23use anyhow::Result;4use log::*;56use crate::{command::CommandExt, nix::HOSTS_ATTRIBUTE};78use serde::{Deserialize, Serialize};910use super::db::DbData;1112pub fn list_hosts() -> Result<Vec<String>> {13	Ok(Command::new("nix")14		.inherit_stdio()15		.arg("eval")16		.arg(HOSTS_ATTRIBUTE)17		.arg("--apply")18		.arg("builtins.attrNames")19		.run_json()?)20}2122#[derive(Serialize, Deserialize, Default)]23pub struct KeyDb {24	host_keys: BTreeMap<String, String>,25}26impl DbData for KeyDb {27	const DB_NAME: &'static str = "keys";28}2930impl KeyDb {31	pub fn fetch_key(&mut self, host: &str) -> Result<()> {32		info!("Fetching key for {}", host);33		let key = Command::ssh_on(host, "cat")34			.arg("/etc/ssh/ssh_host_ed25519_key.pub")35			.run_string()?;36		self.host_keys.insert(host.to_owned(), key);37		Ok(())38	}3940	pub fn ensure_key_loaded(&mut self, host: &str, force: bool) -> Result<()> {41		if !self.host_keys.contains_key(host) || force {42			self.fetch_key(host)?;43		}44		Ok(())45	}4647	pub fn get_host_key(&self, host: &str) -> Result<String> {48		Ok(self49			.host_keys50			.get(host)51			.ok_or_else(|| anyhow::anyhow!("no host key for {}", host))?52			.to_owned())53	}5455	pub fn has_key(&self, key: &str) -> bool {56		self.host_keys.contains_key(key)57	}5859	pub fn remove_key(&mut self, host: &str) {60		self.host_keys.remove(host);61	}62}