Skip to main content

jmap_types/
jmap_uri.rs

1//! The `jmap:` JMAP object URI
2//! (draft-atwood-jmap-object-uri-00 §JMAP Object URIs).
3//!
4//! The draft defines the syntax as
5//! `jmap-object-uri = "jmap:" type-name ":" account-id ":" object-id`,
6//! where `type-name` is `1*( %x61-7A / DIGIT )` and `account-id` and
7//! `object-id` are `1*255id-char`, the RFC 8620 §1.2 `Id` alphabet. That
8//! alphabet excludes `:`, so splitting on `:` is unambiguous, and a URI
9//! with any further segment matches no form this crate implements
10//! (§Other Forms: "A receiver treats a `jmap` URI that matches no form it
11//! implements as unresolvable").
12
13use crate::{Id, ValidationError};
14use std::fmt;
15use std::str::FromStr;
16
17/// A parsed `jmap:<type>:<accountId>:<objectId>` URI.
18///
19/// Build one with [`JmapUri::new`] or parse one with [`str::parse`];
20/// [`Display`](fmt::Display) renders it back to the wire string. The URI
21/// arrives in peer-supplied values, so parsing validates every segment.
22///
23/// ```rust
24/// use jmap_types::JmapUri;
25///
26/// let uri: JmapUri = "jmap:calendarevent:a1:e42".parse().unwrap();
27/// assert_eq!(uri.data_type(), "calendarevent");
28/// assert_eq!(uri.account_id().as_ref(), "a1");
29/// assert_eq!(uri.object_id().as_ref(), "e42");
30/// assert_eq!(uri.to_string(), "jmap:calendarevent:a1:e42");
31/// ```
32///
33/// It serializes as its wire string and deserializes by parsing one, so a
34/// malformed value fails deserialization. Ordering compares the type, then
35/// the account id, then the object id, consistently with equality (the
36/// scheme is case-insensitive and not stored).
37#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct JmapUri {
39    data_type: String,
40    account_id: Id,
41    object_id: Id,
42}
43
44/// Why a string or set of parts is not a valid [`JmapUri`].
45#[non_exhaustive]
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum JmapUriError {
48    /// The URI scheme is not `jmap`, or the string has no scheme at all.
49    NotJmapScheme,
50    /// A `jmap://` authority form, which §Other Forms reserves and which is
51    /// not a JMAP object URI.
52    ReservedForm,
53    /// The `<type>` segment is empty, longer than 255 octets, or not
54    /// lowercase ASCII alphanumeric.
55    InvalidDataType,
56    /// The `<accountId>` segment is missing or not a valid `Id`.
57    InvalidAccountId(Option<ValidationError>),
58    /// No `<objectId>` segment follows the account.
59    MissingObjectId,
60    /// The `<objectId>` segment is not a valid `Id`, including when
61    /// further `:` segments follow it.
62    InvalidObjectId(ValidationError),
63}
64
65impl fmt::Display for JmapUriError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::NotJmapScheme => f.write_str("URI scheme is not `jmap`"),
69            Self::ReservedForm => {
70                f.write_str("jmap:// URI is a reserved form, not a JMAP object URI")
71            }
72            Self::InvalidDataType => {
73                f.write_str("jmap: URI type is not a lowercased JMAP data type name")
74            }
75            Self::InvalidAccountId(_) => f.write_str("jmap: URI accountId is missing or invalid"),
76            Self::MissingObjectId => f.write_str("jmap: URI has no objectId"),
77            Self::InvalidObjectId(_) => f.write_str("jmap: URI objectId is invalid"),
78        }
79    }
80}
81
82impl std::error::Error for JmapUriError {
83    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84        match self {
85            Self::InvalidAccountId(Some(e)) | Self::InvalidObjectId(e) => Some(e),
86            _ => None,
87        }
88    }
89}
90
91impl JmapUri {
92    /// Build a URI from its parts.
93    ///
94    /// # Errors
95    ///
96    /// Returns [`JmapUriError`] when `data_type` is not lowercase ASCII
97    /// alphanumeric or either id fails RFC 8620 §1.2 validation (an
98    /// unvalidated [`Id::from`] could otherwise smuggle a `:` into the
99    /// rendered URI).
100    pub fn new(
101        data_type: impl Into<String>,
102        account_id: Id,
103        object_id: Id,
104    ) -> Result<Self, JmapUriError> {
105        let data_type = data_type.into();
106        validate_data_type(&data_type)?;
107        Id::new_validated(account_id.as_ref())
108            .map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
109        Id::new_validated(object_id.as_ref()).map_err(JmapUriError::InvalidObjectId)?;
110        Ok(Self {
111            data_type,
112            account_id,
113            object_id,
114        })
115    }
116
117    /// The lowercased type name, e.g. `calendarevent`.
118    pub fn data_type(&self) -> &str {
119        &self.data_type
120    }
121
122    /// The account the object lives on.
123    pub fn account_id(&self) -> &Id {
124        &self.account_id
125    }
126
127    /// The referenced object's `id`.
128    pub fn object_id(&self) -> &Id {
129        &self.object_id
130    }
131}
132
133fn validate_data_type(s: &str) -> Result<(), JmapUriError> {
134    // type-name = 1*255( %x61-7A / DIGIT ), the RFC 8620 §1.2 limit that
135    // account-id and object-id also have.
136    if !s.is_empty()
137        && s.len() <= 255
138        && s.bytes()
139            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
140    {
141        Ok(())
142    } else {
143        Err(JmapUriError::InvalidDataType)
144    }
145}
146
147impl FromStr for JmapUri {
148    type Err = JmapUriError;
149
150    /// Parse a `jmap:` URI. The scheme matches case-insensitively
151    /// (RFC 3986 §3.1); every other segment is case-sensitive.
152    fn from_str(s: &str) -> Result<Self, Self::Err> {
153        // At most four parts: anything after the object-id stays in it and
154        // fails `Id` validation, since `:` is not an `id-char`.
155        let mut parts = s.splitn(4, ':');
156        let scheme = parts.next().unwrap_or_default();
157        // No `:` at all: not a URI with the `jmap` scheme.
158        let Some(data_type) = parts.next().filter(|_| scheme.eq_ignore_ascii_case("jmap")) else {
159            return Err(JmapUriError::NotJmapScheme);
160        };
161        if data_type.starts_with("//") {
162            return Err(JmapUriError::ReservedForm);
163        }
164        validate_data_type(data_type)?;
165        let account_id = parts.next().ok_or(JmapUriError::InvalidAccountId(None))?;
166        let account_id =
167            Id::new_validated(account_id).map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
168        let object_id = parts.next().ok_or(JmapUriError::MissingObjectId)?;
169        let object_id = Id::new_validated(object_id).map_err(JmapUriError::InvalidObjectId)?;
170        Self::new(data_type, account_id, object_id)
171    }
172}
173
174impl fmt::Display for JmapUri {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(
177            f,
178            "jmap:{}:{}:{}",
179            self.data_type, self.account_id, self.object_id
180        )
181    }
182}
183
184impl serde::Serialize for JmapUri {
185    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
186        serializer.collect_str(self)
187    }
188}
189
190impl<'de> serde::Deserialize<'de> for JmapUri {
191    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
192        let s = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
193        s.parse().map_err(serde::de::Error::custom)
194    }
195}