pegase 0.2.0

Cli to generate secret config files from yaml recipe
Documentation
use std::fmt::Display;

use enum_dispatch::enum_dispatch;
use garde::Validate;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use crate::internal::secrets::InternalError;

pub mod hash;
pub mod pass;
pub mod ssh;

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(untagged)]
pub enum Secret {
    Asym {
        private: Zeroizing<String>,
        public: String,
    },
    Hash {
        plain: Zeroizing<String>,
        hash: String,
    },
    String(Zeroizing<String>),
}

#[derive(Debug, PartialEq)]
pub enum GenerationError {
    InternalError(String),
    InvalidConfig(Vec<(String, String)>),
}

impl From<InternalError> for GenerationError {
    fn from(value: InternalError) -> Self {
        GenerationError::InternalError(format!("{value}"))
    }
}

impl From<garde::error::Report> for GenerationError {
    fn from(err: garde::error::Report) -> Self {
        GenerationError::InvalidConfig(
            err.iter()
                .map(|(path, error)| (path.to_string(), error.to_string()))
                .collect(),
        )
    }
}

impl Display for GenerationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GenerationError::InternalError(err) => write!(f, "Internal error: {err}"),
            GenerationError::InvalidConfig(err) => {
                write!(f, "Invalid config:")?;
                for (path, msg) in err {
                    write!(f, "\t{path}: {msg}")?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for GenerationError {}

#[enum_dispatch(SecretGenerator)]
pub trait GenerateSecret {
    fn generate(&self) -> Result<Secret, GenerationError>;
}

#[enum_dispatch]
#[derive(Debug, Serialize, Deserialize, Validate, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "generator")]
pub enum SecretGenerator {
    Pass(#[garde(dive)] pass::PassSecretGenerator),
    Ssh(#[garde(dive)] ssh::SshSecretGenerator),
    Hash(#[garde(dive)] hash::HashSecretGenerator),
}