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