pegase 0.2.0

Cli to generate secret config files from yaml recipe
Documentation
use std::{
    collections::{BTreeMap, VecDeque},
    vec,
};

use garde::Validate;
use serde::{Deserialize, Deserializer, Serialize, de};
use serde_value::Value;

use crate::{
    generators::{GenerateSecret, GenerationError, Secret, SecretGenerator},
    internal::garde::{dive_btreemap_values, dive_vec},
};

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum SecretTree {
    Secret(Secret),
    List(Vec<SecretTree>),
    Map(BTreeMap<String, SecretTree>),
}

impl SecretTree {
    pub fn secret(&self) -> Option<&Secret> {
        if let Self::Secret(secret) = self {
            Some(secret)
        } else {
            None
        }
    }

    pub fn list(&self) -> Option<&Vec<SecretTree>> {
        if let Self::List(list) = self {
            Some(list)
        } else {
            None
        }
    }

    pub fn map(&self) -> Option<&BTreeMap<String, SecretTree>> {
        if let Self::Map(map) = self {
            Some(map)
        } else {
            None
        }
    }

    pub fn get_by_id(&self, id: &str) -> Option<SecretTree> {
        self.get_by_id_list(id.split(".").collect())
    }

    pub fn get_by_id_list(&self, mut id: VecDeque<&str>) -> Option<SecretTree> {
        if id.is_empty() {
            return Some(self.clone());
        }

        match self {
            SecretTree::Secret(Secret::String(_)) => None,
            SecretTree::Secret(Secret::Asym { private, public }) => {
                if id == vec!["private"] {
                    Some(Self::Secret(Secret::String(private.clone())))
                } else if id == vec!["public"] {
                    Some(Self::Secret(Secret::String(public.clone().into())))
                } else {
                    None
                }
            }
            SecretTree::Secret(Secret::Hash { plain, hash }) => {
                if id == vec!["plain"] {
                    Some(Self::Secret(Secret::String(plain.clone())))
                } else if id == vec!["hash"] {
                    Some(Self::Secret(Secret::String(hash.clone().into())))
                } else {
                    None
                }
            }
            SecretTree::List(secret_trees) => {
                let index: usize = id.pop_front()?.parse().ok()?;
                secret_trees.get(index)?.get_by_id_list(id)
            }
            SecretTree::Map(btree_map) => {
                let index = id.pop_front()?;
                btree_map.get(index)?.get_by_id_list(id)
            }
        }
    }
}

