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 import_schedules_like_a_put_and_keeps_uniqueness() {
286 let io = Io::new().await;
287 let cal = io.id(CAL).await;
288 let meeting = event(
289 "meet",
290 "Meeting",
291 "ORGANIZER:mailto:alice@dovenest.invalid\r\nATTENDEE:mailto:bob@dovenest.invalid\r\n",
292 );
293 let r = io.import(cal, &meeting).await;
294 assert_eq!(r["created"], 1, "{r}");
295 // Stored as a scheduling object, with a Schedule-Tag like after a PUT.
296 let listing = io.dav("alice", "PROPFIND", CAL, "").await.text();
297 let href = listing
298 .split("<d:href>")
299 .filter_map(|s| s.split("</d:href>").next())
300 .find(|h| h.ends_with(".ics"))
301 .unwrap_or_else(|| panic!("{listing}"))
302 .to_string();
303 let r = io.dav("alice", "GET", &href, "").await;
304 assert!(r.header("schedule-tag").is_some());
305 // bob got a copy and the REQUEST, as after a PUT.
306 for path in ["/pim/calendars/bob/default/", "/pim/calendars/bob/inbox/"] {
307 let r = io.dav("bob", "PROPFIND", path, "").await;
308 assert!(r.text().contains(".ics</"), "{path}: {}", r.text());
309 }
310 // One scheduling object per UID and owner (RFC 6638, 3.2.4.1).
311 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
312 .await;
313 let work = io.id("/pim/calendars/alice/work/").await;
314 let r = io.import(work, &meeting).await;
315 assert_eq!(r["created"], 0);
316 assert_eq!(r["skipped"][0]["uid"], "meet");
317 assert_eq!(
318 r["skipped"][0]["reason"],
319 "unique-scheduling-object-resource"
320 );
321
322 // Imported again without bob, the meeting is cancelled for him.
323 let r = io.import(cal, &event("meet", "Meeting", "")).await;
324 assert_eq!(r["updated"], 1, "{r}");
325 let copy = io
326 .dav("bob", "PROPFIND", "/pim/calendars/bob/default/", "")
327 .await
328 .text();
329 let copy = copy
330 .split("<d:href>")
331 .filter_map(|s| s.split("</d:href>").next())
332 .find(|h| h.ends_with(".ics"))
333 .unwrap_or_else(|| panic!("{copy}"))
334 .to_string();
335 let r = io.dav("bob", "GET", &copy, "").await;
336 assert!(r.text().contains("STATUS:CANCELLED"), "{}", r.text());
337
338 // A read-only loan cannot be imported into.
339 let bob = login(&io.env, "bob", PW).await;
340 io.alice
341 .post_json(
342 &format!("/api/pim/collections/{cal}/shares"),
343 &json!({ "user": "bob", "mode": "ro" }),
344 )
345 .await;
346 let r = bob
347 .raw(
348 Method::POST,
349 &format!("/api/pim/collections/{cal}/import"),
350 &[("content-type", "text/calendar")],
351 event("x", "x", "").into_bytes(),
352 )
353 .await;
354 assert_eq!(r.status, StatusCode::FORBIDDEN);
355 // But exported.
356 let r = bob.get(&format!("/api/pim/collections/{cal}/export")).await;
357 assert_eq!(r.status, StatusCode::OK);
358}
359
360#[tokio::test]
361async fn export_round_trip() {
362 let io = Io::new().await;
363 let cal = io.id(CAL).await;
364 io.import(cal, &event("r1", "One", "")).await;
365 io.import(cal, &event("r2", "Two", "")).await;
366
367 let url = format!("/api/pim/collections/{cal}/export");
368 let r = io.alice.get(&url).await;
369 assert_eq!(r.status, StatusCode::OK);
370 let disposition = r.header("content-disposition").unwrap();
371 assert!(disposition.starts_with("attachment;") && disposition.contains(".ics"));
372 let exported = r.text();
373 // Download only: there is no saving into a folder.
374 let r = io.alice.post_json(&url, &json!({})).await;
375 assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
376
377 // The export imports back as the same objects.
378 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/copy/", "")
379 .await;
380 let copy = io.id("/pim/calendars/alice/copy/").await;
381 let r = io.import(copy, &exported).await;
382 assert_eq!(r["created"], 2, "{r}");
383
384 // vCards, one without UID.
385 let book = io.id("/pim/addressbooks/alice/default/").await;
386 let cards = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:One\r\nEND:VCARD\r\n\
387 BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Two\r\nEND:VCARD\r\n";
388 let r = io.import(book, cards).await;
389 assert_eq!(r["created"], 2, "{r}");
390 let r = io.import(book, cards).await;
391 assert_eq!(r["updated"], 2, "{r}");
392
393 // The system address book has no collection id of its own.
394 let r = io.alice.get("/api/pim/system/export").await;
395 assert_eq!(r.status, StatusCode::OK);
396 assert!(r.header("content-disposition").unwrap().contains(".vcf"));
397 assert!(r.text().contains("FN:alice"));
398}
399
400#[tokio::test]
401async fn import_as_a_new_collection() {
402 let io = Io::new().await;
403 let post = |query: &str, body: String| {
404 let (client, query) = (&io.alice, query.to_string());
405 async move {
406 let r = client
407 .raw(
408 Method::POST,
409 &format!("/api/pim/import?{query}"),
410 &[("content-type", "text/calendar")],
411 body.into_bytes(),
412 )
413 .await;
414 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
415 r.json()
416 }
417 };
418 let before = collections(&io.alice).await;
419 let vevent = |uid: &str, summary: &str| {
420 format!(
421 "BEGIN:VEVENT\r\nUID:{uid}\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T100000Z\r\nSUMMARY:{summary}\r\nEND:VEVENT\r\n"
422 )
423 };
424
425 // The file names itself and its color.
426 let ics = format!(
427 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:Ferien\r\nX-APPLE-CALENDAR-COLOR:#FF2968FF\r\n{}END:VCALENDAR\r\n",
428 vevent("f1", "Sommer")
429 );
430 let r = post("kind=calendar&file=holidays.ics&color=%2322c55e", ics).await;
431 assert_eq!(r["created"], 1, "{r}");
432 assert_eq!(r["collection"]["name"], "Ferien", "{r}");
433 assert_eq!(r["collection"]["color"], "#FF2968FF", "{r}");
434
435 // A typed name wins; without a color in the file the requested one counts.
436 let plain = format!(
437 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nCOLOR:teal\r\n{}END:VCALENDAR\r\n",
438 vevent("f2", "Winter")
439 );
440 let r = post("kind=calendar&name=Mine&file=x.ics&color=%2322c55e", plain).await;
441 assert_eq!(r["collection"]["name"], "Mine", "{r}");
442 assert_eq!(r["collection"]["color"], "#22c55e", "{r}");
443
444 // An address book takes the file name.
445 let vcf = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:Ann\r\nN:;Ann;;;\r\nEND:VCARD\r\n";
446 let r = post("kind=addressbook&file=Team%20contacts.vcf", vcf.to_string()).await;
447 assert_eq!(r["collection"]["name"], "Team contacts", "{r}");
448 assert_eq!(r["collection"]["kind"], "addressbook", "{r}");
449 assert_eq!(collections(&io.alice).await, before + 3);
450
451 // Nothing importable: reported, and no empty collection is left behind.
452 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";
453 let r = post("kind=calendar&file=bad.ics", broken.to_string()).await;
454 assert_eq!(r["collection"], Value::Null, "{r}");
455 assert_eq!(r["skipped_total"], 1, "{r}");
456 assert_eq!(collections(&io.alice).await, before + 3);
457}
458
459async fn collections(c: &Client) -> usize {
460 c.get("/api/pim/collections")
461 .await
462 .json()
463 .as_array()
464 .unwrap()
465 .len()
466}
467
468#[tokio::test]
469async fn share_candidates_leave_out_owner_borrowers_and_disabled() {
470 let io = Io::new().await;
471 let admin = login(&io.env, "admin", "admin1234").await;
472 create_user(&admin, "carol", PW, &[]).await;
473 create_user(&admin, "dave", PW, &[]).await;
474 let dave = user_id(&admin, "dave").await;
475 let r = admin
476 .put_json(
477 &format!("/api/admin/users/{dave}"),
478 &json!({"active": false}),
479 )
480 .await;
481 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
482 let r = admin
483 .post_json(
484 "/api/admin/rooms",
485 &json!({"name": "atrium", "kind": "room"}),
486 )
487 .await;
488 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
489
490 let id = io.id(CAL).await;
491 let r = io
492 .alice
493 .post_json(
494 &format!("/api/pim/collections/{id}/shares"),
495 &json!({"user": "bob", "mode": "ro"}),
496 )
497 .await;
498 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
499
500 let names = |v: Value| -> Vec<String> {
501 v.as_array()
502 .unwrap()
503 .iter()
504 .map(|c| c["name"].as_str().unwrap().to_string())
505 .collect()
506 };
507 let r = io
508 .alice
509 .get(&format!("/api/pim/collections/{id}/shares/candidates"))
510 .await;
511 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
512 // Not alice herself, not bob (a borrower), not dave (disabled), no room.
513 assert_eq!(names(r.json()), ["admin", "carol"]);
514
515 // Only the owner may ask.
516 let bob = login(&io.env, "bob", PW).await;
517 let r = bob
518 .get(&format!("/api/pim/collections/{id}/shares/candidates"))
519 .await;
520 assert_eq!(r.status, StatusCode::NOT_FOUND);
521}
522
523#[tokio::test]
524async fn a_skipped_import_into_a_new_user_leaves_only_the_default_calendar() {
525 use server::db::PimKind;
526 let io = Io::new().await;
527 let client = login(&io.env, "bob", PW).await;
528 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";
529 let r = client
530 .raw(
531 Method::POST,
532 "/api/pim/import?kind=calendar&file=bad.ics",
533 &[("content-type", "text/calendar")],
534 broken.as_bytes().to_vec(),
535 )
536 .await;
537 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
538 assert_eq!(r.json()["collection"], Value::Null);
539 assert_eq!(r.json()["skipped_total"], 1);
540
541 let db = &io.env.state.db;
542 let bob = db.find_user_by_name("bob").await.unwrap().unwrap();
543 let pid = db.principal_of(bob.id).await.unwrap();
544 let slugs: Vec<_> = db
545 .pim_collections(pid, PimKind::Calendar)
546 .await
547 .unwrap()
548 .into_iter()
549 .map(|c| c.slug)
550 .filter(|s| s != "inbox" && s != "outbox")
551 .collect();
552 assert_eq!(slugs, ["default"]);
553}
554
555#[tokio::test]
556async fn collection_names_and_descriptions_are_checked() {
557 let io = Io::new().await;
558 let create = |body: Value| {
559 let client = &io.alice;
560 async move { client.post_json("/api/pim/collections", &body).await }
561 };
562 let long = "x".repeat(257);
563 for name in [long.as_str(), "bell\u{7}"] {
564 let r = create(json!({"kind": "calendar", "name": name})).await;
565 assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name:?}");
566 }
567 let r =
568 create(json!({"kind": "calendar", "name": "Ok", "description": "x".repeat(1025)})).await;
569 assert_eq!(r.status, StatusCode::BAD_REQUEST);
570 let r = create(json!({"kind": "calendar", "name": "Ok", "description": "two\nlines"})).await;
571 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
572 let id = r.json()["id"].as_i64().unwrap();
573 let url = format!("/api/pim/collections/{id}");
574 for body in [
575 json!({"name": long}),
576 json!({"description": "x".repeat(1025)}),
577 ] {
578 let r = io.alice.put_json(&url, &body).await;
579 assert_eq!(r.status, StatusCode::BAD_REQUEST, "{body}");
580 }
581
582 // A file's own name that cannot be stored gives way to the file name.
583 let ics = format!(
584 "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"
585 );
586 let r = io
587 .alice
588 .raw(
589 Method::POST,
590 "/api/pim/import?kind=calendar&file=Trips.ics",
591 &[("content-type", "text/calendar")],
592 ics.into_bytes(),
593 )
594 .await;
595 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
596 assert_eq!(r.json()["collection"]["name"], "Trips");
597}
598
599#[tokio::test]
600async fn a_feed_password_matches_with_edge_spaces() {
601 let io = Io::new().await;
602 let cal = io.id(CAL).await;
603 let locked = io.link(cal, json!({ "password": " feedpass123 " })).await;
604 for pw in [" feedpass123 ", "feedpass123"] {
605 let r = io.anon(&locked, &[("authorization", &basic("", pw))]).await;
606 assert_eq!(r.status, StatusCode::OK, "{pw:?}");
607 }
608}
609
610#[tokio::test]
611async fn feeds_of_a_disabled_owner_stop() {
612 let io = Io::new().await;
613 let admin = login(&io.env, "admin", "admin1234").await;
614 let feed = io.link(io.id(CAL).await, json!({})).await;
615 let alice = user_id(&admin, "alice").await;
616 for (active, status) in [(false, StatusCode::NOT_FOUND), (true, StatusCode::OK)] {
617 let r = admin
618 .put_json(
619 &format!("/api/admin/users/{alice}"),
620 &json!({ "active": active }),
621 )
622 .await;
623 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
624 assert_eq!(io.anon(&feed, &[]).await.status, status);
625 }
626}
627
628#[tokio::test]
629async fn a_loan_to_a_disabled_user_takes_a_new_mode() {
630 let io = Io::new().await;
631 let admin = login(&io.env, "admin", "admin1234").await;
632 create_user(&admin, "carol", PW, &[]).await;
633 let id = io.id(CAL).await;
634 let shares = format!("/api/pim/collections/{id}/shares");
635 let r = io
636 .alice
637 .post_json(&shares, &json!({"user": "bob", "mode": "ro"}))
638 .await;
639 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
640 for name in ["bob", "carol"] {
641 let uid = user_id(&admin, name).await;
642 let r = admin
643 .put_json(
644 &format!("/api/admin/users/{uid}"),
645 &json!({"active": false}),
646 )
647 .await;
648 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
649 }
650
651 let r = io
652 .alice
653 .post_json(&shares, &json!({"user": "bob", "mode": "rw"}))
654 .await;
655 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
656 assert_eq!(r.json()["user_name"], "bob");
657 let list = io.alice.get(&shares).await.json();
658 assert_eq!(list[0]["mode"], "rw", "{list}");
659
660 // No new loan goes to a disabled account.
661 let r = io
662 .alice
663 .post_json(&shares, &json!({"user": "carol", "mode": "ro"}))
664 .await;
665 assert_eq!(r.status, StatusCode::NOT_FOUND);
666}
667
668#[tokio::test]
669async fn an_import_racing_the_collection_delete_never_fails_with_500() {
670 let io = Io::new().await;
671 let url = "/pim/calendars/alice/race/";
672 for i in 0..20 {
673 let r = io.dav("alice", "MKCALENDAR", url, "").await;
674 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
675 let path = format!("/api/pim/collections/{}/import", io.id(url).await);
676 let (import, delete) = tokio::join!(
677 io.alice.raw(
678 Method::POST,
679 &path,
680 &[("content-type", "text/calendar")],
681 event(&format!("race{i}"), "x", "").into_bytes(),
682 ),
683 io.dav("alice", "DELETE", url, ""),
684 );
685 assert_eq!(delete.status, StatusCode::NO_CONTENT);
686 assert!(
687 [StatusCode::OK, StatusCode::NOT_FOUND].contains(&import.status),
688 "{}: {}",
689 import.status,
690 import.text()
691 );
692 }
693}
694
695#[tokio::test]
696async fn the_web_api_keeps_the_dav_limits() {
697 let io = Io::new().await;
698 let cal = io.id(CAL).await;
699 // An object over the 10 MiB a PUT takes is skipped.
700 let big = event(
701 "big",
702 "Big",
703 &format!("DESCRIPTION:{}\r\n", "x".repeat(11 << 20)),
704 );
705 let r = io.import(cal, &(big + &event("small", "Small", ""))).await;
706 assert_eq!(r["created"], 1, "{r}");
707 assert_eq!(r["skipped"][0]["uid"], "big", "{r}");
708
709 // One large time zone copied into every event is refused up front.
710 let zone = format!(
711 "BEGIN:VTIMEZONE\r\nTZID:Big\r\n{}BEGIN:STANDARD\r\nDTSTART:19700101T000000\r\n\
712 TZOFFSETFROM:+0000\r\nTZOFFSETTO:+0000\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n",
713 format!("X-PAD:{}\r\n", "x".repeat(70)).repeat(15_000)
714 );
715 let events: String = (0..200)
716 .map(|i| {
717 format!(
718 "BEGIN:VEVENT\r\nUID:z{i}\r\nDTSTAMP:20260101T000000Z\r\n\
719 DTSTART;TZID=Big:20260101T100000\r\nEND:VEVENT\r\n"
720 )
721 })
722 .collect();
723 let file = format!(
724 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\n{zone}{events}END:VCALENDAR\r\n"
725 );
726 let r = io
727 .alice
728 .raw(
729 Method::POST,
730 &format!("/api/pim/collections/{cal}/import"),
731 &[("content-type", "text/calendar")],
732 file.into_bytes(),
733 )
734 .await;
735 assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", r.text());
736
737 // A zone no event names is not copied, and alarms are no objects.
738 let events: String = (0..150)
739 .map(|i| {
740 format!(
741 "BEGIN:VEVENT\r\nUID:a{i}\r\nDTSTAMP:20260101T000000Z\r\n\
742 DTSTART:20260101T100000Z\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\n\
743 TRIGGER:-PT5M\r\nEND:VALARM\r\nEND:VEVENT\r\n"
744 )
745 })
746 .collect();
747 let file = format!(
748 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\n{zone}{events}END:VCALENDAR\r\n"
749 );
750 let r = io.import(cal, &file).await;
751 assert_eq!(r["created"], 150, "{r}");
752
753 // A suffixed slug never takes the lent form "shared-<id>".
754 for _ in 0..2 {
755 let r = io
756 .alice
757 .post_json(
758 "/api/pim/collections",
759 &json!({"kind": "calendar", "name": "Shared"}),
760 )
761 .await;
762 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
763 assert!(!r.text().contains("/shared-"), "{}", r.text());
764 }
765
766 // No more collections than MKCOL allows.
767 let create = async |name: String| {
768 io.alice
769 .post_json(
770 "/api/pim/collections",
771 &json!({"kind": "addressbook", "name": name}),
772 )
773 .await
774 .status
775 };
776 let mut made = 0;
777 while create(format!("Book {made}")).await == StatusCode::OK {
778 made += 1;
779 assert!(made <= 100);
780 }
781 assert_eq!(create("One more".into()).await, StatusCode::FORBIDDEN);
782}
783