ruma_identifiers_validation/
lib.rs

1#![doc(html_favicon_url = "https://ruma.dev/favicon.ico")]
2#![doc(html_logo_url = "https://ruma.dev/images/logo.png")]
3
4pub mod base64_public_key;
5pub mod client_secret;
6pub mod error;
7pub mod event_id;
8pub mod key_id;
9pub mod mxc_uri;
10pub mod room_alias_id;
11pub mod room_id;
12pub mod room_id_or_alias_id;
13pub mod room_version_id;
14pub mod server_name;
15pub mod server_signing_key_version;
16pub mod user_id;
17pub mod voip_version_id;
18
19pub use error::Error;
20
21/// The maximum allowed length of Matrix identifiers, in bytes.
22pub const ID_MAX_BYTES: usize = 255;
23
24/// Checks if an identifier is valid.
25fn validate_id(id: &str, first_byte: u8) -> Result<(), Error> {
26    #[cfg(not(feature = "compat-arbitrary-length-ids"))]
27    if id.len() > ID_MAX_BYTES {
28        return Err(Error::MaximumLengthExceeded);
29    }
30
31    if id.as_bytes().first() != Some(&first_byte) {
32        return Err(Error::MissingLeadingSigil);
33    }
34
35    Ok(())
36}
37
38/// Checks an identifier that contains a localpart and hostname for validity.
39fn parse_id(id: &str, first_byte: u8) -> Result<usize, Error> {
40    validate_id(id, first_byte)?;
41    let colon_idx = id.find(':').ok_or(Error::MissingColon)?;
42    server_name::validate(&id[colon_idx + 1..])?;
43    Ok(colon_idx)
44}
45
46/// Checks an identifier that contains a localpart and hostname for validity.
47fn validate_delimited_id(id: &str, first_byte: u8) -> Result<(), Error> {
48    parse_id(id, first_byte)?;
49    Ok(())
50}
51
52/// Helper trait to validate the name of a key.
53pub trait KeyName: AsRef<str> {
54    /// Validate the given string for this name.
55    fn validate(s: &str) -> Result<(), Error>;
56}
57
58/// Check whether the Matrix identifier localpart is [allowed over federation].
59///
60/// According to the spec, localparts can consist of any legal non-surrogate Unicode code points
61/// except for `:` and `NUL` (`U+0000`).
62///
63/// [allowed over federation]: https://spec.matrix.org/latest/appendices/#historical-user-ids
64pub fn localpart_is_backwards_compatible(localpart: &str) -> Result<(), Error> {
65    let is_invalid = localpart.contains([':', '\0']);
66    if is_invalid {
67        Err(Error::InvalidCharacters)
68    } else {
69        Ok(())
70    }
71}