ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
use std::borrow::Cow;

use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
use serde::{Deserialize, Serialize};

/// Parsed domain code that an application may translate at its UI boundary.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub struct AuthMessageKey(Cow<'static, str>);

impl AuthMessageKey {
    /// Parses and validates a message key string.
    pub fn parse(raw: &str, field: &'static str) -> ParseResult<Self> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return Err(ParseError::for_field(field, ParseErrorCode::Required));
        }

        if !is_valid_message_key(trimmed) {
            return Err(ParseError::for_field(field, ParseErrorCode::InvalidFormat)
                .with_parameter("expected", "domain_code"));
        }

        Ok(Self(Cow::Owned(trimmed.to_string())))
    }

    /// Builds a message key from a static string literal.
    pub fn new_static(key: &'static str) -> Self {
        Self::parse(key, "auth_message_key").expect("invalid message key")
    }

    /// Returns the underlying key string.
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

impl TryFrom<String> for AuthMessageKey {
    type Error = ParseError;

    fn try_from(value: String) -> ParseResult<Self> {
        Self::parse(&value, "auth_message_key")
    }
}

/// Structured argument supplied to a localized message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthMessageArg {
    name: Cow<'static, str>,
    value: Cow<'static, str>,
}

impl AuthMessageArg {
    /// Creates a new message argument from the provided name and value.
    pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }

    /// Returns the argument name.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    /// Returns the argument value.
    pub fn value(&self) -> &str {
        self.value.as_ref()
    }
}

/// Message descriptor that can be translated by the host application.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthMessage {
    key: AuthMessageKey,
    args: Vec<AuthMessageArg>,
}

impl AuthMessage {
    /// Creates a new message from the provided key.
    pub fn new(key: AuthMessageKey) -> Self {
        Self {
            key,
            args: Vec::new(),
        }
    }

    /// Creates a new message from a static key literal.
    pub fn from_static(key: &'static str) -> Self {
        Self::new(AuthMessageKey::new_static(key))
    }

    /// Adds an argument to the message.
    pub fn with_arg(
        mut self,
        name: impl Into<Cow<'static, str>>,
        value: impl Into<Cow<'static, str>>,
    ) -> Self {
        self.args.push(AuthMessageArg::new(name, value));
        self
    }

    /// Returns the message key.
    pub fn key(&self) -> &AuthMessageKey {
        &self.key
    }

    /// Returns the message arguments.
    pub fn args(&self) -> &[AuthMessageArg] {
        &self.args
    }
}

pub(crate) fn is_valid_message_key(value: &str) -> bool {
    value.chars().all(|ch| {
        ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == '_' || ch == '-'
    })
}

#[cfg(test)]
mod tests {
    use super::AuthMessageKey;

    #[test]
    fn deserialization_uses_the_message_key_parser() {
        for invalid in [
            "",
            "  ",
            "bad key",
            "INVALID",
            "auth.login\nforged",
            "auth.ΓΌ",
        ] {
            assert!(AuthMessageKey::parse(invalid, "key").is_err());
            let input = serde_json::to_string(invalid).unwrap();
            assert!(serde_json::from_str::<AuthMessageKey>(&input).is_err());
        }
        let key: AuthMessageKey = serde_json::from_str("\" auth.login.success \"").unwrap();
        assert_eq!(key.as_str(), "auth.login.success");
        assert_eq!(
            serde_json::to_string(&key).unwrap(),
            "\"auth.login.success\""
        );
    }
}