Move filesystem-related stuff into the config module

This commit is contained in:
Andrey Golovizin 2023-04-15 13:55:25 +02:00
parent a792007abd
commit 10cdbce746
3 changed files with 48 additions and 30 deletions

View file

@ -1,9 +1,6 @@
use base64::prelude::{Engine as _, BASE64_STANDARD};
use log::debug;
use x25519_dalek::{PublicKey, StaticSecret};
use std::{io::Write, path::Path};
use crate::config::MachineConfig;
const KEY_SIZE: usize = 32;
@ -12,7 +9,7 @@ const KEY_SIZE: usize = 32;
pub(crate) struct Key([u8; KEY_SIZE]);
impl Key {
fn try_from_base64(data: &str) -> anyhow::Result<Self> {
pub(crate) fn try_from_base64(data: &str) -> anyhow::Result<Self> {
let mut key_data = [0u8; KEY_SIZE];
let key_bytes = BASE64_STANDARD.decode(data)?;
assert_eq!(key_bytes.len(), KEY_SIZE);
@ -23,17 +20,6 @@ impl Key {
pub(crate) fn to_base64(&self) -> String {
BASE64_STANDARD.encode(self.0)
}
fn load(path: &Path) -> anyhow::Result<Self> {
let key_data = std::fs::read_to_string(path)?;
Self::try_from_base64(key_data.trim_end())
}
fn save(&self, path: &Path) -> anyhow::Result<()> {
let mut file = std::fs::File::create(path)?;
writeln!(file, "{}", self.to_base64())?;
Ok(())
}
}
#[derive(Debug)]
@ -43,14 +29,11 @@ pub(crate) struct WireguardKeyPair {
}
pub(crate) fn get_keys(machine_config: &MachineConfig) -> Result<WireguardKeyPair, anyhow::Error> {
let key_path = machine_config.key_path();
debug!("key path = {:?}", &key_path);
let private_key = if key_path.is_file() {
Key::load(&key_path)?
let private_key = if machine_config.has_key() {
machine_config.key()?
} else {
let key = generate_private_key();
key.save(&key_path)?;
machine_config.save_key(&key)?;
key
};