#[derive(Debug, Serialize, Validate, PartialEq, Clone)]
#[serde(untagged)]
pub enum GeneratorTree {
    List(#[garde(custom(dive_vec))] Vec<GeneratorTree>),
    Map(#[garde(custom(dive_btreemap_values))] BTreeMap<String, GeneratorTree>),
    Generator(#[garde(dive)] SecretGenerator),
}

impl Default for GeneratorTree {
    fn default() -> Self {
        Self::List(vec![])
    }
}

impl<'de> Deserialize<'de> for GeneratorTree {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Value::deserialize(deserializer)? {
            Value::String(value) => {
                let mut mapping = BTreeMap::new();
                mapping.insert(Value::String("generator".to_string()), Value::String(value));

                SecretGenerator::deserialize(Value::Map(mapping))
                    .map(GeneratorTree::Generator)
                    .map_err(de::Error::custom)
            }
            Value::Seq(value) => Vec::<GeneratorTree>::deserialize(Value::Seq(value))
                .map(GeneratorTree::List)
                .map_err(de::Error::custom),
            Value::Map(value) => {
                if value.contains_key(&Value::String("generator".to_string())) {
                    SecretGenerator::deserialize(Value::Map(value))
                        .map(GeneratorTree::Generator)
                        .map_err(de::Error::custom)
                } else {
                    BTreeMap::<String, GeneratorTree>::deserialize(Value::Map(value))
                        .map(GeneratorTree::Map)
                        .map_err(de::Error::custom)
                }
            }

            Value::Bool(value) => Err(de::Error::custom(format!(
                "invalid type: boolean `{value}`, expected a sequence, a map or a string"
            ))),

            Value::U8(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U16(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U32(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U64(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),

            Value::I8(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I16(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I32(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I64(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),

            Value::F32(value) => Err(de::Error::custom(format!(
                "invalid type: float `{value}`, expected a sequence, a map or a string"
            ))),
            Value::F64(value) => Err(de::Error::custom(format!(
                "invalid type: float `{value}`, expected a sequence, a map or a string"
            ))),

            Value::Char(value) => Err(de::Error::custom(format!(
                "invalid type: char `{value}`, expected a sequence, a map or a string"
            ))),

            Value::Unit => Err(de::Error::custom(
                "invalid type: unit value, expected a sequence, a map or a string",
            )),
            Value::Option(value) => Err(de::Error::custom(format!(
                "invalid type: option `{value:?}`, expected a sequence, a map or a string"
            ))),
            Value::Newtype(value) => Err(de::Error::custom(format!(
                "invalid type: newtype `{value:?}`, expected a sequence, a map or a string"
            ))),
            Value::Bytes(value) => Err(de::Error::custom(format!(
                "invalid type: bytes `{value:?}`, expected a sequence, a map or a string"
            ))),
        }
    }
}

impl GeneratorTree {
    pub fn generate(&self) -> Result<SecretTree, GenerationError> {
        match self {
            GeneratorTree::List(generator_list) => Ok(SecretTree::List(
                generator_list
                    .iter()
                    .map(|generator| generator.generate())
                    .collect::<Result<Vec<_>, _>>()?,
            )),
            GeneratorTree::Map(generator_map) => Ok(SecretTree::Map(
                generator_map
                    .iter()
                    .map(|(key, generator)| {
                        Ok::<(String, SecretTree), GenerationError>((
                            key.clone(),
                            generator.generate()?,
                        ))
                    })
                    .collect::<Result<BTreeMap<_, _>, _>>()?,
            )),
            GeneratorTree::Generator(generator) => Ok(SecretTree::Secret(generator.generate()?)),
        }
    }
}

#[derive(Debug, Serialize, Validate, PartialEq, Clone)]
pub enum GeneratorTreeWithRef {
    List(#[garde(custom(dive_vec))] Vec<GeneratorTreeWithRef>),
    Map(#[garde(custom(dive_btreemap_values))] BTreeMap<String, GeneratorTreeWithRef>),
    Generator(#[garde(dive)] SecretGenerator),
    Ref(#[garde(skip)] String),
}

impl<'de> Deserialize<'de> for GeneratorTreeWithRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Value::deserialize(deserializer)? {
            Value::String(value) => {
                let mut mapping = BTreeMap::new();
                mapping.insert(Value::String("generator".to_string()), Value::String(value));

                SecretGenerator::deserialize(Value::Map(mapping))
                    .map(GeneratorTreeWithRef::Generator)
                    .map_err(de::Error::custom)
            }
            Value::Seq(value) => Vec::<GeneratorTreeWithRef>::deserialize(Value::Seq(value))
                .map(GeneratorTreeWithRef::List)
                .map_err(de::Error::custom),
            Value::Map(value) => {
                if let Some(ref_str) = value.get(&Value::String("ref".to_string())) {
                    let other_keys = value
                        .keys()
                        .filter(|key| **key != Value::String("ref".to_string()));

                    if other_keys.clone().next().is_some() {
                        return Err(de::Error::custom(format!(
                            "unknown keys: `{:?}`",
                            other_keys.collect::<Vec<_>>()
                        )));
                    }

                    String::deserialize(ref_str.clone())
                        .map(GeneratorTreeWithRef::Ref)
                        .map_err(de::Error::custom)
                } else if value.contains_key(&Value::String("generator".to_string())) {
                    SecretGenerator::deserialize(Value::Map(value))
                        .map(GeneratorTreeWithRef::Generator)
                        .map_err(de::Error::custom)
                } else {
                    BTreeMap::<String, GeneratorTreeWithRef>::deserialize(Value::Map(value))
                        .map(GeneratorTreeWithRef::Map)
                        .map_err(de::Error::custom)
                }
            }

            Value::Bool(value) => Err(de::Error::custom(format!(
                "invalid type: boolean `{value}`, expected a sequence, a map or a string"
            ))),

            Value::U8(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U16(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U32(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::U64(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),

            Value::I8(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I16(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I32(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),
            Value::I64(value) => Err(de::Error::custom(format!(
                "invalid type: integer `{value}`, expected a sequence, a map or a string"
            ))),

            Value::F32(value) => Err(de::Error::custom(format!(
                "invalid type: float `{value}`, expected a sequence, a map or a string"
            ))),
            Value::F64(value) => Err(de::Error::custom(format!(
                "invalid type: float `{value}`, expected a sequence, a map or a string"
            ))),

            Value::Char(value) => Err(de::Error::custom(format!(
                "invalid type: char `{value}`, expected a sequence, a map or a string"
            ))),

            Value::Unit => Err(de::Error::custom(
                "invalid type: unit value, expected a sequence, a map or a string",
            )),
            Value::Option(value) => Err(de::Error::custom(format!(
                "invalid type: option `{value:?}`, expected a sequence, a map or a string"
            ))),
            Value::Newtype(value) => Err(de::Error::custom(format!(
                "invalid type: newtype `{value:?}`, expected a sequence, a map or a string"
            ))),
            Value::Bytes(value) => Err(de::Error::custom(format!(
                "invalid type: bytes `{value:?}`, expected a sequence, a map or a string"
            ))),
        }
    }
}

impl GeneratorTreeWithRef {
    pub fn generate(&self, shared_secrets: &SecretTree) -> Result<SecretTree, GenerationError> {
        match self {
            Self::List(generator_list) => Ok(SecretTree::List(
                generator_list
                    .iter()
                    .map(|generator| generator.generate(shared_secrets))
                    .collect::<Result<Vec<_>, _>>()?,
            )),
            Self::Map(generator_map) => Ok(SecretTree::Map(
                generator_map
                    .iter()
                    .map(|(key, generator)| {
                        Ok::<(String, SecretTree), GenerationError>((
                            key.clone(),
                            generator.generate(shared_secrets)?,
                        ))
                    })
                    .collect::<Result<BTreeMap<_, _>, _>>()?,
            )),
            Self::Generator(generator) => Ok(SecretTree::Secret(generator.generate()?)),
            GeneratorTreeWithRef::Ref(id) => {
                Ok(shared_secrets
                    .get_by_id(id)
                    .ok_or(GenerationError::InvalidConfig(vec![(
                        id.clone(),
                        "unknown ref".to_string(),
                    )]))?)
            }
        }
    }
}