pim_io.rs
⎇
Raw
1//! Public feeds, import and export of calendars and address books.
2
3use crate::common::*;
4use axum::http::{Method, StatusCode};
5use serde_json::{Value, json};
6
7const PW: &str = "secret12345";
8const CAL: &str = "/pim/calendars/alice/default/";
9
10struct Io {
11 env: Env,
12 alice: Client,
13}
14
15impl Io {
16 async fn new() -> Self {
17 let env = Env::new().await;
18 let admin = env.admin().await;
19 create_user(&admin, "alice", PW, &[]).await;
20 create_user(&admin, "bob", PW, &[]).await;
21 let alice = login(&env, "alice", PW).await;
22 Io { env, alice }
23 }
24
25 async fn dav(&self, user: &str, verb: &str, path: &str, body: &str) -> Resp {
26 let auth = basic(user, PW);
27 // Without Depth, PROPFIND lists only the collection itself.
28 Client::new(self.env.app.clone())
29 .raw(
30 Method::from_bytes(verb.as_bytes()).unwrap(),
31 path,
32 &[("authorization", &auth), ("depth", "1")],
33 body.as_bytes().to_vec(),
34 )
35 .await
36 }
37
38 async fn anon(&self, path: &str, headers: &[(&str, &str)]) -> Resp {
39 Client::new(self.env.app.clone())
40 .raw(Method::GET, path, headers, Vec::new())
41 .await
42 }
43
44 /// The id of alice's collection with this CalDAV/CardDAV URL.
45 async fn id(&self, url: &str) -> i64 {
46 let list = self.alice.get("/api/pim/collections").await.json();
47 list.as_array()
48 .unwrap()
49 .iter()
50 .find(|c| c["url"] == url)
51 .unwrap_or_else(|| panic!("no collection {url}: {list}"))["id"]
52 .as_i64()
53 .unwrap()
54 }
55
56 async fn link(&self, id: i64, body: Value) -> String {
57 let r = self
58 .alice
59 .post_json(&format!("/api/pim/collections/{id}/links"), &body)
60 .await;
61 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
62 r.json()["path"].as_str().unwrap().to_string()
63 }
64
65 async fn import(&self, id: i64, body: &str) -> Value {
66 let r = self
67 .alice
68 .raw(
69 Method::POST,
70 &format!("/api/pim/collections/{id}/import"),
71 &[("content-type", "text/calendar")],
72 body.as_bytes().to_vec(),
73 )
74 .await;
75 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
76 r.json()
77 }
78}
79
80fn event(uid: &str, summary: &str, extra: &str) -> String {
81 format!(
82 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\nBEGIN:VEVENT\r\nUID:{uid}\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T100000Z\r\nSUMMARY:{summary}\r\n{extra}END:VEVENT\r\nEND:VCALENDAR\r\n"
83 )
84}
85
86#[tokio::test]
87async fn feeds() {
88 let io = Io::new().await;
89 let cal = io.id(CAL).await;
90 let book = io.id("/pim/addressbooks/alice/default/").await;
91 for uid in ["a", "b"] {
92 let r = io
93 .dav(
94 "alice",
95 "PUT",
96 &format!("{CAL}{uid}.ics"),
97 &event(
98 uid,
99 "Secret plan",
100 "BEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER:-PT5M\r\nEND:VALARM\r\n",
101 ),
102 )
103 .await;
104 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
105 }
106
107 let r = io
108 .dav(
109 "alice",
110 "PUT",
111 &format!("{CAL}p.ics"),
112 &event("p", "Doctor", "CLASS:PRIVATE\r\n"),
113 )
114 .await;
115 assert_eq!(r.status, StatusCode::CREATED);
116
117 let full = io.link(cal, json!({})).await;
118 assert!(
119 full.starts_with("/feed/") && full.ends_with(".ics"),
120 "{full}"
121 );
122 let r = io.anon(&full, &[]).await;
123 assert_eq!(r.status, StatusCode::OK);
124 assert!(
125 r.header("content-type")
126 .unwrap()
127 .starts_with("text/calendar")
128 );
129 let text = r.text();
130 assert!(
131 text.contains("UID:a\r\n") && text.contains("UID:b\r\n"),
132 "{text}"
133 );
134 assert!(text.contains("X-WR-CALNAME:"));
135 assert!(text.contains("Secret plan"));
136 // A public link shows private events as busy time only.
137 assert!(
138 !text.contains("Doctor") && text.contains("SUMMARY:Busy"),
139 "{text}"
140 );
141 let etag = r.header("etag").unwrap();
142 let r = io.anon(&full, &[("if-none-match", &etag)]).await;
143 assert_eq!(r.status, StatusCode::NOT_MODIFIED);
144 // The extension is optional.
145 let bare = full.trim_end_matches(".ics");
146 assert_eq!(io.anon(bare, &[]).await.status, StatusCode::OK);
147
148 // A change gives a new ETag.
149 io.dav("alice", "PUT", &format!("{CAL}c.ics"), &event("c", "x", ""))
150 .await;
151 let r = io.anon(&full, &[("if-none-match", &etag)]).await;
152 assert_eq!(r.status, StatusCode::OK);
153
154 let busy = io.link(cal, json!({ "busy_only": true })).await;
155 let text = io.anon(&busy, &[]).await.text();
156 assert!(text.contains("SUMMARY:Busy"), "{text}");
157 assert!(
158 !text.contains("Secret plan") && !text.contains("VALARM"),
159 "{text}"
160 );
161 assert!(!text.contains("UID:a\r\n"), "UIDs are hashed: {text}");
162 // The owner's export keeps everything.
163 let export = io
164 .alice
165 .get(&format!("/api/pim/collections/{cal}/export"))
166 .await
167 .text();
168 assert!(export.contains("Doctor"));
169
170 let locked = io.link(cal, json!({ "password": "feedpass123" })).await;
171 let r = io.anon(&locked, &[]).await;
172 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
173 assert!(r.header("www-authenticate").is_some());
174 let wrong = basic("", "nope-nope");
175 for _ in 0..3 {
176 let r = io.anon(&locked, &[("authorization", &wrong)]).await;
177 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
178 }
179 let right = basic("anyone", "feedpass123");
180 assert_eq!(
181 io.anon(&locked, &[("authorization", &right)]).await.status,
182 StatusCode::OK
183 );
184
185 // A link cannot be made expired, so this one runs out.
186 let soon = (chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339();
187 let expired = io.link(cal, json!({ "expires_at": soon })).await;
188 tokio::time::sleep(std::time::Duration::from_millis(1200)).await;
189 assert_eq!(io.anon(&expired, &[]).await.status, StatusCode::GONE);
190
191 let cards = io.link(book, json!({})).await;
192 assert!(cards.ends_with(".vcf"));
193 let r = io.anon(&cards, &[]).await;
194 assert!(r.header("content-type").unwrap().starts_with("text/vcard"));
195 let r = io
196 .alice
197 .post_json(
198 &format!("/api/pim/collections/{book}/links"),
199 &json!({ "busy_only": true }),
200 )
201 .await;
202 assert_eq!(r.status, StatusCode::BAD_REQUEST);
203
204 // Only the owner sees and manages the links.
205 let bob = login(&io.env, "bob", PW).await;
206 assert_eq!(
207 bob.get(&format!("/api/pim/collections/{cal}/links"))
208 .await
209 .status,
210 StatusCode::NOT_FOUND
211 );
212 let list = io
213 .alice
214 .get(&format!("/api/pim/collections/{cal}/links"))
215 .await
216 .json();
217 assert_eq!(list.as_array().unwrap().len(), 4);
218 let first = list[0]["id"].as_i64().unwrap();
219 let r = io
220 .alice
221 .delete(&format!("/api/pim/collections/{cal}/links/{first}"))
222 .await;
223 assert_eq!(r.status, StatusCode::OK);
224 assert_eq!(io.anon(&full, &[]).await.status, StatusCode::NOT_FOUND);
225
226 // A deleted collection takes its links along.
227 let r = io
228 .dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
229 .await;
230 assert_eq!(r.status, StatusCode::CREATED);
231 let work = io.id("/pim/calendars/alice/work/").await;
232 let gone = io.link(work, json!({})).await;
233 assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::OK);
234 io.dav("alice", "DELETE", "/pim/calendars/alice/work/", "")
235 .await;
236 assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::NOT_FOUND);
237}
238
239#[tokio::test]
240async fn import_splits_and_updates() {
241 let io = Io::new().await;
242 let cal = io.id(CAL).await;
243 let file = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:x\r\nMETHOD:PUBLISH\r\n\
244 BEGIN:VEVENT\r\nUID:m\r\nDTSTART:20260105T100000Z\r\nRRULE:FREQ=DAILY;COUNT=3\r\nEND:VEVENT\r\n\
245 BEGIN:VEVENT\r\nUID:m\r\nRECURRENCE-ID:20260106T100000Z\r\nDTSTART:20260106T120000Z\r\nEND:VEVENT\r\n\
246 BEGIN:VEVENT\r\nDTSTART:20260107T100000Z\r\nSUMMARY:no uid\r\nEND:VEVENT\r\n\
247 BEGIN:VEVENT\r\nUID:nostart\r\nSUMMARY:no start\r\nEND:VEVENT\r\n\
248 BEGIN:VFREEBUSY\r\nUID:fb\r\nEND:VFREEBUSY\r\nEND:VCALENDAR\r\n";
249 let r = io.import(cal, file).await;
250 assert_eq!(r["created"], 2, "{r}");
251 assert_eq!(r["updated"], 0);
252 assert_eq!(r["skipped_total"], 2);
253 let reasons: Vec<&str> = r["skipped"]
254 .as_array()
255 .unwrap()
256 .iter()
257 .map(|s| s["reason"].as_str().unwrap())
258 .collect();
259 assert!(reasons.contains(&"supported-calendar-component"), "{r}");
260 assert!(reasons.contains(&"valid-calendar-data"), "{r}");
261
262 // The same file again updates, also the event that had no UID.
263 let r = io.import(cal, file).await;
264 assert_eq!(
265 (r["created"].as_i64(), r["updated"].as_i64()),
266 (Some(0), Some(2))
267 );
268
269 let r = io.dav("alice", "PROPFIND", CAL, "").await;
270 let listing = r.text();
271 assert_eq!(listing.matches(".ics</").count(), 2, "{listing}");
272 let export = io
273 .alice
274 .get(&format!("/api/pim/collections/{cal}/export"))
275 .await;
276 let text = export.text();
277 assert!(!text.contains("METHOD"));
278 assert!(text.contains("RECURRENCE-ID:20260106T100000Z"));
279 assert!(text.contains("DTSTAMP:"), "import adds DTSTAMP: {text}");
280}
281
282#[tokio::test]
283async fn an_import_of_meetings_long_over_sends_nothing() {
284 let io = Io::new().await;
285 let cal = io.id(CAL).await;
286 let people =
287 "ORGANIZER:mailto:alice@dovenest.invalid\r\nATTENDEE:mailto:bob@dovenest.invalid\r\n";
288 let r = io.import(cal, &event("old", "Old", people)).await;
289 assert_eq!(r["created"], 1, "{r}");
290 for path in ["/pim/calendars/bob/default/", "/pim/calendars/bob/inbox/"] {
291 let r = io.dav("bob", "PROPFIND", path, "").await;
292 assert!(!r.text().contains(".ics</"), "{path}: {}", r.text());
293 }
294 // Still a scheduling object, so later changes schedule as usual.
295 let listing = io.dav("alice", "PROPFIND", CAL, "").await.text();
296 let href = listing
297 .split("<d:href>")
298 .filter_map(|s| s.split("</d:href>").next())
299 .find(|h| h.ends_with(".ics"))
300 .unwrap_or_else(|| panic!("{listing}"))
301 .to_string();
302 let r = io.dav("alice", "GET", &href, "").await;
303 assert!(r.header("schedule-tag").is_some(), "{}", r.text());
304
305 let until = format!("RRULE:FREQ=DAILY;UNTIL=29991231T000000Z\r\n{people}");
306 let r = io.import(cal, &event("new", "New", &until)).await;
307 assert_eq!(r["created"], 1, "{r}");
308 let r = io
309 .dav("bob", "PROPFIND", "/pim/calendars/bob/inbox/", "")
310 .await;
311 assert!(r.text().contains(".ics</"), "{}", r.text());
312}
313
314#[tokio::test]
315async fn import_schedules_like_a_put_and_keeps_uniqueness() {
316 let io = Io::new().await;
317 let cal = io.id(CAL).await;
318 // A yearly series has not ended, so it schedules.
319 let meeting = event(
320 "meet",
321 "Meeting",
322 "RRULE:FREQ=YEARLY\r\nORGANIZER:mailto:alice@dovenest.invalid\r\nATTENDEE:mailto:bob@dovenest.invalid\r\n",
323 );
324 let r = io.import(cal, &meeting).await;
325 assert_eq!(r["created"], 1, "{r}");
326 // Stored as a scheduling object, with a Schedule-Tag like after a PUT.
327 let listing = io.dav("alice", "PROPFIND", CAL, "").await.text();
328 let href = listing
329 .split("<d:href>")
330 .filter_map(|s| s.split("</d:href>").next())
331 .find(|h| h.ends_with(".ics"))
332 .unwrap_or_else(|| panic!("{listing}"))
333 .to_string();
334 let r = io.dav("alice", "GET", &href, "").await;
335 assert!(r.header("schedule-tag").is_some());
336 // bob got a copy and the REQUEST, as after a PUT.
337 for path in ["/pim/calendars/bob/default/", "/pim/calendars/bob/inbox/"] {
338 let r = io.dav("bob", "PROPFIND", path, "").await;
339 assert!(r.text().contains(".ics</"), "{path}: {}", r.text());
340 }
341 // One scheduling object per UID and owner (RFC 6638, 3.2.4.1).
342 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
343 .await;
344 let work = io.id("/pim/calendars/alice/work/").await;
345 let r = io.import(work, &meeting).await;
346 assert_eq!(r["created"], 0);
347 assert_eq!(r["skipped"][0]["uid"], "meet");
348 assert_eq!(
349 r["skipped"][0]["reason"],
350 "unique-scheduling-object-resource"
351 );
352
353 // Imported again without bob, the meeting is cancelled for him.
354 let r = io.import(cal, &event("meet", "Meeting", "")).await;
355 assert_eq!(r["updated"], 1, "{r}");
356 let copy = io
357 .dav("bob", "PROPFIND", "/pim/calendars/bob/default/", "")
358 .await
359 .text();
360 let copy = copy
361 .split("<d:href>")
362 .filter_map(|s| s.split("</d:href>").next())
363 .find(|h| h.ends_with(".ics"))
364 .unwrap_or_else(|| panic!("{copy}"))
365 .to_string();
366 let r = io.dav("bob", "GET", &copy, "").await;
367 assert!(r.text().contains("STATUS:CANCELLED"), "{}", r.text());
368
369 // A read-only loan cannot be imported into.
370 let bob = login(&io.env, "bob", PW).await;
371 io.alice
372 .post_json(
373 &format!("/api/pim/collections/{cal}/shares"),
374 &json!({ "user": "bob", "mode": "ro" }),
375 )
376 .await;
377 let r = bob
378 .raw(
379 Method::POST,
380 &format!("/api/pim/collections/{cal}/import"),
381 &[("content-type", "text/calendar")],
382 event("x", "x", "").into_bytes(),
383 )
384 .await;
385 assert_eq!(r.status, StatusCode::FORBIDDEN);
386 // But exported.
387 let r = bob.get(&format!("/api/pim/collections/{cal}/export")).await;
388 assert_eq!(r.status, StatusCode::OK);
389}
390
391#[tokio::test]
392async fn export_round_trip() {
393 let io = Io::new().await;
394 let cal = io.id(CAL).await;
395 io.import(cal, &event("r1", "One", "")).await;
396 io.import(cal, &event("r2", "Two", "")).await;
397
398 let url = format!("/api/pim/collections/{cal}/export");
399 let r = io.alice.get(&url).await;
400 assert_eq!(r.status, StatusCode::OK);
401 let disposition = r.header("content-disposition").unwrap();
402 assert!(disposition.starts_with("attachment;") && disposition.contains(".ics"));
403 let exported = r.text();
404 // Download only: there is no saving into a folder.
405 let r = io.alice.post_json(&url, &json!({})).await;
406 assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
407
408 // The export imports back as the same objects.
409 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/copy/", "")
410 .await;
411 let copy = io.id("/pim/calendars/alice/copy/").await;
412 let r = io.import(copy, &exported).await;
413 assert_eq!(r["created"], 2, "{r}");
414
415 // vCards, one without UID.
416 let book = io.id("/pim/addressbooks/alice/default/").await;
417 let cards = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:One\r\nEND:VCARD\r\n\
418 BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Two\r\nEND:VCARD\r\n";
419 let r = io.import(book, cards).await;
420 assert_eq!(r["created"], 2, "{r}");
421 let r = io.import(book, cards).await;
422 assert_eq!(r["updated"], 2, "{r}");
423
424 // The system address book has no collection id of its own.
425 let r = io.alice.get("/api/pim/system/export").await;
426 assert_eq!(r.status, StatusCode::OK);
427 assert!(r.header("content-disposition").unwrap().contains(".vcf"));
428 assert!(r.text().contains("FN:alice"));
429}
430
431#[tokio::test]
432async fn import_as_a_new_collection() {
433 let io = Io::new().await;
434 let post = |query: &str, body: String| {
435 let (client, query) = (&io.alice, query.to_string());
436 async move {
437 let r = client
438 .raw(
439 Method::POST,
440 &format!("/api/pim/import?{query}"),
441 &[("content-type", "text/calendar")],
442 body.into_bytes(),
443 )
444 .await;
445 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
446 r.json()
447 }
448 };
449 let before = collections(&io.alice).await;
450 let vevent = |uid: &str, summary: &str| {
451 format!(
452 "BEGIN:VEVENT\r\nUID:{uid}\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T100000Z\r\nSUMMARY:{summary}\r\nEND:VEVENT\r\n"
453 )
454 };
455
456 // The file names itself and its color.
457 let ics = format!(
458 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:Ferien\r\nX-APPLE-CALENDAR-COLOR:#FF2968FF\r\n{}END:VCALENDAR\r\n",
459 vevent("f1", "Sommer")
460 );
461 let r = post("kind=calendar&file=holidays.ics&color=%2322c55e", ics).await;
462 assert_eq!(r["created"], 1, "{r}");
463 assert_eq!(r["collection"]["name"], "Ferien", "{r}");
464 assert_eq!(r["collection"]["color"], "#FF2968FF", "{r}");
465
466 // A typed name wins; without a color in the file the requested one counts.
467 let plain = format!(
468 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nCOLOR:teal\r\n{}END:VCALENDAR\r\n",
469 vevent("f2", "Winter")
470 );
471 let r = post("kind=calendar&name=Mine&file=x.ics&color=%2322c55e", plain).await;
472 assert_eq!(r["collection"]["name"], "Mine", "{r}");
473 assert_eq!(r["collection"]["color"], "#22c55e", "{r}");
474
475 // An address book takes the file name.
476 let vcf = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:Ann\r\nN:;Ann;;;\r\nEND:VCARD\r\n";
477 let r = post("kind=addressbook&file=Team%20contacts.vcf", vcf.to_string()).await;
478 assert_eq!(r["collection"]["name"], "Team contacts", "{r}");
479 assert_eq!(r["collection"]["kind"], "addressbook", "{r}");
480 assert_eq!(collections(&io.alice).await, before + 3);
481
482 // Nothing importable: reported, and no empty collection is left behind.
483 let broken = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:bad\r\nSUMMARY:no start\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
484 let r = post("kind=calendar&file=bad.ics", broken.to_string()).await;
485 assert_eq!(r["collection"], Value::Null, "{r}");
486 assert_eq!(r["skipped_total"], 1, "{r}");
487 assert_eq!(collections(&io.alice).await, before + 3);
488}
489
490async fn collections(c: &Client) -> usize {
491 c.get("/api/pim/collections")
492 .await
493 .json()
494 .as_array()
495 .unwrap()
496 .len()
497}
498
499#[tokio::test]
500async fn share_candidates_leave_out_owner_borrowers_and_disabled() {
501 let io = Io::new().await;
502 let admin = login(&io.env, "admin", "admin1234").await;
503 create_user(&admin, "carol", PW, &[]).await;
504 create_user(&admin, "dave", PW, &[]).await;
505 let dave = user_id(&admin, "dave").await;
506 let r = admin
507 .put_json(
508 &format!("/api/admin/users/{dave}"),
509 &json!({"active": false}),
510 )
511 .await;
512 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
513 let r = admin
514 .post_json(
515 "/api/admin/rooms",
516 &json!({"name": "atrium", "kind": "room"}),
517 )
518 .await;
519 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
520
521 let id = io.id(CAL).await;
522 let r = io
523 .alice
524 .post_json(
525 &format!("/api/pim/collections/{id}/shares"),
526 &json!({"user": "bob", "mode": "ro"}),
527 )
528 .await;
529 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
530
531 let names = |v: Value| -> Vec<String> {
532 v.as_array()
533 .unwrap()
534 .iter()
535 .map(|c| c["name"].as_str().unwrap().to_string())
536 .collect()
537 };
538 let r = io
539 .alice
540 .get(&format!("/api/pim/collections/{id}/shares/candidates"))
541 .await;
542 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
543 // Not alice herself, not bob (a borrower), not dave (disabled), no room.
544 assert_eq!(names(r.json()), ["admin", "carol"]);
545
546 // Only the owner may ask.
547 let bob = login(&io.env, "bob", PW).await;
548 let r = bob
549 .get(&format!("/api/pim/collections/{id}/shares/candidates"))
550 .await;
551 assert_eq!(r.status, StatusCode::NOT_FOUND);
552}
553
554#[tokio::test]
555async fn a_skipped_import_into_a_new_user_leaves_only_the_default_calendar() {
556 use server::db::PimKind;
557 let io = Io::new().await;
558 let client = login(&io.env, "bob", PW).await;
559 let broken = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:bad\r\nSUMMARY:no start\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
560 let r = client
561 .raw(
562 Method::POST,
563 "/api/pim/import?kind=calendar&file=bad.ics",
564 &[("content-type", "text/calendar")],
565 broken.as_bytes().to_vec(),
566 )
567 .await;
568 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
569 assert_eq!(r.json()["collection"], Value::Null);
570 assert_eq!(r.json()["skipped_total"], 1);
571
572 let db = &io.env.state.db;
573 let bob = db.find_user_by_name("bob").await.unwrap().unwrap();
574 let pid = db.principal_of(bob.id).await.unwrap();
575 let slugs: Vec<_> = db
576 .pim_collections(pid, PimKind::Calendar)
577 .await
578 .unwrap()
579 .into_iter()
580 .map(|c| c.slug)
581 .filter(|s| s != "inbox" && s != "outbox")
582 .collect();
583 assert_eq!(slugs, ["default"]);
584}
585
586#[tokio::test]
587async fn collection_names_and_descriptions_are_checked() {
588 let io = Io::new().await;
589 let create = |body: Value| {
590 let client = &io.alice;
591 async move { client.post_json("/api/pim/collections", &body).await }
592 };
593 let long = "x".repeat(257);
594 for name in [long.as_str(), "bell\u{7}"] {
595 let r = create(json!({"kind": "calendar", "name": name})).await;
596 assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name:?}");
597 }
598 let r =
599 create(json!({"kind": "calendar", "name": "Ok", "description": "x".repeat(1025)})).await;
600 assert_eq!(r.status, StatusCode::BAD_REQUEST);
601 let r = create(json!({"kind": "calendar", "name": "Ok", "description": "two\nlines"})).await;
602 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
603 let id = r.json()["id"].as_i64().unwrap();
604 let url = format!("/api/pim/collections/{id}");
605 for body in [
606 json!({"name": long}),
607 json!({"description": "x".repeat(1025)}),
608 ] {
609 let r = io.alice.put_json(&url, &body).await;
610 assert_eq!(r.status, StatusCode::BAD_REQUEST, "{body}");
611 }
612
613 // A file's own name that cannot be stored gives way to the file name.
614 let ics = format!(
615 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:{long}\r\nBEGIN:VEVENT\r\nUID:n1\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T100000Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
616 );
617 let r = io
618 .alice
619 .raw(
620 Method::POST,
621 "/api/pim/import?kind=calendar&file=Trips.ics",
622 &[("content-type", "text/calendar")],
623 ics.into_bytes(),
624 )
625 .await;
626 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
627 assert_eq!(r.json()["collection"]["name"], "Trips");
628}
629
630#[tokio::test]
631async fn a_feed_password_matches_with_edge_spaces() {
632 let io = Io::new().await;
633 let cal = io.id(CAL).await;
634 let locked = io.link(cal, json!({ "password": " feedpass123 " })).await;
635 for pw in [" feedpass123 ", "feedpass123"] {
636 let r = io.anon(&locked, &[("authorization", &basic("", pw))]).await;
637 assert_eq!(r.status, StatusCode::OK, "{pw:?}");
638 }
639}
640
641#[tokio::test]
642async fn feeds_of_a_disabled_owner_stop() {
643 let io = Io::new().await;
644 let admin = login(&io.env, "admin", "admin1234").await;
645 let feed = io.link(io.id(CAL).await, json!({})).await;
646 let alice = user_id(&admin, "alice").await;
647 for (active, status) in [(false, StatusCode::NOT_FOUND), (true, StatusCode::OK)] {
648 let r = admin
649 .put_json(
650 &format!("/api/admin/users/{alice}"),
651 &json!({ "active": active }),
652 )
653 .await;
654 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
655 assert_eq!(io.anon(&feed, &[]).await.status, status);
656 }
657}
658
659#[tokio::test]
660async fn a_loan_to_a_disabled_user_takes_a_new_mode() {
661 let io = Io::new().await;
662 let admin = login(&io.env, "admin", "admin1234").await;
663 create_user(&admin, "carol", PW, &[]).await;
664 let id = io.id(CAL).await;
665 let shares = format!("/api/pim/collections/{id}/shares");
666 let r = io
667 .alice
668 .post_json(&shares, &json!({"user": "bob", "mode": "ro"}))
669 .await;
670 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
671 for name in ["bob", "carol"] {
672 let uid = user_id(&admin, name).await;
673 let r = admin
674 .put_json(
675 &format!("/api/admin/users/{uid}"),
676 &json!({"active": false}),
677 )
678 .await;
679 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
680 }
681
682 let r = io
683 .alice
684 .post_json(&shares, &json!({"user": "bob", "mode": "rw"}))
685 .await;
686 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
687 assert_eq!(r.json()["user_name"], "bob");
688 let list = io.alice.get(&shares).await.json();
689 assert_eq!(list[0]["mode"], "rw", "{list}");
690
691 // No new loan goes to a disabled account.
692 let r = io
693 .alice
694 .post_json(&shares, &json!({"user": "carol", "mode": "ro"}))
695 .await;
696 assert_eq!(r.status, StatusCode::NOT_FOUND);
697}
698
699#[tokio::test]
700async fn an_import_racing_the_collection_delete_never_fails_with_500() {
701 let io = Io::new().await;
702 let url = "/pim/calendars/alice/race/";
703 for i in 0..20 {
704 let r = io.dav("alice", "MKCALENDAR", url, "").await;
705 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
706 let path = format!("/api/pim/collections/{}/import", io.id(url).await);
707 let (import, delete) = tokio::join!(
708 io.alice.raw(
709 Method::POST,
710 &path,
711 &[("content-type", "text/calendar")],
712 event(&format!("race{i}"), "x", "").into_bytes(),
713 ),
714 io.dav("alice", "DELETE", url, ""),
715 );
716 assert_eq!(delete.status, StatusCode::NO_CONTENT);
717 assert!(
718 [StatusCode::OK, StatusCode::NOT_FOUND].contains(&import.status),
719 "{}: {}",
720 import.status,
721 import.text()
722 );
723 }
724}
725
726#[tokio::test]
727async fn the_web_api_keeps_the_dav_limits() {
728 let io = Io::new().await;
729 let cal = io.id(CAL).await;
730 // An object over the 10 MiB a PUT takes is skipped.
731 let big = event(
732 "big",
733 "Big",
734 &format!("DESCRIPTION:{}\r\n", "x".repeat(11 << 20)),
735 );
736 let r = io.import(cal, &(big + &event("small", "Small", ""))).await;
737 assert_eq!(r["created"], 1, "{r}");
738 assert_eq!(r["skipped"][0]["uid"], "big", "{r}");
739
740 // One large time zone copied into every event is refused up front.
741 let zone = format!(
742 "BEGIN:VTIMEZONE\r\nTZID:Big\r\n{}BEGIN:STANDARD\r\nDTSTART:19700101T000000\r\n\
743 TZOFFSETFROM:+0000\r\nTZOFFSETTO:+0000\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n",
744 format!("X-PAD:{}\r\n", "x".repeat(70)).repeat(15_000)
745 );
746 let events: String = (0..200)
747 .map(|i| {
748 format!(
749 "BEGIN:VEVENT\r\nUID:z{i}\r\nDTSTAMP:20260101T000000Z\r\n\
750 DTSTART;TZID=Big:20260101T100000\r\nEND:VEVENT\r\n"
751 )
752 })
753 .collect();
754 let file = format!(
755 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\n{zone}{events}END:VCALENDAR\r\n"
756 );
757 let r = io
758 .alice
759 .raw(
760 Method::POST,
761 &format!("/api/pim/collections/{cal}/import"),
762 &[("content-type", "text/calendar")],
763 file.into_bytes(),
764 )
765 .await;
766 assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", r.text());
767
768 // A zone no event names is not copied, and alarms are no objects.
769 let events: String = (0..150)
770 .map(|i| {
771 format!(
772 "BEGIN:VEVENT\r\nUID:a{i}\r\nDTSTAMP:20260101T000000Z\r\n\
773 DTSTART:20260101T100000Z\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\n\
774 TRIGGER:-PT5M\r\nEND:VALARM\r\nEND:VEVENT\r\n"
775 )
776 })
777 .collect();
778 let file = format!(
779 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\n{zone}{events}END:VCALENDAR\r\n"
780 );
781 let r = io.import(cal, &file).await;
782 assert_eq!(r["created"], 150, "{r}");
783
784 // A suffixed slug never takes the lent form "shared-<id>".
785 for _ in 0..2 {
786 let r = io
787 .alice
788 .post_json(
789 "/api/pim/collections",
790 &json!({"kind": "calendar", "name": "Shared"}),
791 )
792 .await;
793 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
794 assert!(!r.text().contains("/shared-"), "{}", r.text());
795 }
796
797 // No more collections than MKCOL allows.
798 let create = async |name: String| {
799 io.alice
800 .post_json(
801 "/api/pim/collections",
802 &json!({"kind": "addressbook", "name": name}),
803 )
804 .await
805 .status
806 };
807 let mut made = 0;
808 while create(format!("Book {made}")).await == StatusCode::OK {
809 made += 1;
810 assert!(made <= 100);
811 }
812 assert_eq!(create("One more".into()).await, StatusCode::FORBIDDEN);
813}
814