ch-auth 0.1.2

Authentication and session primitives with explicit security policies
Documentation
use anyhow::Error as AuthError;
use serde::{Deserialize, Serialize};

use crate::messages::AuthMessage;
use crate::status::{AuthDenyReason, auth_deny_message};

/// Enumerates machine-readable login error codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LoginErrorCode {
    /// No error occurred for the outcome.
    #[default]
    None,
    /// Too many attempts were made in a short period.
    RateLimited,
    /// The submitted credentials did not match an account.
    CredentialsInvalid,
    /// The account is not permitted to authenticate.
    AccountDenied,
    /// The account requires a two-factor challenge before login succeeds.
    TwoFactorRequired,
    /// The provided two-factor code was invalid.
    TwoFactorInvalid,
    /// The two-factor challenge expired before completion.
    TwoFactorExpired,
    /// No active two-factor challenge was found for the session.
    TwoFactorMissing,
    /// Two-factor authentication is unavailable for the account.
    TwoFactorUnavailable,
    /// Two-factor authentication is disabled for the account.
    TwoFactorDisabled,
}

/// Styling variants used for the login feedback banner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoginFeedbackVariant {
    /// Successful authentication or completion messages.
    Success,
    /// Informational prompts that require additional user input.
    Info,
    /// Error messages for failed authentication attempts.
    Error,
}

/// Interface for types that can supply login feedback metadata.
pub trait LoginOutcomeFeedback {
    /// Returns whether the authentication succeeded.
    fn success(&self) -> bool;
    /// Returns whether the login requires a two-factor challenge.
    fn requires_two_factor(&self) -> bool;
    /// Returns the machine-readable error code for the outcome.
    fn error_code(&self) -> LoginErrorCode;
    /// Returns the optional UI message attached to the outcome.
    fn message(&self) -> Option<&AuthMessage>;
    /// Returns the optional denial reason when authentication is blocked.
    fn deny_reason(&self) -> Option<&AuthDenyReason>;
}

/// Login feedback messages derived from message keys.
#[derive(Clone, Debug)]
pub struct LoginFeedbackMessages {
    /// Message shown when rate limiting occurs.
    pub rate_limited: AuthMessage,
    /// Message shown when credentials are invalid.
    pub credentials_invalid: AuthMessage,
    /// Message shown when the account is denied without a specific reason.
    pub account_denied: AuthMessage,
    /// Message shown when two-factor is required.
    pub two_factor_required: AuthMessage,
    /// Message shown when a two-factor code is invalid.
    pub two_factor_invalid: AuthMessage,
    /// Message shown when a two-factor session expires.
    pub two_factor_expired: AuthMessage,
    /// Message shown when a two-factor session is missing.
    pub two_factor_missing: AuthMessage,
    /// Message shown when two-factor is unavailable.
    pub two_factor_unavailable: AuthMessage,
    /// Message shown when two-factor is disabled.
    pub two_factor_disabled: AuthMessage,
    /// Message shown when login succeeds.
    pub success: AuthMessage,
}

impl LoginFeedbackMessages {
    /// Builds default login feedback messages from message keys.
    pub fn default_messages() -> Self {
        Self {
            rate_limited: AuthMessage::from_static("auth.login.feedback.rate_limited"),
            credentials_invalid: AuthMessage::from_static(
                "auth.login.feedback.credentials_invalid",
            ),
            account_denied: AuthMessage::from_static("auth.access.denied.unknown"),
            two_factor_required: AuthMessage::from_static(
                "auth.login.feedback.two_factor_required",
            ),
            two_factor_invalid: AuthMessage::from_static("auth.login.feedback.two_factor_invalid"),
            two_factor_expired: AuthMessage::from_static("auth.login.feedback.two_factor_expired"),
            two_factor_missing: AuthMessage::from_static("auth.login.feedback.two_factor_missing"),
            two_factor_unavailable: AuthMessage::from_static(
                "auth.login.feedback.two_factor_unavailable",
            ),
            two_factor_disabled: AuthMessage::from_static(
                "auth.login.feedback.two_factor_disabled",
            ),
            success: AuthMessage::from_static("auth.login.feedback.success"),
        }
    }

    /// Returns stable placeholder feedback messages for tests.
    #[cfg(test)]
    pub(crate) fn test_messages() -> Self {
        Self {
            rate_limited: AuthMessage::from_static("rate_limited"),
            credentials_invalid: AuthMessage::from_static("credentials_invalid"),
            account_denied: AuthMessage::from_static("account_denied"),
            two_factor_required: AuthMessage::from_static("two_factor_required"),
            two_factor_invalid: AuthMessage::from_static("two_factor_invalid"),
            two_factor_expired: AuthMessage::from_static("two_factor_expired"),
            two_factor_missing: AuthMessage::from_static("two_factor_missing"),
            two_factor_unavailable: AuthMessage::from_static("two_factor_unavailable"),
            two_factor_disabled: AuthMessage::from_static("two_factor_disabled"),
            success: AuthMessage::from_static("success"),
        }
    }
}

/// Derives a user-facing feedback message and styling variant from a login outcome.
pub fn derive_login_feedback<T: LoginOutcomeFeedback>(
    outcome: &T,
) -> Option<(AuthMessage, LoginFeedbackVariant)> {
    let messages = LoginFeedbackMessages::default_messages();

    if outcome.error_code() == LoginErrorCode::AccountDenied {
        let variant = if outcome.requires_two_factor() {
            LoginFeedbackVariant::Info
        } else {
            LoginFeedbackVariant::Error
        };

        let message = outcome
            .deny_reason()
            .map(auth_deny_message)
            .unwrap_or_else(|| messages.account_denied.clone());

        return Some((message, variant));
    }

    derive_login_feedback_with_messages(&messages, outcome)
}

