ibridge-core 1.0.1

Domain newtypes, provider traits and the core error type.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// SPDX-License-Identifier: Apache-2.0

//! Domain newtypes, provider traits and the core error type.

mod account;
mod calendar;
mod contacts;
mod error;
mod ids;
mod mail;

pub use account::AppleId;
pub use calendar::{
    Calendar, CalendarProvider, CompletedFilter, Event, EventDraft, EventList, EventQuery,
    Reminder, ReminderDraft, ReminderList, ReminderPage, RemindersProvider, UPGRADED_LISTS_NOTE,
    UpdateScope,
};
pub use contacts::{
    Contact, ContactDraft, ContactList, ContactQuery, ContactUpdate, ContactsProvider, GroupChange,
    GroupRef, LabeledValue,
};
pub use error::{CoreError, IdError, ParseError};
pub use ids::{ETag, ResourcePath, decode, decode_resource, encode, encode_resource};
pub use mail::{
    Attachment, AttachmentInfo, Draft, FlagChange, MailPage, MailProvider, MailSearch, Mailbox,
    MailboxPath, MailboxRole, Message, MessageId, MessageSummary, Uid, UidValidity,
};

#[cfg(test)]
mod provider_tests {
    use super::{
        CalendarProvider, CompletedFilter, ContactQuery, ContactsProvider, CoreError, MailProvider,
        RemindersProvider,
    };

    fn require_send<T: Send>(value: T) -> T {
        value
    }

    struct NullProvider;

