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 or not lowercase ASCII alphanumeric.
54    InvalidDataType,
55    /// The `<accountId>` segment is missing or not a valid `Id`.
56    InvalidAccountId(Option<ValidationError>),
57    /// No `<objectId>` segment follows the account.
58    MissingObjectId,
59    /// The `<objectId>` segment is not a valid `Id`, including when
60    /// further `:` segments follow it.
61    InvalidObjectId(ValidationError),
62}
63
64impl fmt::Display for JmapUriError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            Self::NotJmapScheme => f.write_str("URI scheme is not `jmap`"),
68            Self::ReservedForm => {
69                f.write_str("jmap:// URI is a reserved form, not a JMAP object URI")
70            }
71            Self::InvalidDataType => {
72                f.write_str("jmap: URI type is not a lowercased JMAP data type name")
73            }
74            Self::InvalidAccountId(_) => f.write_str("jmap: URI accountId is missing or invalid"),
75            Self::MissingObjectId => f.write_str("jmap: URI has no objectId"),
76            Self::InvalidObjectId(_) => f.write_str("jmap: URI objectId is invalid"),
77        }
78    }
79}
80
81impl std::error::Error for JmapUriError {
82    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
83        match self {
84            Self::InvalidAccountId(Some(e)) | Self::InvalidObjectId(e) => Some(e),
85            _ => None,
86        }
87    }
88}
89
90impl JmapUri {
91    /// Build a URI from its parts.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`JmapUriError`] when `data_type` is not lowercase ASCII
96    /// alphanumeric or either id fails RFC 8620 §1.2 validation (an
97    /// unvalidated [`Id::from`] could otherwise smuggle a `:` into the
98    /// rendered URI).
99    pub fn new(
100        data_type: impl Into<String>,
101        account_id: Id,
102        object_id: Id,
103    ) -> Result<Self, JmapUriError> {
104        let data_type = data_type.into();
105        validate_data_type(&data_type)?;
106        Id::new_validated(account_id.as_ref())
107            .map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
108        Id::new_validated(object_id.as_ref()).map_err(JmapUriError::InvalidObjectId)?;
109        Ok(Self {
110            data_type,
111            account_id,
112            object_id,
113        })
114    }
115
116    /// The lowercased type name, e.g. `calendarevent`.
117    pub fn data_type(&self) -> &str {
118        &self.data_type
119    }
120
121    /// The account the object lives on.
122    pub fn account_id(&self) -> &Id {
123        &self.account_id
124    }
125
126    /// The referenced object's `id`.
127    pub fn object_id(&self) -> &Id {
128        &self.object_id
129    }
130}
131
132fn validate_data_type(s: &str) -> Result<(), JmapUriError> {
133    if !s.is_empty()
134        && s.bytes()
135            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
136    {
137        Ok(())
138    } else {
139        Err(JmapUriError::InvalidDataType)
140    }
141}
142
143impl FromStr for JmapUri {
144    type Err = JmapUriError;
145
146    /// Parse a `jmap:` URI. The scheme matches case-insensitively
147    /// (RFC 3986 §3.1); every other segment is case-sensitive.
148    fn from_str(s: &str) -> Result<Self, Self::Err> {
149        // At most four parts: anything after the object-id stays in it and
150        // fails `Id` validation, since `:` is not an `id-char`.
151        let mut parts = s.splitn(4, ':');
152        let scheme = parts.next().unwrap_or_default();
153        // No `:` at all: not a URI with the `jmap` scheme.
154        let Some(data_type) = parts.next().filter(|_| scheme.eq_ignore_ascii_case("jmap")) else {
155            return Err(JmapUriError::NotJmapScheme);
156        };
157        if data_type.starts_with("//") {
158            return Err(JmapUriError::ReservedForm);
159        }
160        validate_data_type(data_type)?;
161        let account_id = parts.next().ok_or(JmapUriError::InvalidAccountId(None))?;
162        let account_id =
163            Id::new_validated(account_id).map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
164        let object_id = parts.next().ok_or(JmapUriError::MissingObjectId)?;
165        let object_id = Id::new_validated(object_id).map_err(JmapUriError::InvalidObjectId)?;
166        Self::new(data_type, account_id, object_id)
167    }
168}
169
170impl fmt::Display for JmapUri {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(
173            f,
174            "jmap:{}:{}:{}",
175            self.data_type, self.account_id, self.object_id
176        )
177    }
178}
179
180impl serde::Serialize for JmapUri {
181    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
182        serializer.collect_str(self)
183    }
184}
185
186impl<'de> serde::Deserialize<'de> for JmapUri {
187    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
188        let s = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
189        s.parse().map_err(serde::de::Error::custom)
190    }
191}