Skip to main content

ibridge_core/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Domain newtypes, provider traits and the core error type.
4
5mod account;
6mod calendar;
7mod contacts;
8mod error;
9mod ids;
10mod mail;
11
12pub use account::AppleId;
13pub use calendar::{
14    Calendar, CalendarProvider, CompletedFilter, Event, EventDraft, EventList, EventQuery,
15    Reminder, ReminderDraft, ReminderList, ReminderPage, RemindersProvider, UPGRADED_LISTS_NOTE,
16    UpdateScope,
17};
18pub use contacts::{
19    Contact, ContactDraft, ContactList, ContactQuery, ContactUpdate, ContactsProvider, GroupChange,
20    GroupRef, LabeledValue,
21};
22pub use error::{CoreError, IdError, ParseError};
23pub use ids::{ETag, ResourcePath, decode, decode_resource, encode, encode_resource};
24pub use mail::{
25    Attachment, AttachmentInfo, Draft, FlagChange, MailPage, MailProvider, MailSearch, Mailbox,
26    MailboxPath, MailboxRole, Message, MessageId, MessageSummary, OneClickFailure, Uid,
27    UidValidity, Unsubscribe, UnsubscribeMail, UnsubscribeMethod,
28};
29
30#[cfg(test)]
31mod provider_tests {
32    use super::{
33        CalendarProvider, CompletedFilter, ContactQuery, ContactsProvider, CoreError, MailProvider,
34        RemindersProvider,
35    };
36
37    fn require_send<T: Send>(value: T) -> T {
38        value
39    }
40
41    struct NullProvider;
42
43    #[expect(
44        clippy::unused_async_trait_impl,
45        reason = "null provider returns immediately"
46    )]
47    impl MailProvider for NullProvider {
48        async fn list_mailboxes(&self) -> Result<Vec<super::Mailbox>, CoreError> {
49            Err(CoreError::Unsupported("null"))
50        }
51        async fn search(&self, _query: &super::MailSearch) -> Result<super::MailPage, CoreError> {
52            Err(CoreError::Unsupported("null"))
53        }
54        async fn get_message(&self, _id: &super::MessageId) -> Result<super::Message, CoreError> {
55            Err(CoreError::Unsupported("null"))
56        }
57        async fn get_attachment(
58            &self,
59            _id: &super::MessageId,
60            _part: &str,
61        ) -> Result<super::Attachment, CoreError> {
62            Err(CoreError::Unsupported("null"))
63        }
64        async fn create_draft(&self, _draft: &super::Draft) -> Result<super::MessageId, CoreError> {
65            Err(CoreError::Unsupported("null"))
66        }
67        async fn send(&self, _draft: &super::Draft) -> Result<super::MessageId, CoreError> {
68            Err(CoreError::Unsupported("null"))
69        }
70        async fn move_to(
71            &self,
72            _id: &super::MessageId,
73            _destination: &super::MailboxPath,
74        ) -> Result<(), CoreError> {
75            Err(CoreError::Unsupported("null"))
76        }
77        async fn set_flags(
78            &self,
79            _id: &super::MessageId,
80            _flags: &super::FlagChange,
81        ) -> Result<(), CoreError> {
82            Err(CoreError::Unsupported("null"))
83        }
84    }
85
86    #[expect(
87        clippy::unused_async_trait_impl,
88        reason = "null provider returns immediately"
89    )]
90    impl CalendarProvider for NullProvider {
91        async fn list_calendars(&self) -> Result<Vec<super::Calendar>, CoreError> {
92            Err(CoreError::Unsupported("null"))
93        }
94        async fn list_events(
95            &self,
96            _query: &super::EventQuery,
97        ) -> Result<super::EventList, CoreError> {
98            Err(CoreError::Unsupported("null"))
99        }
100        async fn get_event(&self, _path: &super::ResourcePath) -> Result<super::Event, CoreError> {
101            Err(CoreError::Unsupported("null"))
102        }
103        async fn create_event(
104            &self,
105            _calendar: &super::ResourcePath,
106            _draft: &super::EventDraft,
107        ) -> Result<super::ResourcePath, CoreError> {
108            Err(CoreError::Unsupported("null"))
109        }
110        async fn update_event(
111            &self,
112            _path: &super::ResourcePath,
113            _etag: &super::ETag,
114            _draft: &super::EventDraft,
115            _scope: &super::UpdateScope,
116        ) -> Result<super::ETag, CoreError> {
117            Err(CoreError::Unsupported("null"))
118        }
119        async fn delete_event(
120            &self,
121            _path: &super::ResourcePath,
122            _etag: &super::ETag,
123        ) -> Result<(), CoreError> {
124            Err(CoreError::Unsupported("null"))
125        }
126    }
127
128    #[expect(
129        clippy::unused_async_trait_impl,
130        reason = "null provider returns immediately"
131    )]
132    impl RemindersProvider for NullProvider {
133        async fn list_lists(&self) -> Result<Vec<super::ReminderList>, CoreError> {
134            Err(CoreError::Unsupported("null"))
135        }
136        async fn list(
137            &self,
138            _list: Option<&super::ResourcePath>,
139            _completed: CompletedFilter,
140        ) -> Result<super::ReminderPage, CoreError> {
141            Err(CoreError::Unsupported("null"))
142        }
143        async fn get(&self, _path: &super::ResourcePath) -> Result<super::Reminder, CoreError> {
144            Err(CoreError::Unsupported("null"))
145        }
146        async fn create(
147            &self,
148            _list: &super::ResourcePath,
149            _draft: &super::ReminderDraft,
150        ) -> Result<super::ResourcePath, CoreError> {
151            Err(CoreError::Unsupported("null"))
152        }
153        async fn update(
154            &self,
155            _path: &super::ResourcePath,
156            _etag: &super::ETag,
157            _draft: &super::ReminderDraft,
158        ) -> Result<super::ETag, CoreError> {
159            Err(CoreError::Unsupported("null"))
160        }
161        async fn delete(
162            &self,
163            _path: &super::ResourcePath,
164            _etag: &super::ETag,
165        ) -> Result<(), CoreError> {
166            Err(CoreError::Unsupported("null"))
167        }
168    }
169
170    #[expect(
171        clippy::unused_async_trait_impl,
172        reason = "null provider returns immediately"
173    )]
174    impl ContactsProvider for NullProvider {
175        async fn search(&self, _query: &ContactQuery) -> Result<super::ContactList, CoreError> {
176            Err(CoreError::Unsupported("null"))
177        }
178        async fn get(&self, _path: &super::ResourcePath) -> Result<super::Contact, CoreError> {
179            Err(CoreError::Unsupported("null"))
180        }
181        async fn create(
182            &self,
183            _draft: &super::ContactDraft,
184        ) -> Result<super::ResourcePath, CoreError> {
185            Err(CoreError::Unsupported("null"))
186        }
187        async fn update(
188            &self,
189            _path: &super::ResourcePath,
190            _etag: &super::ETag,
191            _update: &super::ContactUpdate,
192        ) -> Result<super::ETag, CoreError> {
193            Err(CoreError::Unsupported("null"))
194        }
195        async fn delete(
196            &self,
197            _path: &super::ResourcePath,
198            _etag: &super::ETag,
199        ) -> Result<(), CoreError> {
200            Err(CoreError::Unsupported("null"))
201        }
202        async fn set_group_membership(
203            &self,
204            _group: &super::ResourcePath,
205            _contact: &super::ResourcePath,
206            _change: super::GroupChange,
207        ) -> Result<(), CoreError> {
208            Err(CoreError::Unsupported("null"))
209        }
210    }
211
212    fn assert_mail_send<P: MailProvider + ?Sized>(provider: &P) {
213        let _future = require_send(provider.list_mailboxes());
214    }
215
216    fn assert_calendar_send<P: CalendarProvider + ?Sized>(provider: &P) {
217        let _future = require_send(provider.list_calendars());
218    }
219
220    fn assert_reminders_send<P: RemindersProvider + ?Sized>(provider: &P) {
221        let _future = require_send(provider.list_lists());
222    }
223
224    fn assert_contacts_send<P: ContactsProvider + ?Sized>(provider: &P) {
225        let query = ContactQuery {
226            text: String::new(),
227            limit: 1,
228            include_groups: false,
229        };
230        let _future = require_send(provider.search(&query));
231    }
232
233    #[test]
234    fn provider_futures_are_send() {
235        let provider = NullProvider;
236        assert_mail_send(&provider);
237        assert_calendar_send(&provider);
238        assert_reminders_send(&provider);
239        assert_contacts_send(&provider);
240    }
241
242    #[test]
243    fn core_error_display_has_no_secrets() {
244        let secret = "app-password-do-not-leak";
245        let err = CoreError::Protocol(secret.to_owned());
246        assert_eq!(err.protocol_detail(), Some(secret));
247        assert!(
248            !err.to_string().contains(secret),
249            "display must not contain the protocol detail"
250        );
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use proptest::prelude::*;
257
258    use super::{
259        AppleId, ETag, MailboxPath, MessageId, ResourcePath, Uid, UidValidity, decode, encode,
260    };
261    use crate::ids::encode_raw;
262
263    #[test]
264    fn apple_id_rejects_custom_domain_hint() {
265        let err = AppleId::try_from("ada@example.com").expect_err("custom domain must be rejected");
266        let msg = err.to_string();
267        assert!(
268            msg.contains("@icloud.com") && msg.contains("@me.com") && msg.contains("@mac.com"),
269            "error should hint at the primary domains, got {msg}"
270        );
271        assert!(AppleId::try_from("ada@icloud.com").is_ok());
272        assert!(AppleId::try_from("ada@me.com").is_ok());
273        assert!(AppleId::try_from("ada@mac.com").is_ok());
274    }
275
276    #[test]
277    fn apple_id_spellings_that_differ_only_in_case_are_one_id() {
278        let mixed = AppleId::try_from("Ada.Lovelace@iCloud.com").expect("mixed case");
279        let lower = AppleId::try_from("ada.lovelace@icloud.com").expect("lower case");
280        assert_eq!(mixed, lower, "Apple does not tell the spellings apart");
281        assert_eq!(mixed.as_str(), "ada.lovelace@icloud.com");
282    }
283
284    #[test]
285    fn uid_rejects_zero() {
286        assert!(Uid::try_from(0).is_err(), "zero uid must be rejected");
287        assert!(
288            UidValidity::try_from(0).is_err(),
289            "zero uid validity must be rejected"
290        );
291        assert_eq!(Uid::try_from(1).expect("one").get(), 1);
292        assert_eq!(UidValidity::try_from(42).expect("validity").get(), 42);
293    }
294
295    #[test]
296    fn resource_path_rejects_absolute_url() {
297        for url in [
298            "https://caldav.icloud.com/123/calendars/a.ics",
299            "http://evil.example/a",
300            "https://contacts.icloud.com/1/card.vcf",
301            "//caldav.icloud.com/1/a",
302        ] {
303            assert!(
304                ResourcePath::try_from(url).is_err(),
305                "{url} must be rejected"
306            );
307        }
308        assert!(ResourcePath::try_from("calendars/home/event.ics").is_ok());
309    }
310
311    #[test]
312    fn resource_path_rejects_dotdot() {
313        for path in [
314            "..",
315            "../secret",
316            "calendars/../secret",
317            "calendars/../../etc/passwd",
318            "foo/..",
319            "%2e%2e",
320            "calendars/%2e%2e/secret",
321            "calendars/%2E%2E/secret",
322        ] {
323            assert!(
324                ResourcePath::try_from(path).is_err(),
325                "{path} must be rejected"
326            );
327        }
328        assert!(ResourcePath::try_from("calendars/home/event.ics").is_ok());
329    }
330
331    proptest! {
332        #[test]
333        fn apple_id_roundtrip(
334            local in "[a-z][a-z0-9]{0,12}",
335            domain in prop_oneof![Just("icloud.com"), Just("me.com"), Just("mac.com")],
336        ) {
337            let address = format!("{local}@{domain}");
338            let parsed = AppleId::try_from(address.as_str()).unwrap();
339            prop_assert_eq!(parsed.as_str(), address.as_str());
340        }
341
342        #[test]
343        fn uid_roundtrip(value in 1u32..=u32::MAX) {
344            prop_assert_eq!(Uid::try_from(value).unwrap().get(), value);
345            prop_assert_eq!(UidValidity::try_from(value).unwrap().get(), value);
346        }
347
348        #[test]
349        fn mailbox_path_roundtrip(path in "[A-Za-z0-9][A-Za-z0-9 ]{0,31}") {
350            let parsed = MailboxPath::try_from(path.as_str()).unwrap();
351            prop_assert_eq!(parsed.as_str(), path.as_str());
352        }
353
354        #[test]
355        fn resource_path_roundtrip(segments in prop::collection::vec("[a-z0-9]{1,8}", 1..4usize)) {
356            let path = segments.join("/");
357            let parsed = ResourcePath::try_from(path.as_str()).unwrap();
358            prop_assert_eq!(parsed.as_str(), path.as_str());
359        }
360
361        #[test]
362        fn etag_roundtrip(token in "[A-Za-z0-9]{1,16}") {
363            let etag = format!("\"{token}\"");
364            let parsed = ETag::try_from(etag.as_str()).unwrap();
365            prop_assert_eq!(parsed.as_str(), etag.as_str());
366        }
367
368        #[test]
369        fn message_id_roundtrip(
370            mailbox in "[A-Za-z][A-Za-z0-9]{0,16}",
371            validity in 1u32..=u32::MAX,
372            uid in 1u32..=u32::MAX,
373        ) {
374            let id = MessageId {
375                mailbox: MailboxPath::try_from(mailbox.as_str()).unwrap(),
376                validity: UidValidity::try_from(validity).unwrap(),
377                uid: Uid::try_from(uid).unwrap(),
378            };
379            let decoded = decode(&encode(&id)).unwrap();
380            prop_assert_eq!(decoded, id);
381        }
382    }
383
384    #[test]
385    fn resource_id_roundtrips() {
386        let path = ResourcePath::try_from("calendars/home/event one.ics").expect("path");
387        let token = super::encode_resource(&path);
388        assert!(!token.is_empty(), "the token carries the path");
389        assert!(
390            !token.contains('/') && !token.contains("home"),
391            "the token is opaque base64url, got {token}"
392        );
393        assert_eq!(super::decode_resource(&token).expect("decodes"), path);
394    }
395
396    #[test]
397    fn resource_id_rejects_message_tokens_and_tampering() {
398        let message = MessageId {
399            mailbox: MailboxPath::try_from("INBOX").expect("mailbox"),
400            validity: UidValidity::try_from(9).expect("validity"),
401            uid: Uid::try_from(4).expect("uid"),
402        };
403        assert!(
404            super::decode_resource(&encode(&message)).is_err(),
405            "a message token is not a resource token"
406        );
407        let path = ResourcePath::try_from("calendars/home/a.ics").expect("path");
408        let mut bytes = super::encode_resource(&path).into_bytes();
409        assert!(!bytes.is_empty(), "the token carries the path");
410        let index = bytes.len() / 2;
411        bytes[index] = if bytes[index] == b'A' { b'B' } else { b'A' };
412        let tampered = String::from_utf8(bytes).expect("ascii token");
413        assert!(super::decode_resource(&tampered).is_err());
414        assert!(super::decode_resource("https://caldav.icloud.com/1/a.ics").is_err());
415    }
416
417    #[test]
418    fn decode_rejects_tampered() {
419        let id = MessageId {
420            mailbox: MailboxPath::try_from("INBOX").expect("mailbox"),
421            validity: UidValidity::try_from(9).expect("validity"),
422            uid: Uid::try_from(4).expect("uid"),
423        };
424        let token = encode(&id);
425        let mut bytes = token.into_bytes();
426        let index = bytes.len() / 2;
427        bytes[index] = if bytes[index] == b'A' { b'B' } else { b'A' };
428        let tampered = String::from_utf8(bytes).expect("ascii token");
429        assert!(
430            decode(&tampered).is_err(),
431            "a flipped character must not decode"
432        );
433    }
434
435    #[test]
436    fn decode_rejects_url_payload() {
437        let url = "https://p12-caldav.icloud.com/123/calendars/x.ics";
438        assert!(decode(url).is_err(), "a raw URL is not an id");
439        let crafted = encode_raw(url, 7, 9);
440        assert!(
441            decode(&crafted).is_err(),
442            "a length-prefixed URL payload must not decode"
443        );
444    }
445}