Skip to main content

ch_auth/
status.rs

1use std::borrow::Cow;
2
3use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
4use serde::{Deserialize, Serialize};
5
6use crate::messages::{AuthMessage, AuthMessageKey, is_valid_message_key};
7
8const AUTH_DENY_KEY_PREFIX: &str = "auth.access.denied.";
9
10/// Describes whether an account is allowed to authenticate.
11#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum AuthDecision {
14    /// Account may authenticate and use protected routes.
15    Allow,
16    /// Account must not authenticate because of the supplied reason.
17    Deny(AuthDenyReason),
18}
19
20impl AuthDecision {
21    /// Returns `true` when the decision allows authentication.
22    pub fn is_allowed(&self) -> bool {
23        matches!(self, Self::Allow)
24    }
25
26    /// Builds an allow decision.
27    pub fn allow() -> Self {
28        Self::Allow
29    }
30
31    /// Builds a deny decision with the supplied reason.
32    pub fn deny(reason: AuthDenyReason) -> Self {
33        Self::Deny(reason)
34    }
35}
36
37/// Enumerates standard denial reasons shared across apps.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum AuthDenyCode {
41    /// Account is inactive and cannot authenticate.
42    Inactive,
43    /// Account is blocked from authenticating.
44    Blocked,
45}
46
47/// Parsed identifier for custom denial reasons.
48#[derive(Clone, Debug, PartialEq, Eq, Hash)]
49pub struct AuthDenyKey(Cow<'static, str>);
50
51impl AuthDenyKey {
52    /// Parses and validates a custom denial key.
53    pub fn parse(raw: &str, field: &'static str) -> ParseResult<Self> {
54        let trimmed = raw.trim();
55        if trimmed.is_empty() {
56            return Err(ParseError::for_field(field, ParseErrorCode::Required));
57        }
58
59        if !trimmed.starts_with(AUTH_DENY_KEY_PREFIX) || !is_valid_message_key(trimmed) {
60            return Err(ParseError::for_field(field, ParseErrorCode::InvalidFormat)
61                .with_parameter("expected", AUTH_DENY_KEY_PREFIX));
62        }
63
64        Ok(Self(Cow::Owned(trimmed.to_string())))
65    }
66
67    /// Builds a custom denial key from a static string literal.
68    pub fn new_static(key: &'static str) -> Self {
69        Self::parse(key, "auth_deny_key").expect("invalid auth deny key")
70    }
71
72    /// Returns the underlying key string.
73    pub fn as_str(&self) -> &str {
74        self.0.as_ref()
75    }
76}
77
78impl Serialize for AuthDenyKey {
79    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
80    where
81        S: serde::Serializer,
82    {
83        serializer.serialize_str(self.as_str())
84    }
85}
86
87impl<'de> Deserialize<'de> for AuthDenyKey {
88    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
89    where
90        D: serde::Deserializer<'de>,
91    {
92        let raw = String::deserialize(deserializer)?;
93        AuthDenyKey::parse(raw.as_str(), "auth_deny_key")
94            .map_err(|error| serde::de::Error::custom(error.to_string()))
95    }
96}
97
98/// Describes why authentication is denied.
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
101pub enum AuthDenyReason {
102    /// Shared denial reason across all apps.
103    Standard(AuthDenyCode),
104    /// Application-defined denial reason represented by a stable domain code.
105    Custom(AuthDenyKey),
106}
107
108impl AuthDenyReason {
109    /// Returns a denial reason for inactive accounts.
110    pub fn inactive() -> Self {
111        Self::Standard(AuthDenyCode::Inactive)
112    }
113
114    /// Returns a denial reason for blocked accounts.
115    pub fn blocked() -> Self {
116        Self::Standard(AuthDenyCode::Blocked)
117    }
118
119    /// Returns a denial reason backed by a custom key.
120    pub fn custom(key: AuthDenyKey) -> Self {
121        Self::Custom(key)
122    }
123}
124
125/// Returns the message descriptor for a denial reason.
126pub fn auth_deny_message(reason: &AuthDenyReason) -> AuthMessage {
127    match reason {
128        AuthDenyReason::Standard(AuthDenyCode::Inactive) => {
129            AuthMessage::from_static("auth.access.denied.inactive")
130        }
131        AuthDenyReason::Standard(AuthDenyCode::Blocked) => {
132            AuthMessage::from_static("auth.access.denied.blocked")
133        }
134        AuthDenyReason::Custom(key) => AuthMessage::new(message_key_from_deny_key(key)),
135    }
136}
137
138/// Converts a validated denial key into a message key.
139fn message_key_from_deny_key(key: &AuthDenyKey) -> AuthMessageKey {
140    AuthMessageKey::parse(key.as_str(), "auth_deny_key").expect("invalid auth deny key")
141}
142
143#[cfg(test)]
144mod tests {
145    use super::{AuthDenyKey, AuthDenyReason};
146
147    #[test]
148    fn parses_valid_deny_keys() {
149        let key = AuthDenyKey::parse("auth.access.denied.deactivated", "key").expect("valid key");
150        assert_eq!(key.as_str(), "auth.access.denied.deactivated");
151    }
152
153    #[test]
154    fn rejects_invalid_deny_keys() {
155        assert!(AuthDenyKey::parse("invalid key", "key").is_err());
156        assert!(AuthDenyKey::parse("auth.denied.bad", "key").is_err());
157    }
158
159    #[test]
160    fn matches_custom_deny_reasons() {
161        let key = AuthDenyKey::new_static("auth.access.denied.deactivated");
162        let reason = AuthDenyReason::custom(key);
163        match reason {
164            AuthDenyReason::Custom(custom) => {
165                assert_eq!(custom.as_str(), "auth.access.denied.deactivated");
166            }
167            _ => panic!("expected custom deny reason"),
168        }
169    }
170}