    #[expect(
        clippy::unused_async_trait_impl,
        reason = "null provider returns immediately"
    )]
    impl MailProvider for NullProvider {
        async fn list_mailboxes(&self) -> Result<Vec<super::Mailbox>, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn search(&self, _query: &super::MailSearch) -> Result<super::MailPage, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn get_message(&self, _id: &super::MessageId) -> Result<super::Message, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn get_attachment(
            &self,
            _id: &super::MessageId,
            _part: &str,
        ) -> Result<super::Attachment, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn create_draft(&self, _draft: &super::Draft) -> Result<super::MessageId, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn send(&self, _draft: &super::Draft) -> Result<super::MessageId, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn move_to(
            &self,
            _id: &super::MessageId,
            _destination: &super::MailboxPath,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn set_flags(
            &self,
            _id: &super::MessageId,
            _flags: &super::FlagChange,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
    }

    #[expect(
        clippy::unused_async_trait_impl,
        reason = "null provider returns immediately"
    )]
    impl CalendarProvider for NullProvider {
        async fn list_calendars(&self) -> Result<Vec<super::Calendar>, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn list_events(
            &self,
            _query: &super::EventQuery,
        ) -> Result<super::EventList, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn get_event(&self, _path: &super::ResourcePath) -> Result<super::Event, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn create_event(
            &self,
            _calendar: &super::ResourcePath,
            _draft: &super::EventDraft,
        ) -> Result<super::ResourcePath, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn update_event(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
            _draft: &super::EventDraft,
            _scope: &super::UpdateScope,
        ) -> Result<super::ETag, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn delete_event(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
    }

    #[expect(
        clippy::unused_async_trait_impl,
        reason = "null provider returns immediately"
    )]
    impl RemindersProvider for NullProvider {
        async fn list_lists(&self) -> Result<Vec<super::ReminderList>, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn list(
            &self,
            _list: Option<&super::ResourcePath>,
            _completed: CompletedFilter,
        ) -> Result<super::ReminderPage, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn get(&self, _path: &super::ResourcePath) -> Result<super::Reminder, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn create(
            &self,
            _list: &super::ResourcePath,
            _draft: &super::ReminderDraft,
        ) -> Result<super::ResourcePath, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn update(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
            _draft: &super::ReminderDraft,
        ) -> Result<super::ETag, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn delete(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
    }

    #[expect(
        clippy::unused_async_trait_impl,
        reason = "null provider returns immediately"
    )]
    impl ContactsProvider for NullProvider {
        async fn search(&self, _query: &ContactQuery) -> Result<super::ContactList, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn get(&self, _path: &super::ResourcePath) -> Result<super::Contact, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn create(
            &self,
            _draft: &super::ContactDraft,
        ) -> Result<super::ResourcePath, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn update(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
            _update: &super::ContactUpdate,
        ) -> Result<super::ETag, CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn delete(
            &self,
            _path: &super::ResourcePath,
            _etag: &super::ETag,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
        async fn set_group_membership(
            &self,
            _group: &super::ResourcePath,
            _contact: &super::ResourcePath,
            _change: super::GroupChange,
        ) -> Result<(), CoreError> {
            Err(CoreError::Unsupported("null"))
        }
    }

    fn assert_mail_send<P: MailProvider + ?Sized>(provider: &P) {
        let _future = require_send(provider.list_mailboxes());
    }

    fn assert_calendar_send<P: CalendarProvider + ?Sized>(provider: &P) {
        let _future = require_send(provider.list_calendars());
    }

    fn assert_reminders_send<P: RemindersProvider + ?Sized>(provider: &P) {
        let _future = require_send(provider.list_lists());
    }

    fn assert_contacts_send<P: ContactsProvider + ?Sized>(provider: &P) {
        let query = ContactQuery {
            text: String::new(),
            limit: 1,
            include_groups: false,
        };
        let _future = require_send(provider.search(&query));
    }

    #[test]
    fn provider_futures_are_send() {
        let provider = NullProvider;
        assert_mail_send(&provider);
        assert_calendar_send(&provider);
        assert_reminders_send(&provider);
        assert_contacts_send(&provider);
    }

    #[test]
    fn core_error_display_has_no_secrets() {
        let secret = "app-password-do-not-leak";
        let err = CoreError::Protocol(secret.to_owned());
        assert_eq!(err.protocol_detail(), Some(secret));
        assert!(
            !err.to_string().contains(secret),
            "display must not contain the protocol detail"
        );
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::{
        AppleId, ETag, MailboxPath, MessageId, ResourcePath, Uid, UidValidity, decode, encode,
    };
    use crate::ids::encode_raw;

    #[test]
    fn apple_id_rejects_custom_domain_hint() {
        let err = AppleId::try_from("ada@example.com").expect_err("custom domain must be rejected");
        let msg = err.to_string();
        assert!(
            msg.contains("@icloud.com") && msg.contains("@me.com") && msg.contains("@mac.com"),
            "error should hint at the primary domains, got {msg}"
        );
        assert!(AppleId::try_from("ada@icloud.com").is_ok());
        assert!(AppleId::try_from("ada@me.com").is_ok());
        assert!(AppleId::try_from("ada@mac.com").is_ok());
    }

    #[test]
    fn apple_id_spellings_that_differ_only_in_case_are_one_id() {
        let mixed = AppleId::try_from("Ada.Lovelace@iCloud.com").expect("mixed case");
        let lower = AppleId::try_from("ada.lovelace@icloud.com").expect("lower case");
        assert_eq!(mixed, lower, "Apple does not tell the spellings apart");
        assert_eq!(mixed.as_str(), "ada.lovelace@icloud.com");
    }

    #[test]
    fn uid_rejects_zero() {
        assert!(Uid::try_from(0).is_err(), "zero uid must be rejected");
        assert!(
            UidValidity::try_from(0).is_err(),
            "zero uid validity must be rejected"
        );
        assert_eq!(Uid::try_from(1).expect("one").get(), 1);
        assert_eq!(UidValidity::try_from(42).expect("validity").get(), 42);
    }

    #[test]
    fn resource_path_rejects_absolute_url() {
        for url in [
            "https://caldav.icloud.com/123/calendars/a.ics",
            "http://evil.example/a",
            "https://contacts.icloud.com/1/card.vcf",
            "//caldav.icloud.com/1/a",
        ] {
            assert!(
                ResourcePath::try_from(url).is_err(),
                "{url} must be rejected"
            );
        }
        assert!(ResourcePath::try_from("calendars/home/event.ics").is_ok());
    }

    #[test]
    fn resource_path_rejects_dotdot() {
        for path in [
            "..",
            "../secret",
            "calendars/../secret",
            "calendars/../../etc/passwd",
            "foo/..",
            "%2e%2e",
            "calendars/%2e%2e/secret",
            "calendars/%2E%2E/secret",
        ] {
            assert!(
                ResourcePath::try_from(path).is_err(),
                "{path} must be rejected"
            );
        }
        assert!(ResourcePath::try_from("calendars/home/event.ics").is_ok());
    }

    proptest! {
        #[test]
        fn apple_id_roundtrip(
            local in "[a-z][a-z0-9]{0,12}",
            domain in prop_oneof![Just("icloud.com"), Just("me.com"), Just("mac.com")],
        ) {
            let address = format!("{local}@{domain}");
            let parsed = AppleId::try_from(address.as_str()).unwrap();
            prop_assert_eq!(parsed.as_str(), address.as_str());
        }

        #[test]
        fn uid_roundtrip(value in 1u32..=u32::MAX) {
            prop_assert_eq!(Uid::try_from(value).unwrap().get(), value);
            prop_assert_eq!(UidValidity::try_from(value).unwrap().get(), value);
        }

        #[test]
        fn mailbox_path_roundtrip(path in "[A-Za-z0-9][A-Za-z0-9 ]{0,31}") {
            let parsed = MailboxPath::try_from(path.as_str()).unwrap();
            prop_assert_eq!(parsed.as_str(), path.as_str());
        }

        #[test]
        fn resource_path_roundtrip(segments in prop::collection::vec("[a-z0-9]{1,8}", 1..4usize)) {
            let path = segments.join("/");
            let parsed = ResourcePath::try_from(path.as_str()).unwrap();
            prop_assert_eq!(parsed.as_str(), path.as_str());
        }

        #[test]
        fn etag_roundtrip(token in "[A-Za-z0-9]{1,16}") {
            let etag = format!("\"{token}\"");
            let parsed = ETag::try_from(etag.as_str()).unwrap();
            prop_assert_eq!(parsed.as_str(), etag.as_str());
        }

        #[test]
        fn message_id_roundtrip(
            mailbox in "[A-Za-z][A-Za-z0-9]{0,16}",
            validity in 1u32..=u32::MAX,
            uid in 1u32..=u32::MAX,
        ) {
            let id = MessageId {
                mailbox: MailboxPath::try_from(mailbox.as_str()).unwrap(),
                validity: UidValidity::try_from(validity).unwrap(),
                uid: Uid::try_from(uid).unwrap(),
            };
            let decoded = decode(&encode(&id)).unwrap();
            prop_assert_eq!(decoded, id);
        }
    }

    #[test]
    fn resource_id_roundtrips() {
        let path = ResourcePath::try_from("calendars/home/event one.ics").expect("path");
        let token = super::encode_resource(&path);
        assert!(!token.is_empty(), "the token carries the path");
        assert!(
            !token.contains('/') && !token.contains("home"),
            "the token is opaque base64url, got {token}"
        );
        assert_eq!(super::decode_resource(&token).expect("decodes"), path);
    }

    #[test]
    fn resource_id_rejects_message_tokens_and_tampering() {
        let message = MessageId {
            mailbox: MailboxPath::try_from("INBOX").expect("mailbox"),
            validity: UidValidity::try_from(9).expect("validity"),
            uid: Uid::try_from(4).expect("uid"),
        };
        assert!(
            super::decode_resource(&encode(&message)).is_err(),
            "a message token is not a resource token"
        );
        let path = ResourcePath::try_from("calendars/home/a.ics").expect("path");
        let mut bytes = super::encode_resource(&path).into_bytes();
        assert!(!bytes.is_empty(), "the token carries the path");
        let index = bytes.len() / 2;
        bytes[index] = if bytes[index] == b'A' { b'B' } else { b'A' };
        let tampered = String::from_utf8(bytes).expect("ascii token");
        assert!(super::decode_resource(&tampered).is_err());
        assert!(super::decode_resource("https://caldav.icloud.com/1/a.ics").is_err());
    }

    #[test]
    fn decode_rejects_tampered() {
        let id = MessageId {
            mailbox: MailboxPath::try_from("INBOX").expect("mailbox"),
            validity: UidValidity::try_from(9).expect("validity"),
            uid: Uid::try_from(4).expect("uid"),
        };
        let token = encode(&id);
        let mut bytes = token.into_bytes();
        let index = bytes.len() / 2;
        bytes[index] = if bytes[index] == b'A' { b'B' } else { b'A' };
        let tampered = String::from_utf8(bytes).expect("ascii token");
        assert!(
            decode(&tampered).is_err(),
            "a flipped character must not decode"
        );
    }

    #[test]
    fn decode_rejects_url_payload() {
        let url = "https://p12-caldav.icloud.com/123/calendars/x.ics";
        assert!(decode(url).is_err(), "a raw URL is not an id");
        let crafted = encode_raw(url, 7, 9);
        assert!(
            decode(&crafted).is_err(),
            "a length-prefixed URL payload must not decode"
        );
    }
}