Skip to main content

ibridge_core/
ids.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Opaque identifiers and DAV resource paths.
4
5use std::fmt;
6
7use base64::Engine;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD;
9
10use crate::error::{IdError, ParseError};
11use crate::mail::{MailboxPath, MessageId, Uid, UidValidity};
12
13const VERSION: u8 = 1;
14const KIND_MESSAGE: u8 = 1;
15const KIND_RESOURCE: u8 = 2;
16
17/// Encodes a [`MessageId`] as an opaque token.
18///
19/// Version 1 is base64url (no padding) over a length-prefixed body: version,
20/// kind, `u16` mailbox length, mailbox bytes, `u32` UIDVALIDITY, `u32` UID, and
21/// a CRC-32 of those bytes. A flipped character fails the checksum.
22#[must_use]
23pub fn encode(id: &MessageId) -> String {
24    encode_parts(id.mailbox.as_str(), id.validity.get(), id.uid.get())
25}
26
27/// Decodes a token produced by [`encode`].
28///
29/// # Errors
30///
31/// Returns [`IdError::Decode`] when the token is malformed, tampered, or carries a URL.
32pub fn decode(token: &str) -> Result<MessageId, IdError> {
33    let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| IdError::Decode)?;
34    // version + kind + length + validity + uid + checksum, with an empty mailbox.
35    if bytes.len() < 16 {
36        return Err(IdError::Decode);
37    }
38    let (body, sum_bytes) = bytes.split_at(bytes.len() - 4);
39    let mut sum = [0_u8; 4];
40    sum.copy_from_slice(sum_bytes);
41    if crc32(body) != u32::from_be_bytes(sum) {
42        return Err(IdError::Decode);
43    }
44    let mut rest = body;
45    if take_u8(&mut rest)? != VERSION || take_u8(&mut rest)? != KIND_MESSAGE {
46        return Err(IdError::Decode);
47    }
48    let len = usize::from(take_u16(&mut rest)?);
49    if rest.len() != len + 8 {
50        return Err(IdError::Decode);
51    }
52    let (mailbox_bytes, after) = rest.split_at(len);
53    let mailbox = std::str::from_utf8(mailbox_bytes).map_err(|_| IdError::Decode)?;
54    let mailbox = MailboxPath::try_from(mailbox).map_err(|_| IdError::Decode)?;
55    let mut tail = after;
56    let validity = UidValidity::try_from(take_u32(&mut tail)?).map_err(|_| IdError::Decode)?;
57    let uid = Uid::try_from(take_u32(&mut tail)?).map_err(|_| IdError::Decode)?;
58    if !tail.is_empty() {
59        return Err(IdError::Decode);
60    }
61    Ok(MessageId {
62        mailbox,
63        validity,
64        uid,
65    })
66}
67
68/// Encodes a DAV [`ResourcePath`] as an opaque token. Same framing as
69/// [`encode`], with its own kind byte so a message token never decodes as a path.
70#[must_use]
71pub fn encode_resource(path: &ResourcePath) -> String {
72    let bytes = path.as_str().as_bytes();
73    // A path is short; a longer one would not have been a useful id anyway.
74    let len = u16::try_from(bytes.len()).unwrap_or(u16::MAX);
75    let mut body = Vec::with_capacity(8 + bytes.len());
76    body.push(VERSION);
77    body.push(KIND_RESOURCE);
78    body.extend_from_slice(&len.to_be_bytes());
79    body.extend_from_slice(&bytes[..usize::from(len)]);
80    let sum = crc32(&body);
81    body.extend_from_slice(&sum.to_be_bytes());
82    URL_SAFE_NO_PAD.encode(body)
83}
84
85/// Decodes a token produced by [`encode_resource`].
86///
87/// # Errors
88///
89/// Returns [`IdError::Decode`] when the token is malformed, tampered, or not a resource token.
90pub fn decode_resource(token: &str) -> Result<ResourcePath, IdError> {
91    let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| IdError::Decode)?;
92    if bytes.len() < 8 {
93        return Err(IdError::Decode);
94    }
95    let (body, sum_bytes) = bytes.split_at(bytes.len() - 4);
96    let mut sum = [0_u8; 4];
97    sum.copy_from_slice(sum_bytes);
98    if crc32(body) != u32::from_be_bytes(sum) {
99        return Err(IdError::Decode);
100    }
101    let mut rest = body;
102    if take_u8(&mut rest)? != VERSION || take_u8(&mut rest)? != KIND_RESOURCE {
103        return Err(IdError::Decode);
104    }
105    let len = usize::from(take_u16(&mut rest)?);
106    if rest.len() != len {
107        return Err(IdError::Decode);
108    }
109    let path = std::str::from_utf8(rest).map_err(|_| IdError::Decode)?;
110    ResourcePath::try_from(path).map_err(|_| IdError::Decode)
111}
112
113/// Builds a token from raw parts, skipping mailbox validation. Tests use this to
114/// craft a URL payload.
115#[cfg(test)]
116#[must_use]
117pub(crate) fn encode_raw(mailbox: &str, validity: u32, uid: u32) -> String {
118    encode_parts(mailbox, validity, uid)
119}
120
121fn encode_parts(mailbox: &str, validity: u32, uid: u32) -> String {
122    URL_SAFE_NO_PAD.encode(frame(mailbox, validity, uid))
123}
124
125fn frame(mailbox: &str, validity: u32, uid: u32) -> Vec<u8> {
126    let mailbox_bytes = mailbox.as_bytes();
127    let len = u16::try_from(mailbox_bytes.len()).expect("mailbox name fits in a u16");
128    let mut body = Vec::with_capacity(16 + mailbox_bytes.len());
129    body.push(VERSION);
130    body.push(KIND_MESSAGE);
131    body.extend_from_slice(&len.to_be_bytes());
132    body.extend_from_slice(mailbox_bytes);
133    body.extend_from_slice(&validity.to_be_bytes());
134    body.extend_from_slice(&uid.to_be_bytes());
135    let sum = crc32(&body);
136    body.extend_from_slice(&sum.to_be_bytes());
137    body
138}
139
140fn take_u8(rest: &mut &[u8]) -> Result<u8, IdError> {
141    let (&first, tail) = rest.split_first().ok_or(IdError::Decode)?;
142    *rest = tail;
143    Ok(first)
144}
145
146fn take_u16(rest: &mut &[u8]) -> Result<u16, IdError> {
147    Ok(u16::from_be_bytes(take_array::<2>(rest)?))
148}
149
150fn take_u32(rest: &mut &[u8]) -> Result<u32, IdError> {
151    Ok(u32::from_be_bytes(take_array::<4>(rest)?))
152}
153
154fn take_array<const N: usize>(rest: &mut &[u8]) -> Result<[u8; N], IdError> {
155    if rest.len() < N {
156        return Err(IdError::Decode);
157    }
158    let (head, tail) = rest.split_at(N);
159    *rest = tail;
160    let mut value = [0_u8; N];
161    value.copy_from_slice(head);
162    Ok(value)
163}
164
165/// CRC-32/ISO-HDLC. Detects a flipped token byte; it is not an authenticator.
166fn crc32(data: &[u8]) -> u32 {
167    let mut crc = 0xffff_ffff_u32;
168    for &byte in data {
169        crc ^= u32::from(byte);
170        for _ in 0..8 {
171            let mask = (crc & 1).wrapping_neg();
172            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
173        }
174    }
175    !crc
176}
177
178/// A DAV resource path relative to the account's discovered collection.
179///
180/// It is never a URL. The server joins it to the cached iCloud host.
181#[derive(Clone, PartialEq, Eq, Hash, Debug)]
182pub struct ResourcePath(String);
183
184impl ResourcePath {
185    /// Returns the path.
186    #[must_use]
187    pub fn as_str(&self) -> &str {
188        &self.0
189    }
190}
191
192impl TryFrom<&str> for ResourcePath {
193    type Error = ParseError;
194
195    fn try_from(value: &str) -> Result<Self, Self::Error> {
196        if !is_relative_collection_path(value) {
197            return Err(ParseError::ResourcePath);
198        }
199        Ok(Self(value.to_owned()))
200    }
201}
202
203impl fmt::Display for ResourcePath {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_str(self.as_str())
206    }
207}
208
209/// An HTTP `ETag` for a conditional DAV write.
210#[derive(Clone, PartialEq, Eq, Hash, Debug)]
211pub struct ETag(String);
212
213impl ETag {
214    /// Returns the `ETag`, including any `W/` weak prefix and quotes.
215    #[must_use]
216    pub fn as_str(&self) -> &str {
217        &self.0
218    }
219}
220
221impl TryFrom<&str> for ETag {
222    type Error = ParseError;
223
224    fn try_from(value: &str) -> Result<Self, Self::Error> {
225        if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) {
226            return Err(ParseError::ETag);
227        }
228        Ok(Self(value.to_owned()))
229    }
230}
231
232impl fmt::Display for ETag {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        f.write_str(self.as_str())
235    }
236}
237
238/// A collection-relative path: no scheme, no leading slash, no `.` or `..` segment.
239///
240/// A single trailing slash is kept so a collection path can name a directory.
241/// Percent-encoded segments are decoded before the `.` / `..` check.
242fn is_relative_collection_path(value: &str) -> bool {
243    if value.is_empty()
244        || value.contains("://")
245        || value.starts_with('/')
246        || value.starts_with('\\')
247    {
248        return false;
249    }
250    if value.chars().any(|c| c.is_control() || c == '\\') {
251        return false;
252    }
253    let body = value.strip_suffix('/').unwrap_or(value);
254    if body.is_empty() || body.ends_with('/') {
255        return false;
256    }
257    body.split('/').all(valid_segment)
258}
259
260fn valid_segment(segment: &str) -> bool {
261    let Some(decoded) = percent_decode(segment) else {
262        return false;
263    };
264    if decoded.is_empty() || decoded == "." || decoded == ".." {
265        return false;
266    }
267    !decoded
268        .chars()
269        .any(|c| c == '/' || c == '\\' || c == ':' || c.is_control())
270}
271
272fn percent_decode(segment: &str) -> Option<String> {
273    if !segment.contains('%') {
274        return Some(segment.to_owned());
275    }
276    let bytes = segment.as_bytes();
277    let mut out = Vec::with_capacity(bytes.len());
278    let mut index = 0;
279    while index < bytes.len() {
280        if bytes[index] == b'%' {
281            let hi = from_hex(*bytes.get(index + 1)?)?;
282            let lo = from_hex(*bytes.get(index + 2)?)?;
283            out.push((hi << 4) | lo);
284            index += 3;
285        } else {
286            out.push(bytes[index]);
287            index += 1;
288        }
289    }
290    String::from_utf8(out).ok()
291}
292
293fn from_hex(byte: u8) -> Option<u8> {
294    match byte {
295        b'0'..=b'9' => Some(byte - b'0'),
296        b'a'..=b'f' => Some(byte - b'a' + 10),
297        b'A'..=b'F' => Some(byte - b'A' + 10),
298        _ => None,
299    }
300}