/// Derives a user-facing feedback message using prebuilt login feedback messages.
pub fn derive_login_feedback_with_messages<T: LoginOutcomeFeedback>(
    messages: &LoginFeedbackMessages,
    outcome: &T,
) -> Option<(AuthMessage, LoginFeedbackVariant)> {
    if outcome.success() && !outcome.requires_two_factor() {
        return None;
    }

    let variant = if outcome.requires_two_factor() {
        LoginFeedbackVariant::Info
    } else {
        LoginFeedbackVariant::Error
    };

    let message = match outcome.error_code() {
        LoginErrorCode::RateLimited => messages.rate_limited.clone(),
        LoginErrorCode::CredentialsInvalid => messages.credentials_invalid.clone(),
        LoginErrorCode::AccountDenied => messages.account_denied.clone(),
        LoginErrorCode::TwoFactorRequired => messages.two_factor_required.clone(),
        LoginErrorCode::TwoFactorInvalid => messages.two_factor_invalid.clone(),
        LoginErrorCode::TwoFactorExpired => messages.two_factor_expired.clone(),
        LoginErrorCode::TwoFactorMissing => messages.two_factor_missing.clone(),
        LoginErrorCode::TwoFactorUnavailable => messages.two_factor_unavailable.clone(),
        LoginErrorCode::TwoFactorDisabled => messages.two_factor_disabled.clone(),
        LoginErrorCode::None => outcome.message()?.clone(),
    };

    Some((message, variant))
}

/// Maps a login result into a user-facing feedback tuple.
pub fn login_feedback_from_result<T: LoginOutcomeFeedback>(
    result: &Result<T, AuthError>,
) -> Option<(AuthMessage, LoginFeedbackVariant)> {
    let messages = LoginFeedbackMessages::default_messages();
    login_feedback_from_result_with_messages(&messages, result)
}

/// Maps a login result into a feedback tuple using prebuilt messages.
pub fn login_feedback_from_result_with_messages<T: LoginOutcomeFeedback>(
    messages: &LoginFeedbackMessages,
    result: &Result<T, AuthError>,
) -> Option<(AuthMessage, LoginFeedbackVariant)> {
    match result {
        Ok(outcome) => derive_login_feedback_with_messages(messages, outcome),
        Err(_error) => Some((
            AuthMessage::from_static("auth.server_error"),
            LoginFeedbackVariant::Error,
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        LoginErrorCode, LoginFeedbackMessages, LoginFeedbackVariant, LoginOutcomeFeedback,
        derive_login_feedback_with_messages, login_feedback_from_result_with_messages,
    };
    use crate::messages::AuthMessage;
    use crate::status::AuthDenyReason;
    use anyhow::{Error as AuthError, anyhow};

    #[derive(Debug)]
    struct TestOutcome {
        success: bool,
        requires_two_factor: bool,
        error_code: LoginErrorCode,
        message: Option<AuthMessage>,
        deny_reason: Option<AuthDenyReason>,
    }

    impl LoginOutcomeFeedback for TestOutcome {
        fn success(&self) -> bool {
            self.success
        }

        fn requires_two_factor(&self) -> bool {
            self.requires_two_factor
        }

        fn error_code(&self) -> LoginErrorCode {
            self.error_code
        }

        fn message(&self) -> Option<&AuthMessage> {
            self.message.as_ref()
        }

        fn deny_reason(&self) -> Option<&AuthDenyReason> {
            self.deny_reason.as_ref()
        }
    }

    #[test]
    fn derives_message_from_error_code() {
        let messages = LoginFeedbackMessages::test_messages();
        let outcome = TestOutcome {
            success: false,
            requires_two_factor: false,
            error_code: LoginErrorCode::RateLimited,
            message: None,
            deny_reason: None,
        };

        let feedback = derive_login_feedback_with_messages(&messages, &outcome);

        assert_eq!(
            feedback,
            Some((
                AuthMessage::from_static("rate_limited"),
                LoginFeedbackVariant::Error,
            ))
        );
    }

    #[test]
    fn suppresses_feedback_when_successful() {
        let messages = LoginFeedbackMessages::test_messages();
        let outcome = TestOutcome {
            success: true,
            requires_two_factor: false,
            error_code: LoginErrorCode::None,
            message: Some(AuthMessage::from_static("ignored")),
            deny_reason: None,
        };

        let feedback = derive_login_feedback_with_messages(&messages, &outcome);

        assert_eq!(feedback, None);
    }

    #[test]
    fn falls_back_to_outcome_message_when_present() {
        let messages = LoginFeedbackMessages::test_messages();
        let outcome = TestOutcome {
            success: false,
            requires_two_factor: false,
            error_code: LoginErrorCode::None,
            message: Some(AuthMessage::from_static("custom")),
            deny_reason: None,
        };

        let feedback = derive_login_feedback_with_messages(&messages, &outcome);

        assert_eq!(
            feedback,
            Some((
                AuthMessage::from_static("custom"),
                LoginFeedbackVariant::Error,
            ))
        );
    }

    #[test]
    fn maps_backend_errors_to_error_variant() {
        let messages = LoginFeedbackMessages::test_messages();
        let result: Result<TestOutcome, AuthError> = Err(anyhow!("oops".to_string()));

        let feedback = login_feedback_from_result_with_messages(&messages, &result);

        assert_eq!(
            feedback,
            Some((
                AuthMessage::from_static("auth.server_error"),
                LoginFeedbackVariant::Error,
            ))
        );
    }
}