Skip to main content

relay_core/identity/
inbox.rs

1use serde::{
2    Deserialize, Deserializer, Serialize, Serializer,
3    de::{self, Visitor},
4};
5
6use crate::prelude::UserId;
7
8use super::{IdentityError as Err, canonical_identity_string, is_valid_identity_string};
9
10/// A unique identifier for an Inbox.
11/// https://gitlab.com/relay-mail/docs/-/wikis/Architecture/Identity#inbox
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
13pub struct InboxId(String);
14
15impl TryFrom<UserId> for InboxId {
16    type Error = Err;
17
18    fn try_from(user: UserId) -> Result<Self, Err> {
19        match user.inbox() {
20            Some(inbox) => Ok(inbox.clone()),
21            None => Err(Err::InvalidInbox),
22        }
23    }
24}
25
26impl TryFrom<&str> for InboxId {
27    type Error = Err;
28
29    fn try_from(value: &str) -> Result<Self, Err> {
30        InboxId::parse(value)
31    }
32}
33
34impl TryFrom<String> for InboxId {
35    type Error = Err;
36
37    fn try_from(value: String) -> Result<Self, Err> {
38        InboxId::parse(value)
39    }
40}
41
42impl InboxId {
43    /// Parse an InboxId from a string according to the identity rules.
44    /// https://gitlab.com/relay-mail/docs/-/wikis/Architecture/Identity#inbox
45    ///
46    /// # Example
47    /// ```
48    /// let inbox_id = relay_core::id::InboxId::parse("Work").unwrap();
49    /// assert_eq!(inbox_id.canonical(), "work");
50    /// ```
51    pub fn parse(input: impl AsRef<str>) -> Result<Self, Err> {
52        let input = input.as_ref();
53
54        if input.is_empty() {
55            return Err(Err::InvalidInbox);
56        }
57        if !is_valid_identity_string(input) {
58            return Err(Err::InvalidIdentityString);
59        }
60
61        let canonical = canonical_identity_string(input);
62
63        Ok(Self(canonical))
64    }
65
66    /// Replace the current InboxId with a new value.
67    pub fn replace(&mut self, new_value: impl AsRef<str>) -> Result<(), Err> {
68        *self = Self::parse(new_value)?;
69        Ok(())
70    }
71
72    /// The canonical form of the InboxId. The value is already stored as such.
73    /// https://gitlab.com/relay-mail/docs/-/wikis/Architecture/Identity#canonical-form
74    pub fn canonical(&self) -> &str {
75        &self.0
76    }
77}
78
79impl std::fmt::Display for InboxId {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{}", self.canonical())
82    }
83}
84
85impl Serialize for InboxId {
86    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87    where
88        S: Serializer,
89    {
90        serializer.serialize_str(self.canonical())
91    }
92}
93
94impl<'de> Deserialize<'de> for InboxId {
95    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
96    where
97        D: Deserializer<'de>,
98    {
99        struct InboxIdVisitor;
100
101        impl<'de> Visitor<'de> for InboxIdVisitor {
102            type Value = InboxId;
103
104            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
105                f.write_str("a canonical Relay Mail address string")
106            }
107
108            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
109            where
110                E: de::Error,
111            {
112                InboxId::parse(value)
113                    .map_err(|e| de::Error::custom(format!("invalid address `{}`: {}", value, e)))
114            }
115
116            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
117            where
118                E: de::Error,
119            {
120                self.visit_str(&value)
121            }
122        }
123
124        deserializer.deserialize_str(InboxIdVisitor)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn parses_and_canonicalizes() {
134        assert_eq!(InboxId::parse("Work").unwrap().canonical(), "work");
135    }
136
137    #[test]
138    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidInbox")]
139    fn rejects_empty() {
140        let _ = InboxId::parse("").unwrap();
141    }
142
143    #[test]
144    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
145    fn rejects_invalid_chars() {
146        let _ = InboxId::parse("Invalid Inbox!").unwrap();
147    }
148
149    #[test]
150    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
151    fn reject_untrimmed() {
152        let _ = InboxId::parse("  trim_me  ").unwrap();
153    }
154
155    #[test]
156    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
157    fn rejects_non_ascii() {
158        let _ = InboxId::parse("调试输出").unwrap();
159    }
160
161    #[test]
162    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
163    fn rejects_homoglyphs() {
164        let _ = InboxId::parse("wоrk").unwrap(); // Cyrillic 'о'
165    }
166}