Skip to main content

ch_auth/
messages.rs

1use std::borrow::Cow;
2
3use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
4use serde::{Deserialize, Serialize};
5
6/// Parsed domain code that an application may translate at its UI boundary.
7#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(try_from = "String")]
9pub struct AuthMessageKey(Cow<'static, str>);
10
11impl AuthMessageKey {
12    /// Parses and validates a message key string.
13    pub fn parse(raw: &str, field: &'static str) -> ParseResult<Self> {
14        let trimmed = raw.trim();
15        if trimmed.is_empty() {
16            return Err(ParseError::for_field(field, ParseErrorCode::Required));
17        }
18
19        if !is_valid_message_key(trimmed) {
20            return Err(ParseError::for_field(field, ParseErrorCode::InvalidFormat)
21                .with_parameter("expected", "domain_code"));
22        }
23
24        Ok(Self(Cow::Owned(trimmed.to_string())))
25    }
26
27    /// Builds a message key from a static string literal.
28    pub fn new_static(key: &'static str) -> Self {
29        Self::parse(key, "auth_message_key").expect("invalid message key")
30    }
31
32    /// Returns the underlying key string.
33    pub fn as_str(&self) -> &str {
34        self.0.as_ref()
35    }
36}
37
38impl TryFrom<String> for AuthMessageKey {
39    type Error = ParseError;
40
41    fn try_from(value: String) -> ParseResult<Self> {
42        Self::parse(&value, "auth_message_key")
43    }
44}
45
46/// Structured argument supplied to a localized message.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct AuthMessageArg {
49    name: Cow<'static, str>,
50    value: Cow<'static, str>,
51}
52
53impl AuthMessageArg {
54    /// Creates a new message argument from the provided name and value.
55    pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
56        Self {
57            name: name.into(),
58            value: value.into(),
59        }
60    }
61
62    /// Returns the argument name.
63    pub fn name(&self) -> &str {
64        self.name.as_ref()
65    }
66
67    /// Returns the argument value.
68    pub fn value(&self) -> &str {
69        self.value.as_ref()
70    }
71}
72
73/// Message descriptor that can be translated by the host application.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75pub struct AuthMessage {
76    key: AuthMessageKey,
77    args: Vec<AuthMessageArg>,
78}
79
80impl AuthMessage {
81    /// Creates a new message from the provided key.
82    pub fn new(key: AuthMessageKey) -> Self {
83        Self {
84            key,
85            args: Vec::new(),
86        }
87    }
88
89    /// Creates a new message from a static key literal.
90    pub fn from_static(key: &'static str) -> Self {
91        Self::new(AuthMessageKey::new_static(key))
92    }
93
94    /// Adds an argument to the message.
95    pub fn with_arg(
96        mut self,
97        name: impl Into<Cow<'static, str>>,
98        value: impl Into<Cow<'static, str>>,
99    ) -> Self {
100        self.args.push(AuthMessageArg::new(name, value));
101        self
102    }
103
104    /// Returns the message key.
105    pub fn key(&self) -> &AuthMessageKey {
106        &self.key
107    }
108
109    /// Returns the message arguments.
110    pub fn args(&self) -> &[AuthMessageArg] {
111        &self.args
112    }
113}
114
115pub(crate) fn is_valid_message_key(value: &str) -> bool {
116    value.chars().all(|ch| {
117        ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == '_' || ch == '-'
118    })
119}
120
121#[cfg(test)]
122mod tests {
123    use super::AuthMessageKey;
124
125    #[test]
126    fn deserialization_uses_the_message_key_parser() {
127        for invalid in [
128            "",
129            "  ",
130            "bad key",
131            "INVALID",
132            "auth.login\nforged",
133            "auth.ΓΌ",
134        ] {
135            assert!(AuthMessageKey::parse(invalid, "key").is_err());
136            let input = serde_json::to_string(invalid).unwrap();
137            assert!(serde_json::from_str::<AuthMessageKey>(&input).is_err());
138        }
139        let key: AuthMessageKey = serde_json::from_str("\" auth.login.success \"").unwrap();
140        assert_eq!(key.as_str(), "auth.login.success");
141        assert_eq!(
142            serde_json::to_string(&key).unwrap(),
143            "\"auth.login.success\""
144        );
145    }
146}