ruma_common/identifiers/
user_id.rs

1//! Matrix user identifiers.
2
3use std::{rc::Rc, sync::Arc};
4
5use super::{matrix_uri::UriAction, IdParseError, MatrixToUri, MatrixUri, ServerName};
6
7/// A Matrix [user ID].
8///
9/// A `UserId` is generated randomly or converted from a string slice, and can be converted back
10/// into a string as needed.
11///
12/// ```
13/// # use ruma_common::UserId;
14/// assert_eq!(<&UserId>::try_from("@carl:example.com").unwrap(), "@carl:example.com");
15/// ```
16///
17/// [user ID]: https://spec.matrix.org/latest/appendices/#user-identifiers
18#[repr(transparent)]
19#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdZst)]
20#[ruma_id(validate = ruma_identifiers_validation::user_id::validate)]
21pub struct UserId(str);
22
23impl UserId {
24    /// Attempts to generate a `UserId` for the given origin server with a localpart consisting of
25    /// 12 random ASCII characters.
26    #[cfg(feature = "rand")]
27    #[allow(clippy::new_ret_no_self)]
28    pub fn new(server_name: &ServerName) -> OwnedUserId {
29        Self::from_borrowed(&format!(
30            "@{}:{}",
31            super::generate_localpart(12).to_lowercase(),
32            server_name
33        ))
34        .to_owned()
35    }
36
37    /// Attempts to complete a user ID, by adding the colon + server name and `@` prefix, if not
38    /// present already.
39    ///
40    /// This is a convenience function for the login API, where a user can supply either their full
41    /// user ID or just the localpart. It only supports a valid user ID or a valid user ID
42    /// localpart, not the localpart plus the `@` prefix, or the localpart plus server name without
43    /// the `@` prefix.
44    pub fn parse_with_server_name(
45        id: impl AsRef<str> + Into<Box<str>>,
46        server_name: &ServerName,
47    ) -> Result<OwnedUserId, IdParseError> {
48        let id_str = id.as_ref();
49
50        if id_str.starts_with('@') {
51            Self::parse(id)
52        } else {
53            let _ = localpart_is_fully_conforming(id_str)?;
54            Ok(Self::from_borrowed(&format!("@{id_str}:{server_name}")).to_owned())
55        }
56    }
57
58    /// Variation of [`parse_with_server_name`] that returns `Rc<Self>`.
59    ///
60    /// [`parse_with_server_name`]: Self::parse_with_server_name
61    pub fn parse_with_server_name_rc(
62        id: impl AsRef<str> + Into<Rc<str>>,
63        server_name: &ServerName,
64    ) -> Result<Rc<Self>, IdParseError> {
65        let id_str = id.as_ref();
66
67        if id_str.starts_with('@') {
68            Self::parse_rc(id)
69        } else {
70            let _ = localpart_is_fully_conforming(id_str)?;
71            Ok(Self::from_rc(format!("@{id_str}:{server_name}").into()))
72        }
73    }
74
75    /// Variation of [`parse_with_server_name`] that returns `Arc<Self>`.
76    ///
77    /// [`parse_with_server_name`]: Self::parse_with_server_name
78    pub fn parse_with_server_name_arc(
79        id: impl AsRef<str> + Into<Arc<str>>,
80        server_name: &ServerName,
81    ) -> Result<Arc<Self>, IdParseError> {
82        let id_str = id.as_ref();
83
84        if id_str.starts_with('@') {
85            Self::parse_arc(id)
86        } else {
87            let _ = localpart_is_fully_conforming(id_str)?;
88            Ok(Self::from_arc(format!("@{id_str}:{server_name}").into()))
89        }
90    }
91
92    /// Returns the user's localpart.
93    pub fn localpart(&self) -> &str {
94        &self.as_str()[1..self.colon_idx()]
95    }
96
97    /// Returns the server name of the user ID.
98    pub fn server_name(&self) -> &ServerName {
99        ServerName::from_borrowed(&self.as_str()[self.colon_idx() + 1..])
100    }
101
102    /// Whether this user ID is a historical one.
103    ///
104    /// A historical user ID is one that doesn't conform to the latest specification of the user ID
105    /// grammar but is still accepted because it was previously allowed.
106    pub fn is_historical(&self) -> bool {
107        !localpart_is_fully_conforming(self.localpart()).unwrap()
108    }
109
110    /// Create a `matrix.to` URI for this user ID.
111    ///
112    /// # Example
113    ///
114    /// ```
115    /// use ruma_common::user_id;
116    ///
117    /// let message = format!(
118    ///     r#"Thanks for the update <a href="{link}">{display_name}</a>."#,
119    ///     link = user_id!("@jplatte:notareal.hs").matrix_to_uri(),
120    ///     display_name = "jplatte",
121    /// );
122    /// ```
123    pub fn matrix_to_uri(&self) -> MatrixToUri {
124        MatrixToUri::new(self.into(), Vec::new())
125    }
126
127    /// Create a `matrix:` URI for this user ID.
128    ///
129    /// If `chat` is `true`, a click on the URI should start a direct message
130    /// with the user.
131    ///
132    /// # Example
133    ///
134    /// ```
135    /// use ruma_common::user_id;
136    ///
137    /// let message = format!(
138    ///     r#"Thanks for the update <a href="{link}">{display_name}</a>."#,
139    ///     link = user_id!("@jplatte:notareal.hs").matrix_uri(false),
140    ///     display_name = "jplatte",
141    /// );
142    /// ```
143    pub fn matrix_uri(&self, chat: bool) -> MatrixUri {
144        MatrixUri::new(self.into(), Vec::new(), Some(UriAction::Chat).filter(|_| chat))
145    }
146
147    fn colon_idx(&self) -> usize {
148        self.as_str().find(':').unwrap()
149    }
150}
151
152pub use ruma_identifiers_validation::user_id::localpart_is_fully_conforming;
153use ruma_macros::IdZst;
154
155#[cfg(test)]
156mod tests {
157    use super::{OwnedUserId, UserId};
158    use crate::{server_name, IdParseError};
159
160    #[test]
161    fn valid_user_id_from_str() {
162        let user_id = <&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.");
163        assert_eq!(user_id.as_str(), "@carl:example.com");
164        assert_eq!(user_id.localpart(), "carl");
165        assert_eq!(user_id.server_name(), "example.com");
166        assert!(!user_id.is_historical());
167    }
168
169    #[test]
170    fn parse_valid_user_id() {
171        let server_name = server_name!("example.com");
172        let user_id = UserId::parse_with_server_name("@carl:example.com", server_name)
173            .expect("Failed to create UserId.");
174        assert_eq!(user_id.as_str(), "@carl:example.com");
175        assert_eq!(user_id.localpart(), "carl");
176        assert_eq!(user_id.server_name(), "example.com");
177        assert!(!user_id.is_historical());
178    }
179
180    #[test]
181    fn parse_valid_user_id_parts() {
182        let server_name = server_name!("example.com");
183        let user_id =
184            UserId::parse_with_server_name("carl", server_name).expect("Failed to create UserId.");
185        assert_eq!(user_id.as_str(), "@carl:example.com");
186        assert_eq!(user_id.localpart(), "carl");
187        assert_eq!(user_id.server_name(), "example.com");
188        assert!(!user_id.is_historical());
189    }
190
191    #[cfg(not(feature = "compat-user-id"))]
192    #[test]
193    fn invalid_user_id() {
194        let localpart = "τ";
195        let user_id = "@τ:example.com";
196        let server_name = server_name!("example.com");
197
198        <&UserId>::try_from(user_id).unwrap_err();
199        UserId::parse_with_server_name(user_id, server_name).unwrap_err();
200        UserId::parse_with_server_name(localpart, server_name).unwrap_err();
201        UserId::parse_with_server_name_rc(user_id, server_name).unwrap_err();
202        UserId::parse_with_server_name_rc(localpart, server_name).unwrap_err();
203        UserId::parse_with_server_name_arc(user_id, server_name).unwrap_err();
204        UserId::parse_with_server_name_arc(localpart, server_name).unwrap_err();
205        UserId::parse_rc(user_id).unwrap_err();
206        UserId::parse_arc(user_id).unwrap_err();
207    }
208
209    #[test]
210    fn definitely_invalid_user_id() {
211        UserId::parse_with_server_name("a:b", server_name!("example.com")).unwrap_err();
212    }
213
214    #[test]
215    fn valid_historical_user_id() {
216        let user_id =
217            <&UserId>::try_from("@a%b[irc]:example.com").expect("Failed to create UserId.");
218        assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
219        assert_eq!(user_id.localpart(), "a%b[irc]");
220        assert_eq!(user_id.server_name(), "example.com");
221        assert!(user_id.is_historical());
222    }
223
224    #[test]
225    fn parse_valid_historical_user_id() {
226        let server_name = server_name!("example.com");
227        let user_id = UserId::parse_with_server_name("@a%b[irc]:example.com", server_name)
228            .expect("Failed to create UserId.");
229        assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
230        assert_eq!(user_id.localpart(), "a%b[irc]");
231        assert_eq!(user_id.server_name(), "example.com");
232        assert!(user_id.is_historical());
233    }
234
235    #[test]
236    fn parse_valid_historical_user_id_parts() {
237        let server_name = server_name!("example.com");
238        let user_id = UserId::parse_with_server_name("a%b[irc]", server_name)
239            .expect("Failed to create UserId.");
240        assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
241        assert_eq!(user_id.localpart(), "a%b[irc]");
242        assert_eq!(user_id.server_name(), "example.com");
243        assert!(user_id.is_historical());
244    }
245
246    #[test]
247    fn uppercase_user_id() {
248        let user_id = <&UserId>::try_from("@CARL:example.com").expect("Failed to create UserId.");
249        assert_eq!(user_id.as_str(), "@CARL:example.com");
250        assert!(user_id.is_historical());
251    }
252
253    #[cfg(feature = "rand")]
254    #[test]
255    fn generate_random_valid_user_id() {
256        let server_name = server_name!("example.com");
257        let user_id = UserId::new(server_name);
258        assert_eq!(user_id.localpart().len(), 12);
259        assert_eq!(user_id.server_name(), "example.com");
260
261        let id_str = user_id.as_str();
262
263        assert!(id_str.starts_with('@'));
264        assert_eq!(id_str.len(), 25);
265    }
266
267    #[test]
268    fn serialize_valid_user_id() {
269        assert_eq!(
270            serde_json::to_string(
271                <&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.")
272            )
273            .expect("Failed to convert UserId to JSON."),
274            r#""@carl:example.com""#
275        );
276    }
277
278    #[test]
279    fn deserialize_valid_user_id() {
280        assert_eq!(
281            serde_json::from_str::<OwnedUserId>(r#""@carl:example.com""#)
282                .expect("Failed to convert JSON to UserId"),
283            <&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.")
284        );
285    }
286
287    #[test]
288    fn valid_user_id_with_explicit_standard_port() {
289        assert_eq!(
290            <&UserId>::try_from("@carl:example.com:443")
291                .expect("Failed to create UserId.")
292                .as_str(),
293            "@carl:example.com:443"
294        );
295    }
296
297    #[test]
298    fn valid_user_id_with_non_standard_port() {
299        let user_id =
300            <&UserId>::try_from("@carl:example.com:5000").expect("Failed to create UserId.");
301        assert_eq!(user_id.as_str(), "@carl:example.com:5000");
302        assert!(!user_id.is_historical());
303    }
304
305    #[test]
306    #[cfg(not(feature = "compat-user-id"))]
307    fn invalid_characters_in_user_id_localpart() {
308        assert_eq!(
309            <&UserId>::try_from("@te\nst:example.com").unwrap_err(),
310            IdParseError::InvalidCharacters
311        );
312    }
313
314    #[test]
315    fn missing_user_id_sigil() {
316        assert_eq!(
317            <&UserId>::try_from("carl:example.com").unwrap_err(),
318            IdParseError::MissingLeadingSigil
319        );
320    }
321
322    #[test]
323    fn missing_user_id_delimiter() {
324        assert_eq!(<&UserId>::try_from("@carl").unwrap_err(), IdParseError::MissingColon);
325    }
326
327    #[test]
328    fn invalid_user_id_host() {
329        assert_eq!(<&UserId>::try_from("@carl:/").unwrap_err(), IdParseError::InvalidServerName);
330    }
331
332    #[test]
333    fn invalid_user_id_port() {
334        assert_eq!(
335            <&UserId>::try_from("@carl:example.com:notaport").unwrap_err(),
336            IdParseError::InvalidServerName
337        );
338    }
339}