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};

use crate::messages::{AuthMessage, AuthMessageKey, is_valid_message_key};

const AUTH_DENY_KEY_PREFIX: &str = "auth.access.denied.";

/// Describes whether an account is allowed to authenticate.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthDecision {
    /// Account may authenticate and use protected routes.
    Allow,
    /// Account must not authenticate because of the supplied reason.
    Deny(AuthDenyReason),
}

impl AuthDecision {
    /// Returns `true` when the decision allows authentication.
    pub fn is_allowed(&self) -> bool {
        matches!(self, Self::Allow)
    }

    /// Builds an allow decision.
    pub fn allow() -> Self {
        Self::Allow
    }

    /// Builds a deny decision with the supplied reason.
    pub fn deny(reason: AuthDenyReason) -> Self {
        Self::Deny(reason)
    }
}

/// Enumerates standard denial reasons shared across apps.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthDenyCode {
    /// Account is inactive and cannot authenticate.
    Inactive,
    /// Account is blocked from authenticating.
    Blocked,
}

/// Parsed identifier for custom denial reasons.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AuthDenyKey(Cow<'static, str>);

impl AuthDenyKey {
    /// Parses and validates a custom denial key.
    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 !trimmed.starts_with(AUTH_DENY_KEY_PREFIX) || !is_valid_message_key(trimmed) {
            return Err(ParseError::for_field(field, ParseErrorCode::InvalidFormat)
                .with_parameter("expected", AUTH_DENY_KEY_PREFIX));
        }

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

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

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

impl Serialize for AuthDenyKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for AuthDenyKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        AuthDenyKey::parse(raw.as_str(), "auth_deny_key")
            .map_err(|error| serde::de::Error::custom(error.to_string()))
    }
}

/// Describes why authentication is denied.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
pub enum AuthDenyReason {
    /// Shared denial reason across all apps.
    Standard(AuthDenyCode),
    /// Application-defined denial reason represented by a stable domain code.
    Custom(AuthDenyKey),
}

impl AuthDenyReason {
    /// Returns a denial reason for inactive accounts.
    pub fn inactive() -> Self {
        Self::Standard(AuthDenyCode::Inactive)
    }

    /// Returns a denial reason for blocked accounts.
    pub fn blocked() -> Self {
        Self::Standard(AuthDenyCode::Blocked)
    }

    /// Returns a denial reason backed by a custom key.
    pub fn custom(key: AuthDenyKey) -> Self {
        Self::Custom(key)
    }
}

/// Returns the message descriptor for a denial reason.
pub fn auth_deny_message(reason: &AuthDenyReason) -> AuthMessage {
    match reason {
        AuthDenyReason::Standard(AuthDenyCode::Inactive) => {
            AuthMessage::from_static("auth.access.denied.inactive")
        }
        AuthDenyReason::Standard(AuthDenyCode::Blocked) => {
            AuthMessage::from_static("auth.access.denied.blocked")
        }
        AuthDenyReason::Custom(key) => AuthMessage::new(message_key_from_deny_key(key)),
    }
}

/// Converts a validated denial key into a message key.
fn message_key_from_deny_key(key: &AuthDenyKey) -> AuthMessageKey {
    AuthMessageKey::parse(key.as_str(), "auth_deny_key").expect("invalid auth deny key")
}

#[cfg(test)]
mod tests {
    use super::{AuthDenyKey, AuthDenyReason};

    #[test]
    fn parses_valid_deny_keys() {
        let key = AuthDenyKey::parse("auth.access.denied.deactivated", "key").expect("valid key");
        assert_eq!(key.as_str(), "auth.access.denied.deactivated");
    }

    #[test]
    fn rejects_invalid_deny_keys() {
        assert!(AuthDenyKey::parse("invalid key", "key").is_err());
        assert!(AuthDenyKey::parse("auth.denied.bad", "key").is_err());
    }

    #[test]
    fn matches_custom_deny_reasons() {
        let key = AuthDenyKey::new_static("auth.access.denied.deactivated");
        let reason = AuthDenyReason::custom(key);
        match reason {
            AuthDenyReason::Custom(custom) => {
                assert_eq!(custom.as_str(), "auth.access.denied.deactivated");
            }
            _ => panic!("expected custom deny reason"),
        }
    }
}