pegase 0.2.0

Cli to generate secret config files from yaml recipe
Documentation
use std::collections::BTreeMap;

use garde::{Report, Validate};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    generators::{GenerateSecret, GenerationError, Secret},
    internal::secrets::{ed25519::Ed25519, rsa::Rsa},
};

#[derive(Debug, Serialize, Deserialize, Clone, Validate, PartialEq)]
pub struct SshKeySize(#[garde(range(min = 2048))] pub usize);

impl Default for SshKeySize {
    fn default() -> Self {
        Self(4096)
    }
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Validate, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "kind")]
pub enum SshKeyKind {
    Rsa {
        #[garde(dive)]
        bits: Option<SshKeySize>,
    },
    #[default]
    Ed25519,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Validate, PartialEq)]
#[serde(try_from = "SshSecretGeneratorConfigDeserializeWith")]
pub struct SshSecretGeneratorConfig {
    #[garde(dive)]
    pub kind: Option<SshKeyKind>,
    #[garde(skip)]
    pub comment: Option<String>,
}

/* #region absolute horror */
/*
   `#[serde(deny_unknown_fields)]` does not support `#[serde(flatten)]` so a way to achieve a
   similar result is to add an `other` field that contains all remaining fields and check if this
   field is empty
*/

#[derive(Deserialize, Default, Clone, Debug, Validate)]
struct SshSecretGeneratorConfigDeserializeWith {
    #[serde(flatten)]
    #[garde(dive)]
    kind: Option<SshKeyKind>,
    #[garde(skip)]
    comment: Option<String>,
    #[serde(flatten)]
    #[garde(skip)]
    other: BTreeMap<String, serde_value::Value>,
}

#[derive(Debug, Error)]
pub enum ParsingError {
    #[error("Unknown field: {0}")]
    UnknownField(String),
    #[error("Value error: {0}")]
    ValueError(#[from] Report),
}

impl TryFrom<SshSecretGeneratorConfigDeserializeWith> for SshSecretGeneratorConfig {
    type Error = ParsingError;

    fn try_from(
        value: SshSecretGeneratorConfigDeserializeWith,
    ) -> Result<SshSecretGeneratorConfig, ParsingError> {
        let mut other_keys = value.other.clone();

        /* #region absolute horror - the return */
        /*
           There is an issue with `#[serde(tag)]` and `#[serde(flatten)]`, the fields of the tagged
           enums are duplicated inside the `other` map so they need to be removed to check if there
           are unknown fields
        */

        match &value.kind {
            // Some(Rsa({bits: Some(bits)})) => todo!(),
            Some(SshKeyKind::Rsa { bits: Some(_) }) => {
                other_keys.remove("kind");
                other_keys.remove("bits");
            }
            Some(SshKeyKind::Rsa { bits: None }) => {
                other_keys.remove("kind");
            }
            Some(SshKeyKind::Ed25519) => {
                other_keys.remove("kind");
            }
            None => (),
        }

        /* #endregion */

        if let Some((key, _)) = other_keys.first_key_value() {
            return Err(ParsingError::UnknownField(format!("{:?}", key)));
        }

        value.validate()?;

        Ok(SshSecretGeneratorConfig {
            kind: value.kind,
            comment: value.comment,
        })
    }
}

/* #endregion */

#[derive(Debug, Serialize, Deserialize, Clone, Default, Validate, PartialEq)]
#[serde(transparent)]
pub struct SshSecretGenerator {
    #[garde(dive)]
    pub config: SshSecretGeneratorConfig,
}

impl GenerateSecret for SshSecretGenerator {
    fn generate(&self) -> Result<Secret, GenerationError> {
        let config = self.config.clone();

        config.validate()?;

        match config.kind.unwrap_or_default() {
            SshKeyKind::Rsa { bits } => {
                let rsa = Rsa::generate(
                    bits.unwrap_or_default().0,
                    config.comment.unwrap_or_default(),
                )?;
                let private = rsa.private_key()?;
                let public = rsa.public_key()?;

                Ok(Secret::Asym { private, public })
            }
            SshKeyKind::Ed25519 => {
                let ed25519 = Ed25519::generate(config.comment.unwrap_or_default())?;
                let private = ed25519.private_key()?;
                let public = ed25519.public_key()?;

                Ok(Secret::Asym { private, public })
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use ssh_key::{PrivateKey, PublicKey};

    use super::{SshKeyKind, SshKeySize, SshSecretGenerator, SshSecretGeneratorConfig};
    use crate::generators::{GenerateSecret, Secret};

    #[test]
    fn check_ed25519() {
        let generator = SshSecretGenerator {
            config: SshSecretGeneratorConfig {
                kind: Some(SshKeyKind::Ed25519),
                comment: Some("My beautifull ed25519 key".to_string()),
            },
        };

        let secret = generator.generate().unwrap();

        if let Secret::Asym { private, public } = secret {
            let private_key = PrivateKey::from_openssh(private).unwrap();
            let public_key = PublicKey::from_openssh(&public).unwrap();

            assert_eq!(private_key.public_key(), &public_key);
            assert!(private_key.algorithm().is_ed25519());
            assert_eq!(
                public_key.comment().as_str().unwrap(),
                "My beautifull ed25519 key"
            );
        } else {
            panic!("expected asym, got {secret:?}")
        }
    }

    #[test]
    fn check_rsa() {
        for bits in [2048usize, 3072, 4096, 2056] {
            let generator = SshSecretGenerator {
                config: SshSecretGeneratorConfig {
                    kind: Some(SshKeyKind::Rsa {
                        bits: Some(SshKeySize(bits)),
                    }),
                    comment: Some("My beautifull rsa key".to_string()),
                },
            };

            let secret = generator.generate().unwrap();

            if let Secret::Asym { private, public } = secret {
                let private_key = PrivateKey::from_openssh(private).unwrap();
                let public_key = PublicKey::from_openssh(&public).unwrap();

                assert_eq!(private_key.public_key(), &public_key);
                assert!(private_key.algorithm().is_rsa());
                assert_eq!(
                    public_key
                        .key_data()
                        .rsa()
                        .unwrap()
                        .n()
                        .as_positive_bytes()
                        .unwrap()
                        .len()
                        * 8,
                    bits
                );
                assert_eq!(
                    public_key.comment().as_str().unwrap(),
                    "My beautifull rsa key"
                );
            } else {
                panic!("expected asym, got {secret:?}")
            }
        }
    }
}