api_pim.rs
⎇
Raw
1//! CalDAV and CardDAV: discovery, collections, properties and objects.
2
3mod common;
4
5use axum::http::{Method, StatusCode};
6use common::*;
7use pimdav::xml::{self, APPLE, CALDAV, CALSERVER, CARDDAV, DAV, Name};
8use serde_json::json;
9use xmltree::Element;
10
11const ALICE: &str = "alice";
12const PW: &str = "alice12345";
13
14async fn setup() -> (Env, String) {
15 let env = Env::new().await;
16 let admin = env.admin().await;
17 create_user(&admin, ALICE, PW, &[]).await;
18 (env, basic(ALICE, PW))
19}
20
21async fn req(
22 env: &Env,
23 verb: &str,
24 path: &str,
25 auth: &str,
26 extra: &[(&str, &str)],
27 body: &str,
28) -> Resp {
29 let mut headers = vec![("authorization", auth)];
30 headers.extend_from_slice(extra);
31 Client::new(env.app.clone())
32 .raw(
33 Method::from_bytes(verb.as_bytes()).unwrap(),
34 path,
35 &headers,
36 body.as_bytes().to_vec(),
37 )
38 .await
39}
40
41fn propfind_body(props: &[(&str, &str)]) -> String {
42 let props: String = props
43 .iter()
44 .map(|(ns, l)| format!("<{l} xmlns=\"{ns}\"/>"))
45 .collect();
46 format!("<d:propfind xmlns:d=\"DAV:\"><d:prop>{props}</d:prop></d:propfind>")
47}
48
49/// `href -> [(status, property element)]` of a multistatus.
50fn parse_multistatus(r: &Resp) -> Vec<(String, Vec<(u16, Element)>)> {
51 assert_eq!(r.status, StatusCode::MULTI_STATUS, "{}", r.text());
52 let root = Element::parse(r.body.as_slice()).unwrap();
53 xml::elements(&root)
54 .map(|resp| {
55 let href = xml::text(xml::child(resp, DAV, "href").unwrap());
56 let props = xml::elements(resp)
57 .filter(|e| Name::of(e).is(DAV, "propstat"))
58 .flat_map(|ps| {
59 let code: u16 = xml::text(xml::child(ps, DAV, "status").unwrap())
60 .split(' ')
61 .nth(1)
62 .unwrap()
63 .parse()
64 .unwrap();
65 let prop = xml::child(ps, DAV, "prop").unwrap();
66 xml::elements(prop)
67 .map(move |p| (code, p.clone()))
68 .collect::<Vec<_>>()
69 })
70 .collect();
71 (href, props)
72 })
73 .collect()
74}
75
76/// The property of `href` with status 200.
77fn prop(
78 ms: &[(String, Vec<(u16, Element)>)],
79 href: &str,
80 ns: &str,
81 local: &str,
82) -> Option<Element> {
83 ms.iter()
84 .find(|(h, _)| h == href)
85 .unwrap_or_else(|| panic!("no response for {href}"))
86 .1
87 .iter()
88 .find(|(code, p)| *code == 200 && Name::of(p).is(ns, local))
89 .map(|(_, p)| p.clone())
90}
91
92fn prop_text(
93 ms: &[(String, Vec<(u16, Element)>)],
94 href: &str,
95 ns: &str,
96 local: &str,
97) -> Option<String> {
98 prop(ms, href, ns, local).map(|p| xml::text(&p))
99}
100
101fn hrefs_of(p: &Element) -> Vec<String> {
102 xml::elements(p).map(xml::text).collect()
103}
104
105fn error_condition(r: &Resp) -> Name {
106 let root = Element::parse(r.body.as_slice()).unwrap_or_else(|_| panic!("{}", r.text()));
107 assert!(Name::of(&root).is(DAV, "error"), "{}", r.text());
108 Name::of(xml::elements(&root).next().unwrap())
109}
110
111const HOME: &str = "/pim/calendars/alice/";
112const CAL: &str = "/pim/calendars/alice/default/";
113const BOOK: &str = "/pim/addressbooks/alice/default/";
114const INBOX: &str = "/pim/calendars/alice/inbox/";
115const OUTBOX: &str = "/pim/calendars/alice/outbox/";
116
117fn event(uid: &str, summary: &str) -> String {
118 format!(
119 "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\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
120 )
121}
122
123#[tokio::test]
124async fn discovery() {
125 let (env, auth) = setup().await;
126
127 let r = req(&env, "PROPFIND", "/pim/", "", &[], "").await;
128 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
129 assert!(r.header("www-authenticate").is_some());
130
131 let r = req(&env, "PROPFIND", "/.well-known/caldav", &auth, &[], "").await;
132 assert_eq!(r.status, StatusCode::TEMPORARY_REDIRECT);
133 assert_eq!(r.header("location").as_deref(), Some("/pim/"));
134
135 // A Basic login spelled in another case still gets the stored spelling.
136 let body = propfind_body(&[(DAV, "current-user-principal")]);
137 let r = req(
138 &env,
139 "PROPFIND",
140 "/pim/",
141 &basic("ALICE", PW),
142 &[("depth", "0")],
143 &body,
144 )
145 .await;
146 let ms = parse_multistatus(&r);
147 let p = prop(&ms, "/pim/", DAV, "current-user-principal").unwrap();
148 assert_eq!(hrefs_of(&p), ["/pim/principals/alice/"]);
149
150 let body = propfind_body(&[
151 (CALDAV, "calendar-home-set"),
152 (CARDDAV, "addressbook-home-set"),
153 (CALDAV, "calendar-user-address-set"),
154 (DAV, "displayname"),
155 (DAV, "no-such-prop"),
156 ]);
157 let r = req(
158 &env,
159 "PROPFIND",
160 "/pim/principals/alice/",
161 &auth,
162 &[("depth", "0")],
163 &body,
164 )
165 .await;
166 let ms = parse_multistatus(&r);
167 let p = "/pim/principals/alice/";
168 assert_eq!(
169 hrefs_of(&prop(&ms, p, CALDAV, "calendar-home-set").unwrap()),
170 [HOME]
171 );
172 assert_eq!(
173 hrefs_of(&prop(&ms, p, CARDDAV, "addressbook-home-set").unwrap()),
174 ["/pim/addressbooks/alice/"]
175 );
176 let addresses = hrefs_of(&prop(&ms, p, CALDAV, "calendar-user-address-set").unwrap());
177 assert_eq!(addresses[0], "mailto:alice@filebrowser.invalid");
178 assert!(addresses[2].starts_with("urn:uuid:"));
179 assert_eq!(
180 prop_text(&ms, p, DAV, "displayname").as_deref(),
181 Some(ALICE)
182 );
183 assert!(
184 ms[0]
185 .1
186 .iter()
187 .any(|(c, e)| *c == 404 && Name::of(e).is(DAV, "no-such-prop"))
188 );
189
190 // An app password works as well.
191 let admin = login(&env, ALICE, PW).await;
192 let r = admin
193 .post_json("/api/auth/app-passwords", &json!({ "name": "phone" }))
194 .await;
195 let secret = r.json()["secret"].as_str().unwrap().to_string();
196 let r = req(
197 &env,
198 "PROPFIND",
199 "/pim/",
200 &basic("x", &secret),
201 &[("depth", "0")],
202 "",
203 )
204 .await;
205 assert_eq!(r.status, StatusCode::MULTI_STATUS);
206
207 let r = req(&env, "OPTIONS", "/pim/", &auth, &[], "").await;
208 assert!(r.header("dav").unwrap().contains("calendar-access"));
209}
210
211#[tokio::test]
212async fn homes_list_the_default_collections() {
213 let (env, auth) = setup().await;
214 let r = req(&env, "PROPFIND", HOME, &auth, &[("depth", "1")], "").await;
215 let ms = parse_multistatus(&r);
216 // The home, the calendar, and the scheduling inbox and outbox.
217 assert_eq!(ms.len(), 4, "{}", r.text());
218 for (href, kind) in [(INBOX, "schedule-inbox"), (OUTBOX, "schedule-outbox")] {
219 let rt = prop(&ms, href, DAV, "resourcetype").unwrap();
220 assert!(xml::child(&rt, CALDAV, kind).is_some(), "{href}");
221 }
222 assert_eq!(
223 prop(&ms, INBOX, CALDAV, "schedule-default-calendar-URL").map(|p| hrefs_of(&p)),
224 Some(vec![CAL.to_string()])
225 );
226 let rt = prop(&ms, CAL, DAV, "resourcetype").unwrap();
227 assert!(xml::child(&rt, CALDAV, "calendar").is_some());
228 assert_eq!(
229 prop_text(&ms, CAL, DAV, "displayname").as_deref(),
230 Some("Calendar")
231 );
232 let comps = prop(&ms, CAL, CALDAV, "supported-calendar-component-set").unwrap();
233 let comps: Vec<_> = xml::elements(&comps)
234 .map(|c| c.attributes["name"].clone())
235 .collect();
236 assert_eq!(comps, ["VEVENT", "VTODO", "VJOURNAL"]);
237 assert!(prop_text(&ms, CAL, CALSERVER, "getctag").is_some());
238 assert!(
239 prop_text(&ms, CAL, DAV, "sync-token")
240 .unwrap()
241 .starts_with("urn:")
242 );
243
244 let r = req(
245 &env,
246 "PROPFIND",
247 "/pim/addressbooks/alice/",
248 &auth,
249 &[("depth", "1")],
250 "",
251 )
252 .await;
253 let ms = parse_multistatus(&r);
254 let rt = prop(&ms, BOOK, DAV, "resourcetype").unwrap();
255 assert!(xml::child(&rt, CARDDAV, "addressbook").is_some());
256
257 let r = req(&env, "PROPFIND", HOME, &auth, &[("depth", "infinity")], "").await;
258 assert_eq!(r.status, StatusCode::FORBIDDEN);
259 assert!(error_condition(&r).is(DAV, "propfind-finite-depth"));
260}
261
262#[tokio::test]
263async fn other_users_are_off_limits() {
264 let (env, auth) = setup().await;
265 for path in ["/pim/calendars/admin/", "/pim/calendars/admin/default/"] {
266 let r = req(&env, "PROPFIND", path, &auth, &[("depth", "0")], "").await;
267 assert_eq!(r.status, StatusCode::FORBIDDEN, "{path}");
268 }
269 // Another account's principal is readable, for scheduling.
270 let body = propfind_body(&[
271 (DAV, "displayname"),
272 (CALDAV, "calendar-user-address-set"),
273 (CARDDAV, "addressbook-home-set"),
274 ]);
275 let p = "/pim/principals/admin/";
276 let r = req(&env, "PROPFIND", p, &auth, &[("depth", "0")], &body).await;
277 let ms = parse_multistatus(&r);
278 assert_eq!(
279 prop_text(&ms, p, DAV, "displayname").as_deref(),
280 Some("admin")
281 );
282 let addresses = hrefs_of(&prop(&ms, p, CALDAV, "calendar-user-address-set").unwrap());
283 assert!(addresses.contains(&"mailto:admin@filebrowser.invalid".to_string()));
284 assert!(prop(&ms, p, CARDDAV, "addressbook-home-set").is_none());
285
286 let r = req(&env, "PROPFIND", "/pim/principals/nobody/", &auth, &[], "").await;
287 assert_eq!(r.status, StatusCode::NOT_FOUND);
288}
289
290#[tokio::test]
291async fn make_and_patch_collections() {
292 let (env, auth) = setup().await;
293 let work = "/pim/calendars/alice/work/";
294 let body = r##"<c:mkcalendar xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:i="http://apple.com/ns/ical/">
295 <d:set><d:prop>
296 <d:displayname>Work</d:displayname>
297 <i:calendar-color>#00ff00</i:calendar-color>
298 <c:supported-calendar-component-set><c:comp name="VTODO"/></c:supported-calendar-component-set>
299 </d:prop></d:set></c:mkcalendar>"##;
300 let r = req(&env, "MKCALENDAR", work, &auth, &[], body).await;
301 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
302 let r = req(&env, "MKCALENDAR", work, &auth, &[], "").await;
303 assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
304
305 let r = req(&env, "PROPFIND", work, &auth, &[("depth", "0")], "").await;
306 let ms = parse_multistatus(&r);
307 assert_eq!(
308 prop_text(&ms, work, DAV, "displayname").as_deref(),
309 Some("Work")
310 );
311 assert_eq!(
312 prop_text(&ms, work, APPLE, "calendar-color").as_deref(),
313 Some("#00ff00")
314 );
315 let ctag = prop_text(&ms, work, CALSERVER, "getctag").unwrap();
316
317 // One bad property fails the whole request, and nothing is created.
318 let bad = body.replace("VTODO", "VCARD");
319 let r = req(
320 &env,
321 "MKCALENDAR",
322 "/pim/calendars/alice/bad/",
323 &auth,
324 &[],
325 &bad,
326 )
327 .await;
328 assert_eq!(r.status, StatusCode::FORBIDDEN);
329 assert!(r.text().contains("mkcalendar-response"), "{}", r.text());
330 let r = req(
331 &env,
332 "PROPFIND",
333 "/pim/calendars/alice/bad/",
334 &auth,
335 &[("depth", "0")],
336 "",
337 )
338 .await;
339 assert_eq!(r.status, StatusCode::NOT_FOUND);
340
341 // A plain MKCOL cannot make a calendar, an extended one makes an address book.
342 let r = req(&env, "MKCOL", "/pim/calendars/alice/plain/", &auth, &[], "").await;
343 assert_eq!(r.status, StatusCode::FORBIDDEN);
344 let mkcol = r#"<d:mkcol xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><d:set><d:prop>
345 <d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>
346 <d:displayname>Friends</d:displayname></d:prop></d:set></d:mkcol>"#;
347 let r = req(
348 &env,
349 "MKCOL",
350 "/pim/addressbooks/alice/friends/",
351 &auth,
352 &[],
353 mkcol,
354 )
355 .await;
356 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
357
358 let patch = r#"<d:propertyupdate xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
359 <d:set><d:prop><d:displayname>Job</d:displayname><c:calendar-description>Tasks</c:calendar-description></d:prop></d:set>
360 </d:propertyupdate>"#;
361 let r = req(&env, "PROPPATCH", work, &auth, &[], patch).await;
362 let ms = parse_multistatus(&r);
363 assert!(ms[0].1.iter().all(|(c, _)| *c == 200));
364 let r = req(&env, "PROPFIND", work, &auth, &[("depth", "0")], "").await;
365 let ms = parse_multistatus(&r);
366 assert_eq!(
367 prop_text(&ms, work, DAV, "displayname").as_deref(),
368 Some("Job")
369 );
370 assert_eq!(
371 prop_text(&ms, work, CALDAV, "calendar-description").as_deref(),
372 Some("Tasks")
373 );
374 assert_ne!(prop_text(&ms, work, CALSERVER, "getctag").unwrap(), ctag);
375
376 let patch = r#"<d:propertyupdate xmlns:d="DAV:"><d:set><d:prop>
377 <d:displayname>Never</d:displayname><d:getetag>x</d:getetag></d:prop></d:set></d:propertyupdate>"#;
378 let r = req(&env, "PROPPATCH", work, &auth, &[], patch).await;
379 let ms = parse_multistatus(&r);
380 let codes: Vec<u16> = ms[0].1.iter().map(|(c, _)| *c).collect();
381 assert_eq!(codes, [424, 403]);
382 let r = req(&env, "PROPFIND", work, &auth, &[("depth", "0")], "").await;
383 let ms = parse_multistatus(&r);
384 assert_eq!(
385 prop_text(&ms, work, DAV, "displayname").as_deref(),
386 Some("Job")
387 );
388
389 let r = req(&env, "DELETE", work, &auth, &[], "").await;
390 assert_eq!(r.status, StatusCode::NO_CONTENT);
391 let r = req(&env, "PROPFIND", work, &auth, &[("depth", "0")], "").await;
392 assert_eq!(r.status, StatusCode::NOT_FOUND);
393}
394
395#[tokio::test]
396async fn calendar_objects() {
397 let (env, auth) = setup().await;
398 let obj = format!("{CAL}a.ics");
399
400 let r = req(
401 &env,
402 "PUT",
403 &obj,
404 &auth,
405 &[("if-none-match", "*")],
406 &event("a", "One"),
407 )
408 .await;
409 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
410 let etag = r.header("etag").unwrap();
411
412 let r = req(&env, "GET", &obj, &auth, &[], "").await;
413 assert_eq!(r.status, StatusCode::OK);
414 assert_eq!(r.text(), event("a", "One"));
415 assert_eq!(r.header("etag"), Some(etag.clone()));
416 assert!(
417 r.header("content-type")
418 .unwrap()
419 .starts_with("text/calendar")
420 );
421 let r = req(&env, "HEAD", &obj, &auth, &[], "").await;
422 assert_eq!(r.status, StatusCode::OK);
423 assert!(r.body.is_empty());
424
425 let r = req(
426 &env,
427 "PUT",
428 &obj,
429 &auth,
430 &[("if-none-match", "*")],
431 &event("a", "Two"),
432 )
433 .await;
434 assert_eq!(r.status, StatusCode::PRECONDITION_FAILED);
435 let r = req(
436 &env,
437 "PUT",
438 &obj,
439 &auth,
440 &[("if-match", "\"stale\"")],
441 &event("a", "Two"),
442 )
443 .await;
444 assert_eq!(r.status, StatusCode::PRECONDITION_FAILED);
445
446 let before = parse_multistatus(&req(&env, "PROPFIND", CAL, &auth, &[("depth", "0")], "").await);
447 let r = req(
448 &env,
449 "PUT",
450 &obj,
451 &auth,
452 &[("if-match", &etag)],
453 &event("a", "Two"),
454 )
455 .await;
456 assert_eq!(r.status, StatusCode::NO_CONTENT);
457 let new_etag = r.header("etag").unwrap();
458 assert_ne!(new_etag, etag);
459 let after = parse_multistatus(&req(&env, "PROPFIND", CAL, &auth, &[("depth", "1")], "").await);
460 assert_ne!(
461 prop_text(&before, CAL, DAV, "sync-token"),
462 prop_text(&after, CAL, DAV, "sync-token")
463 );
464 assert_eq!(prop_text(&after, &obj, DAV, "getetag"), Some(new_etag));
465
466 // The UID is already stored under another name.
467 let r = req(
468 &env,
469 "PUT",
470 &format!("{CAL}b.ics"),
471 &auth,
472 &[],
473 &event("a", "Dup"),
474 )
475 .await;
476 assert_eq!(r.status, StatusCode::FORBIDDEN);
477 assert!(error_condition(&r).is(CALDAV, "no-uid-conflict"));
478 assert!(r.text().contains(&obj), "{}", r.text());
479
480 let freebusy = event("j", "x").replace("VEVENT", "VFREEBUSY");
481 let cases = [
482 ("not a calendar".to_string(), "valid-calendar-data"),
483 (
484 event("m", "x").replace("VERSION:2.0", "VERSION:2.0\r\nMETHOD:PUBLISH"),
485 "valid-calendar-object-resource",
486 ),
487 (freebusy, "supported-calendar-component"),
488 ];
489 for (body, cond) in cases {
490 let r = req(&env, "PUT", &format!("{CAL}x.ics"), &auth, &[], &body).await;
491 assert_eq!(r.status, StatusCode::FORBIDDEN, "{cond}");
492 assert!(error_condition(&r).is(CALDAV, cond), "{cond}: {}", r.text());
493 }
494
495 let r = req(
496 &env,
497 "PUT",
498 "/pim/calendars/alice/nope/x.ics",
499 &auth,
500 &[],
501 &event("x", "x"),
502 )
503 .await;
504 assert_eq!(r.status, StatusCode::CONFLICT);
505
506 let r = req(
507 &env,
508 "DELETE",
509 &obj,
510 &auth,
511 &[("if-match", "\"stale\"")],
512 "",
513 )
514 .await;
515 assert_eq!(r.status, StatusCode::PRECONDITION_FAILED);
516 let r = req(&env, "DELETE", &obj, &auth, &[], "").await;
517 assert_eq!(r.status, StatusCode::NO_CONTENT);
518 let r = req(&env, "DELETE", &obj, &auth, &[], "").await;
519 assert_eq!(r.status, StatusCode::NOT_FOUND);
520
521 let r = req(&env, "REPORT", CAL, &auth, &[], "").await;
522 assert_eq!(r.status, StatusCode::BAD_REQUEST);
523}
524
525#[tokio::test]
526async fn address_objects() {
527 let (env, auth) = setup().await;
528 let card = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:Bob\r\nN:;Bob;;;\r\nEND:VCARD\r\n";
529 let r = req(&env, "PUT", &format!("{BOOK}c1.vcf"), &auth, &[], card).await;
530 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
531 let r = req(&env, "GET", &format!("{BOOK}c1.vcf"), &auth, &[], "").await;
532 assert_eq!(r.text(), card);
533 assert!(r.header("content-type").unwrap().starts_with("text/vcard"));
534
535 let r = req(&env, "PUT", &format!("{BOOK}c2.vcf"), &auth, &[], card).await;
536 assert!(error_condition(&r).is(CARDDAV, "no-uid-conflict"));
537 let r = req(
538 &env,
539 "PUT",
540 &format!("{BOOK}c3.vcf"),
541 &auth,
542 &[],
543 &event("e", "x"),
544 )
545 .await;
546 assert!(error_condition(&r).is(CARDDAV, "valid-address-data"));
547}
548
549#[tokio::test]
550async fn the_default_calendar_stays() {
551 let (env, auth) = setup().await;
552 // Invitations arrive there (RFC 6638, 4.3).
553 let r = req(&env, "DELETE", CAL, &auth, &[], "").await;
554 assert_eq!(r.status, StatusCode::FORBIDDEN);
555 assert!(error_condition(&r).is(CALDAV, "default-calendar-needed"));
556 let other = format!("{HOME}work/");
557 assert_eq!(
558 req(&env, "MKCALENDAR", &other, &auth, &[], "").await.status,
559 StatusCode::CREATED
560 );
561 assert_eq!(
562 req(&env, "DELETE", &other, &auth, &[], "").await.status,
563 StatusCode::NO_CONTENT
564 );
565 // Nor can the inbox be made or removed by a client.
566 assert_eq!(
567 req(&env, "DELETE", INBOX, &auth, &[], "").await.status,
568 StatusCode::FORBIDDEN
569 );
570 assert_eq!(
571 req(
572 &env,
573 "MKCALENDAR",
574 "/pim/calendars/alice/outbox/",
575 &auth,
576 &[],
577 ""
578 )
579 .await
580 .status,
581 StatusCode::FORBIDDEN
582 );
583}
584
585#[tokio::test]
586async fn deleting_a_user_deletes_their_collections() {
587 let env = Env::new().await;
588 let admin = env.admin().await;
589 create_user(&admin, ALICE, PW, &[]).await;
590 let auth = basic(ALICE, PW);
591 let r = req(
592 &env,
593 "PUT",
594 &format!("{CAL}a.ics"),
595 &auth,
596 &[],
597 &event("a", "x"),
598 )
599 .await;
600 assert_eq!(r.status, StatusCode::CREATED);
601 let id = user_id(&admin, ALICE).await;
602 let r = admin.delete(&format!("/api/admin/users/{id}")).await;
603 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
604 let db = &env.state.db;
605 assert!(
606 db.pim_collections(id, server::db::PimKind::Calendar)
607 .await
608 .unwrap()
609 .is_empty()
610 );
611}
612
613// ---------------------------------------------------------------------------
614// REPORT and MOVE
615// ---------------------------------------------------------------------------
616
617/// `(href, status of the response itself)` of every response.
618fn statuses(r: &Resp) -> Vec<(String, Option<u16>)> {
619 let root = Element::parse(r.body.as_slice()).unwrap();
620 xml::elements(&root)
621 .filter(|e| Name::of(e).is(DAV, "response"))
622 .map(|resp| {
623 let href = xml::text(xml::child(resp, DAV, "href").unwrap());
624 let code = xml::child(resp, DAV, "status")
625 .map(|s| xml::text(s).split(' ').nth(1).unwrap().parse().unwrap());
626 (href, code)
627 })
628 .collect()
629}
630
631fn sync_token_of(r: &Resp) -> String {
632 let root = Element::parse(r.body.as_slice()).unwrap();
633 xml::text(xml::child(&root, DAV, "sync-token").unwrap())
634}
635
636fn ics(body: &str) -> String {
637 format!("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\n{body}END:VCALENDAR\r\n")
638}
639
640const LUNCH: &str = "BEGIN:VEVENT\r\nUID:lunch\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T120000Z\r\nDTEND:20260101T130000Z\r\nSUMMARY:Team Lunch\r\nEND:VEVENT\r\n";
641const WEEKLY: &str = "BEGIN:VEVENT\r\nUID:weekly\r\nDTSTAMP:20260101T000000Z\r\nDTSTART;TZID=Europe/Berlin:20251201T090000\r\nDTEND;TZID=Europe/Berlin:20251201T093000\r\nRRULE:FREQ=WEEKLY\r\nSUMMARY:Standup\r\nEND:VEVENT\r\n";
642const TODO: &str = "BEGIN:VTODO\r\nUID:todo\r\nDTSTAMP:20260101T000000Z\r\nDUE:20260110T170000Z\r\nSUMMARY:Taxes\r\nEND:VTODO\r\n";
643
644async fn put(env: &Env, auth: &str, path: &str, body: &str) {
645 let r = req(env, "PUT", path, auth, &[], body).await;
646 assert!(r.status.is_success(), "{path}: {}", r.text());
647}
648
649fn query(filter: &str, data: &str) -> String {
650 format!(
651 r#"<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
652 <d:prop><d:getetag/>{data}</d:prop>
653 <c:filter><c:comp-filter name="VCALENDAR">{filter}</c:comp-filter></c:filter>
654 </c:calendar-query>"#
655 )
656}
657
658fn hrefs_in(r: &Resp) -> Vec<String> {
659 let mut h: Vec<_> = statuses(r).into_iter().map(|(h, _)| h).collect();
660 h.sort();
661 h
662}
663
664#[tokio::test]
665async fn calendar_reports() {
666 let (env, auth) = setup().await;
667 put(&env, &auth, &format!("{CAL}lunch.ics"), &ics(LUNCH)).await;
668 put(&env, &auth, &format!("{CAL}weekly.ics"), &ics(WEEKLY)).await;
669 put(&env, &auth, &format!("{CAL}todo.ics"), &ics(TODO)).await;
670
671 let r = req(
672 &env,
673 "PROPFIND",
674 CAL,
675 &auth,
676 &[("depth", "0")],
677 &propfind_body(&[(DAV, "supported-report-set")]),
678 )
679 .await;
680 let reports = prop(&parse_multistatus(&r), CAL, DAV, "supported-report-set").unwrap();
681 assert_eq!(xml::elements(&reports).count(), 4);
682
683 // multiget: stored bytes back, a miss as 404.
684 let body = format!(
685 r#"<c:calendar-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
686 <d:prop><d:getetag/><c:calendar-data/></d:prop>
687 <d:href>{CAL}lunch.ics</d:href><d:href>{CAL}gone.ics</d:href>
688 </c:calendar-multiget>"#
689 );
690 let r = req(&env, "REPORT", CAL, &auth, &[("depth", "1")], &body).await;
691 let ms = parse_multistatus(&r);
692 let lunch = format!("{CAL}lunch.ics");
693 // The CR of each CRLF goes out as `&#13;`, which XML parsing keeps.
694 assert!(r.text().contains("&#13;\n"), "{}", r.text());
695 let data = prop_text(&ms, &lunch, CALDAV, "calendar-data").unwrap();
696 assert_eq!(data, ics(LUNCH).trim());
697 assert!(statuses(&r).contains(&(format!("{CAL}gone.ics"), Some(404))));
698
699 // Time range: the Monday 2026-01-05 holds only an instance of the weekly
700 // series, which started a month earlier in Berlin time.
701 let range = r#"<c:comp-filter name="VEVENT"><c:time-range start="20260105T000000Z" end="20260106T000000Z"/></c:comp-filter>"#;
702 let r = req(
703 &env,
704 "REPORT",
705 CAL,
706 &auth,
707 &[("depth", "1")],
708 &query(range, ""),
709 )
710 .await;
711 assert_eq!(hrefs_in(&r), [format!("{CAL}weekly.ics")]);
712
713 // The same with expand: one instance in UTC, without the RRULE.
714 let expand = r#"<c:calendar-data><c:expand start="20260105T000000Z" end="20260106T000000Z"/></c:calendar-data>"#;
715 let r = req(
716 &env,
717 "REPORT",
718 CAL,
719 &auth,
720 &[("depth", "1")],
721 &query(range, expand),
722 )
723 .await;
724 let data = prop_text(
725 &parse_multistatus(&r),
726 &format!("{CAL}weekly.ics"),
727 CALDAV,
728 "calendar-data",
729 )
730 .unwrap();
731 assert!(data.contains("DTSTART:20260105T080000Z"), "{data}");
732 assert!(data.contains("RECURRENCE-ID:20260105T080000Z"), "{data}");
733 assert!(!data.contains("RRULE"), "{data}");
734
735 // text-match folds ASCII case by default, and negates on request.
736 let text = r#"<c:comp-filter name="VEVENT"><c:prop-filter name="SUMMARY"><c:text-match>team lunch</c:text-match></c:prop-filter></c:comp-filter>"#;
737 let r = req(
738 &env,
739 "REPORT",
740 CAL,
741 &auth,
742 &[("depth", "1")],
743 &query(text, ""),
744 )
745 .await;
746 assert_eq!(hrefs_in(&r), std::slice::from_ref(&lunch));
747 let negated = text.replace("<c:text-match>", r#"<c:text-match negate-condition="yes">"#);
748 let r = req(
749 &env,
750 "REPORT",
751 CAL,
752 &auth,
753 &[("depth", "1")],
754 &query(&negated, ""),
755 )
756 .await;
757 assert_eq!(hrefs_in(&r), [format!("{CAL}weekly.ics")]);
758 let odd = text.replace("<c:text-match>", r#"<c:text-match collation="i;klingon">"#);
759 let r = req(
760 &env,
761 "REPORT",
762 CAL,
763 &auth,
764 &[("depth", "1")],
765 &query(&odd, ""),
766 )
767 .await;
768 assert_eq!(r.status, StatusCode::FORBIDDEN);
769 assert_eq!(
770 error_condition(&r),
771 Name::new(CALDAV, "supported-collation")
772 );
773
774 // A VTODO with only DUE matches the range that holds DUE.
775 let todo = r#"<c:comp-filter name="VTODO"><c:time-range start="20260110T000000Z" end="20260111T000000Z"/></c:comp-filter>"#;
776 let r = req(
777 &env,
778 "REPORT",
779 CAL,
780 &auth,
781 &[("depth", "1")],
782 &query(todo, ""),
783 )
784 .await;
785 assert_eq!(hrefs_in(&r), [format!("{CAL}todo.ics")]);
786
787 // Only the components asked for.
788 let comp = r#"<c:calendar-data><c:comp name="VCALENDAR"><c:comp name="VEVENT"><c:prop name="SUMMARY"/></c:comp></c:comp></c:calendar-data>"#;
789 let r = req(
790 &env,
791 "REPORT",
792 CAL,
793 &auth,
794 &[("depth", "1")],
795 &query(text, comp),
796 )
797 .await;
798 let data = prop_text(&parse_multistatus(&r), &lunch, CALDAV, "calendar-data").unwrap();
799 assert!(
800 data.contains("SUMMARY:Team Lunch")
801 && !data.contains("DTSTART")
802 && !data.contains("VERSION"),
803 "{data}"
804 );
805
806 let fb = r#"<c:free-busy-query xmlns:c="urn:ietf:params:xml:ns:caldav"><c:time-range start="20260101T000000Z" end="20260106T000000Z"/></c:free-busy-query>"#;
807 let r = req(&env, "REPORT", CAL, &auth, &[("depth", "1")], fb).await;
808 assert_eq!(r.status, StatusCode::OK);
809 assert!(
810 r.header("content-type")
811 .unwrap()
812 .starts_with("text/calendar")
813 );
814 assert!(
815 r.text()
816 .contains("FREEBUSY;FBTYPE=BUSY:20260105T080000Z/20260105T083000Z"),
817 "{}",
818 r.text()
819 );
820 assert!(
821 r.text()
822 .contains("FREEBUSY;FBTYPE=BUSY:20260101T120000Z/20260101T130000Z"),
823 "{}",
824 r.text()
825 );
826
827 // An address book report on a calendar is refused.
828 let r = req(&env, "REPORT", CAL, &auth, &[], r#"<card:addressbook-query xmlns:card="urn:ietf:params:xml:ns:carddav"><card:filter/></card:addressbook-query>"#).await;
829 assert_eq!(error_condition(&r), Name::new(DAV, "supported-report"));
830}
831
832#[tokio::test]
833async fn sync_collection() {
834 let (env, auth) = setup().await;
835 let sync = |token: &str, limit: &str| {
836 format!(
837 r#"<d:sync-collection xmlns:d="DAV:"><d:sync-token>{token}</d:sync-token><d:sync-level>1</d:sync-level>{limit}<d:prop><d:getetag/></d:prop></d:sync-collection>"#
838 )
839 };
840 put(&env, &auth, &format!("{CAL}a.ics"), &event("a", "A")).await;
841 put(&env, &auth, &format!("{CAL}b.ics"), &event("b", "B")).await;
842
843 let r = req(&env, "REPORT", CAL, &auth, &[], &sync("", "")).await;
844 assert_eq!(hrefs_in(&r), [format!("{CAL}a.ics"), format!("{CAL}b.ics")]);
845 let token = sync_token_of(&r);
846
847 put(&env, &auth, &format!("{CAL}c.ics"), &event("c", "C")).await;
848 put(&env, &auth, &format!("{CAL}a.ics"), &event("a", "A2")).await;
849 let r = req(&env, "DELETE", &format!("{CAL}b.ics"), &auth, &[], "").await;
850 assert_eq!(r.status, StatusCode::NO_CONTENT);
851
852 let r = req(&env, "REPORT", CAL, &auth, &[], &sync(&token, "")).await;
853 let mut got = statuses(&r);
854 got.sort();
855 assert_eq!(
856 got,
857 [
858 (format!("{CAL}a.ics"), None),
859 (format!("{CAL}b.ics"), Some(404)),
860 (format!("{CAL}c.ics"), None),
861 ]
862 );
863 let latest = sync_token_of(&r);
864 let r = req(&env, "REPORT", CAL, &auth, &[], &sync(&latest, "")).await;
865 assert!(statuses(&r).is_empty());
866
867 // A limit hands out the token of the last change it returned.
868 let limit = "<d:limit><d:nresults>1</d:nresults></d:limit>";
869 let r = req(&env, "REPORT", CAL, &auth, &[], &sync(&token, limit)).await;
870 let got = statuses(&r);
871 assert_eq!(got.len(), 2);
872 assert_eq!(got[1], (CAL.to_string(), Some(507)));
873 let r = req(
874 &env,
875 "REPORT",
876 CAL,
877 &auth,
878 &[],
879 &sync(&sync_token_of(&r), ""),
880 )
881 .await;
882 assert_eq!(statuses(&r).len(), 2);
883
884 for bad in ["urn:fbng:sync:999-1", "nonsense", &format!("{latest}0")] {
885 let r = req(&env, "REPORT", CAL, &auth, &[], &sync(bad, "")).await;
886 assert_eq!(
887 error_condition(&r),
888 Name::new(DAV, "valid-sync-token"),
889 "{bad}"
890 );
891 }
892}
893
894#[tokio::test]
895async fn addressbook_reports() {
896 let (env, auth) = setup().await;
897 let card = |uid: &str, name: &str, mail: &str| {
898 format!(
899 "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:{uid}\r\nFN:{name}\r\nEMAIL;TYPE=WORK:{mail}\r\nEND:VCARD\r\n"
900 )
901 };
902 put(
903 &env,
904 &auth,
905 &format!("{BOOK}bob.vcf"),
906 &card("bob", "Bob Builder", "bob@example.com"),
907 )
908 .await;
909 put(
910 &env,
911 &auth,
912 &format!("{BOOK}ann.vcf"),
913 &card("ann", "Ann Äpfel", "ann@example.org"),
914 )
915 .await;
916 let query = |filter: &str, data: &str| {
917 format!(
918 r#"<card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><d:prop><d:getetag/>{data}</d:prop>{filter}</card:addressbook-query>"#
919 )
920 };
921 let email = r#"<card:filter><card:prop-filter name="EMAIL"><card:text-match match-type="ends-with">.ORG</card:text-match></card:prop-filter></card:filter>"#;
922 let r = req(&env, "REPORT", BOOK, &auth, &[], &query(email, "")).await;
923 assert_eq!(hrefs_in(&r), [format!("{BOOK}ann.vcf")]);
924
925 // Unicode case folding is the CardDAV default.
926 let fname = r#"<card:filter><card:prop-filter name="FN"><card:text-match match-type="equals">ann äpfel</card:text-match></card:prop-filter></card:filter>"#;
927 let r = req(
928 &env,
929 "REPORT",
930 BOOK,
931 &auth,
932 &[],
933 &query(
934 fname,
935 "<card:address-data><card:prop name=\"FN\"/></card:address-data>",
936 ),
937 )
938 .await;
939 let data = prop_text(
940 &parse_multistatus(&r),
941 &format!("{BOOK}ann.vcf"),
942 CARDDAV,
943 "address-data",
944 )
945 .unwrap();
946 assert!(
947 data.contains("Ann Äpfel") && !data.contains("EMAIL"),
948 "{data}"
949 );
950
951 let param = r#"<card:filter test="allof"><card:prop-filter name="EMAIL"><card:param-filter name="TYPE"><card:text-match match-type="equals">work</card:text-match></card:param-filter></card:prop-filter><card:prop-filter name="NICKNAME"><card:is-not-defined/></card:prop-filter></card:filter>"#;
952 let r = req(&env, "REPORT", BOOK, &auth, &[], &query(param, "")).await;
953 assert_eq!(hrefs_in(&r).len(), 2);
954
955 let limited = query(
956 "<card:filter/><card:limit><card:nresults>1</card:nresults></card:limit>",
957 "",
958 );
959 let r = req(&env, "REPORT", BOOK, &auth, &[], &limited).await;
960 let got = statuses(&r);
961 assert_eq!(got.len(), 2);
962 assert_eq!(got[1], (BOOK.to_string(), Some(507)));
963
964 let body = format!(
965 r#"<card:addressbook-multiget xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><d:prop><card:address-data/></d:prop><d:href>{BOOK}bob.vcf</d:href></card:addressbook-multiget>"#
966 );
967 let r = req(&env, "REPORT", BOOK, &auth, &[], &body).await;
968 let data = prop_text(
969 &parse_multistatus(&r),
970 &format!("{BOOK}bob.vcf"),
971 CARDDAV,
972 "address-data",
973 )
974 .unwrap();
975 assert!(data.contains("FN:Bob Builder"));
976}
977
978#[tokio::test]
979async fn move_objects() {
980 let (env, auth) = setup().await;
981 let r = req(&env, "MKCALENDAR", &format!("{HOME}work/"), &auth, &[], "").await;
982 assert_eq!(r.status, StatusCode::CREATED);
983 put(&env, &auth, &format!("{CAL}a.ics"), &event("a", "A")).await;
984 put(&env, &auth, &format!("{CAL}b.ics"), &event("b", "B")).await;
985
986 let dest = |p: &str| format!("http://localhost{p}");
987 let r = req(
988 &env,
989 "MOVE",
990 &format!("{CAL}a.ics"),
991 &auth,
992 &[("destination", &dest(&format!("{HOME}work/a.ics")))],
993 "",
994 )
995 .await;
996 assert_eq!(r.status, StatusCode::CREATED);
997 assert_eq!(
998 req(&env, "GET", &format!("{CAL}a.ics"), &auth, &[], "")
999 .await
1000 .status,
1001 StatusCode::NOT_FOUND
1002 );
1003 assert_eq!(
1004 req(&env, "GET", &format!("{HOME}work/a.ics"), &auth, &[], "")
1005 .await
1006 .text(),
1007 event("a", "A")
1008 );
1009
1010 // Overwrite: F refuses an existing destination.
1011 put(&env, &auth, &format!("{CAL}a2.ics"), &event("a2", "A2")).await;
1012 let r = req(
1013 &env,
1014 "MOVE",
1015 &format!("{CAL}a2.ics"),
1016 &auth,
1017 &[("destination", &format!("{CAL}b.ics")), ("overwrite", "F")],
1018 "",
1019 )
1020 .await;
1021 assert_eq!(r.status, StatusCode::PRECONDITION_FAILED);
1022 let r = req(
1023 &env,
1024 "MOVE",
1025 &format!("{CAL}a2.ics"),
1026 &auth,
1027 &[("destination", &format!("{CAL}b.ics"))],
1028 "",
1029 )
1030 .await;
1031 assert_eq!(r.status, StatusCode::NO_CONTENT);
1032
1033 // The same UID under another name in the destination.
1034 put(&env, &auth, &format!("{CAL}dup.ics"), &event("a", "again")).await;
1035 let r = req(
1036 &env,
1037 "MOVE",
1038 &format!("{CAL}dup.ics"),
1039 &auth,
1040 &[("destination", &format!("{HOME}work/other.ics"))],
1041 "",
1042 )
1043 .await;
1044 assert_eq!(error_condition(&r), Name::new(CALDAV, "no-uid-conflict"));
1045
1046 // Across kinds is refused.
1047 let r = req(
1048 &env,
1049 "MOVE",
1050 &format!("{CAL}b.ics"),
1051 &auth,
1052 &[("destination", &format!("{BOOK}b.vcf"))],
1053 "",
1054 )
1055 .await;
1056 assert_eq!(r.status, StatusCode::FORBIDDEN);
1057}
1058
1059#[tokio::test]
1060async fn hrefs_follow_the_requested_spelling() {
1061 let (env, auth) = setup().await;
1062 let body = propfind_body(&[(DAV, "displayname")]);
1063 let r = req(
1064 &env,
1065 "PROPFIND",
1066 "/pim/calendars/ALICE/",
1067 &auth,
1068 &[("depth", "1")],
1069 &body,
1070 )
1071 .await;
1072 let hrefs = hrefs_in(&r);
1073 assert!(
1074 hrefs.iter().all(|h| h.starts_with("/pim/calendars/ALICE/")),
1075 "{hrefs:?}"
1076 );
1077}
1078
1079// ---------------------------------------------------------------------------
1080// Sharing, the system address book, rooms and principal search
1081// ---------------------------------------------------------------------------
1082
1083const BOB: &str = "bob";
1084const BOB_PW: &str = "bob12345678";
1085
1086/// alice with an event in her default calendar, and bob.
1087async fn two_users() -> (Env, Client, String, String) {
1088 let env = Env::new().await;
1089 let admin = env.admin().await;
1090 create_user(&admin, ALICE, PW, &[]).await;
1091 create_user(&admin, BOB, BOB_PW, &[]).await;
1092 let alice = basic(ALICE, PW);
1093 put(&env, &alice, &format!("{CAL}lunch.ics"), &ics(LUNCH)).await;
1094 (env, admin, alice, basic(BOB, BOB_PW))
1095}
1096
1097/// The id of alice's default calendar, from the JSON API.
1098async fn calendar_id(alice: &Client) -> i64 {
1099 let r = alice.get("/api/pim/collections").await;
1100 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
1101 r.json()
1102 .as_array()
1103 .unwrap()
1104 .iter()
1105 .find(|c| c["kind"] == "calendar" && c["mode"].is_null())
1106 .unwrap()["id"]
1107 .as_i64()
1108 .unwrap()
1109}
1110
1111fn privilege_names(p: &Element) -> Vec<String> {
1112 xml::elements(p)
1113 .flat_map(xml::elements)
1114 .map(|e| e.name.clone())
1115 .collect()
1116}
1117
1118#[tokio::test]
1119async fn lent_collections() {
1120 let (env, admin, alice_auth, bob) = two_users().await;
1121 let alice = login(&env, ALICE, PW).await;
1122 let id = calendar_id(&alice).await;
1123 let shares = format!("/api/pim/collections/{id}/shares");
1124
1125 let r = alice
1126 .post_json(&shares, &json!({"user": "nobody", "mode": "ro"}))
1127 .await;
1128 assert_eq!(r.status, StatusCode::NOT_FOUND);
1129 let r = alice
1130 .post_json(&shares, &json!({"user": ALICE, "mode": "ro"}))
1131 .await;
1132 assert_eq!(r.status, StatusCode::BAD_REQUEST);
1133 let r = alice
1134 .post_json(&shares, &json!({"user": "BOB", "mode": "ro"}))
1135 .await;
1136 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
1137 let bob_client = login(&env, BOB, BOB_PW).await;
1138 assert_eq!(bob_client.get(&shares).await.status, StatusCode::NOT_FOUND);
1139 let listed = bob_client.get("/api/pim/collections").await.json();
1140 let lent = listed
1141 .as_array()
1142 .unwrap()
1143 .iter()
1144 .find(|c| c["id"] == id)
1145 .unwrap()
1146 .clone();
1147 assert_eq!(lent["mode"], "ro");
1148 assert_eq!(lent["owner"], ALICE);
1149 let shared = format!("/pim/calendars/bob/shared-{id}/");
1150 assert_eq!(lent["url"], shared.as_str());
1151
1152 // bob's home shows it, read-only, with alice as the owner.
1153 let body = propfind_body(&[
1154 (DAV, "displayname"),
1155 (DAV, "owner"),
1156 (DAV, "current-user-privilege-set"),
1157 ]);
1158 let r = req(
1159 &env,
1160 "PROPFIND",
1161 "/pim/calendars/bob/",
1162 &bob,
1163 &[("depth", "1")],
1164 &body,
1165 )
1166 .await;
1167 let ms = parse_multistatus(&r);
1168 assert_eq!(
1169 prop_text(&ms, &shared, DAV, "displayname").as_deref(),
1170 Some("Calendar (alice)")
1171 );
1172 assert_eq!(
1173 hrefs_of(&prop(&ms, &shared, DAV, "owner").unwrap()),
1174 ["/pim/principals/alice/"]
1175 );
1176 let privs = privilege_names(&prop(&ms, &shared, DAV, "current-user-privilege-set").unwrap());
1177 assert_eq!(privs, ["read", "read-current-user-privilege-set"]);
1178
1179 // Read works through every method, writes do not.
1180 let lunch = format!("{shared}lunch.ics");
1181 let r = req(&env, "GET", &lunch, &bob, &[], "").await;
1182 assert_eq!(r.status, StatusCode::OK);
1183 let r = req(&env, "REPORT", &shared, &bob, &[], &query("", "")).await;
1184 assert_eq!(hrefs_in(&r), [lunch.as_str()]);
1185 let sync = r#"<d:sync-collection xmlns:d="DAV:"><d:sync-token/><d:prop><d:getetag/></d:prop></d:sync-collection>"#;
1186 let r = req(&env, "REPORT", &shared, &bob, &[], sync).await;
1187 assert_eq!(hrefs_in(&r), [lunch.as_str()]);
1188 let r = req(
1189 &env,
1190 "PUT",
1191 &format!("{shared}new.ics"),
1192 &bob,
1193 &[],
1194 &event("new", "x"),
1195 )
1196 .await;
1197 assert_eq!(r.status, StatusCode::FORBIDDEN);
1198 assert!(error_condition(&r).is(DAV, "need-privileges"));
1199 let r = req(&env, "DELETE", &lunch, &bob, &[], "").await;
1200 assert_eq!(r.status, StatusCode::FORBIDDEN);
1201 let patch = r#"<d:propertyupdate xmlns:d="DAV:"><d:set><d:prop><d:displayname>Mine</d:displayname></d:prop></d:set></d:propertyupdate>"#;
1202 let r = req(&env, "PROPPATCH", &shared, &bob, &[], patch).await;
1203 assert_eq!(r.status, StatusCode::FORBIDDEN);
1204
1205 // Read-write: bob adds an event, alice sees it; bob moves one out.
1206 let r = alice
1207 .post_json(&shares, &json!({"user": BOB, "mode": "rw"}))
1208 .await;
1209 assert_eq!(r.status, StatusCode::OK);
1210 put(
1211 &env,
1212 &bob,
1213 &format!("{shared}new.ics"),
1214 &event("new", "from bob"),
1215 )
1216 .await;
1217 let r = req(&env, "GET", &format!("{CAL}new.ics"), &alice_auth, &[], "").await;
1218 assert_eq!(r.status, StatusCode::OK);
1219 let r = req(
1220 &env,
1221 "MOVE",
1222 &format!("{shared}new.ics"),
1223 &bob,
1224 &[("destination", "/pim/calendars/bob/default/new.ics")],
1225 "",
1226 )
1227 .await;
1228 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
1229 let r = req(&env, "GET", &format!("{CAL}new.ics"), &alice_auth, &[], "").await;
1230 assert_eq!(r.status, StatusCode::NOT_FOUND);
1231 let r = req(&env, "PROPPATCH", &shared, &bob, &[], patch).await;
1232 assert_eq!(r.status, StatusCode::FORBIDDEN);
1233
1234 // bob deleting it only takes it out of his home.
1235 let r = req(&env, "DELETE", &shared, &bob, &[], "").await;
1236 assert_eq!(r.status, StatusCode::NO_CONTENT);
1237 assert_eq!(
1238 req(&env, "GET", &lunch, &bob, &[], "").await.status,
1239 StatusCode::NOT_FOUND
1240 );
1241 assert!(
1242 alice
1243 .get(&shares)
1244 .await
1245 .json()
1246 .as_array()
1247 .unwrap()
1248 .is_empty()
1249 );
1250 let r = req(
1251 &env,
1252 "GET",
1253 &format!("{CAL}lunch.ics"),
1254 &alice_auth,
1255 &[],
1256 "",
1257 )
1258 .await;
1259 assert_eq!(r.status, StatusCode::OK);
1260
1261 // Revoking, and deleting the borrower, end the loan.
1262 alice
1263 .post_json(&shares, &json!({"user": BOB, "mode": "ro"}))
1264 .await;
1265 let r = alice
1266 .delete(&format!("{shares}/{}", user_id(&admin, BOB).await))
1267 .await;
1268 assert_eq!(r.status, StatusCode::OK);
1269 assert_eq!(
1270 req(&env, "GET", &lunch, &bob, &[], "").await.status,
1271 StatusCode::NOT_FOUND
1272 );
1273 alice
1274 .post_json(&shares, &json!({"user": BOB, "mode": "ro"}))
1275 .await;
1276 let r = admin
1277 .delete(&format!("/api/admin/users/{}", user_id(&admin, BOB).await))
1278 .await;
1279 assert_eq!(r.status, StatusCode::OK);
1280 assert!(
1281 alice
1282 .get(&shares)
1283 .await
1284 .json()
1285 .as_array()
1286 .unwrap()
1287 .is_empty()
1288 );
1289}
1290
1291const DIR: &str = "/pim/addressbooks/alice/system/";
1292
1293#[tokio::test]
1294async fn system_address_book() {
1295 let (env, admin, alice, _) = two_users().await;
1296 let body = propfind_body(&[(DAV, "getetag"), (CALSERVER, "getctag")]);
1297 let r = req(&env, "PROPFIND", DIR, &alice, &[("depth", "1")], &body).await;
1298 let ms = parse_multistatus(&r);
1299 // admin, alice and bob.
1300 assert_eq!(ms.len(), 4);
1301 let ctag = prop_text(&ms, DIR, CALSERVER, "getctag").unwrap();
1302 let card = ms.iter().find(|(h, _)| h != DIR).unwrap().0.clone();
1303 let r = req(&env, "GET", &card, &alice, &[], "").await;
1304 assert_eq!(r.status, StatusCode::OK);
1305 assert!(r.text().contains("EMAIL;TYPE=INTERNET:"), "{}", r.text());
1306
1307 let q = r#"<card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
1308 <d:prop><card:address-data/></d:prop>
1309 <card:filter><card:prop-filter name="FN"><card:text-match>BOB</card:text-match></card:prop-filter></card:filter>
1310 </card:addressbook-query>"#;
1311 let r = req(&env, "REPORT", DIR, &alice, &[], q).await;
1312 assert_eq!(statuses(&r).len(), 1);
1313 assert!(r.text().contains("FN:bob"));
1314
1315 let sync = |token: &str| {
1316 format!(
1317 r#"<d:sync-collection xmlns:d="DAV:"><d:sync-token>{token}</d:sync-token><d:prop><d:getetag/></d:prop></d:sync-collection>"#
1318 )
1319 };
1320 let r = req(&env, "REPORT", DIR, &alice, &[], &sync("")).await;
1321 assert_eq!(statuses(&r).len(), 3);
1322 let token = sync_token_of(&r);
1323 let r = req(&env, "REPORT", DIR, &alice, &[], &sync(&token)).await;
1324 assert!(statuses(&r).is_empty());
1325
1326 // A new account changes the CTag, and the old token no longer works.
1327 create_user(&admin, "carol", "carol12345", &[]).await;
1328 let r = req(&env, "REPORT", DIR, &alice, &[], &sync(&token)).await;
1329 assert_eq!(r.status, StatusCode::FORBIDDEN);
1330 assert!(error_condition(&r).is(DAV, "valid-sync-token"));
1331 let r = req(&env, "PROPFIND", DIR, &alice, &[("depth", "0")], &body).await;
1332 assert_ne!(
1333 prop_text(&parse_multistatus(&r), DIR, CALSERVER, "getctag").unwrap(),
1334 ctag
1335 );
1336
1337 let r = req(
1338 &env,
1339 "PUT",
1340 &format!("{DIR}x.vcf"),
1341 &alice,
1342 &[],
1343 "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:x\r\nEND:VCARD\r\n",
1344 )
1345 .await;
1346 assert_eq!(r.status, StatusCode::FORBIDDEN);
1347 assert!(error_condition(&r).is(DAV, "need-privileges"));
1348 assert_eq!(
1349 req(&env, "DELETE", &card, &alice, &[], "").await.status,
1350 StatusCode::FORBIDDEN
1351 );
1352 assert_eq!(
1353 req(&env, "DELETE", DIR, &alice, &[], "").await.status,
1354 StatusCode::FORBIDDEN
1355 );
1356 let r = req(&env, "MKCOL", DIR, &alice, &[], "").await;
1357 assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
1358}
1359
1360#[tokio::test]
1361async fn rooms_and_resources() {
1362 let (env, admin, alice, _) = two_users().await;
1363 let alice_client = login(&env, ALICE, PW).await;
1364 let room = json!({"name": "board", "display_name": "Board Room", "kind": "room"});
1365 assert_eq!(
1366 alice_client
1367 .post_json("/api/admin/rooms", &room)
1368 .await
1369 .status,
1370 StatusCode::FORBIDDEN
1371 );
1372 let r = admin.post_json("/api/admin/rooms", &room).await;
1373 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
1374 let id = r.json()["id"].as_i64().unwrap();
1375 assert_eq!(r.json()["url"], "/pim/principals/board/");
1376 let taken = json!({"name": "ALICE", "kind": "resource"});
1377 assert_eq!(
1378 admin.post_json("/api/admin/rooms", &taken).await.status,
1379 StatusCode::CONFLICT
1380 );
1381 let r = admin
1382 .post_json(
1383 "/api/admin/users",
1384 &json!({"name": "Board", "password": "x1234567", "is_admin": false, "roots": []}),
1385 )
1386 .await;
1387 assert_eq!(r.status, StatusCode::CONFLICT);
1388 // Not an account: not listed, not editable, no sign-in.
1389 let users = admin.get("/api/admin/users").await.json();
1390 assert!(
1391 users
1392 .as_array()
1393 .unwrap()
1394 .iter()
1395 .all(|u| u["name"] != "board")
1396 );
1397 let r = admin
1398 .put_json(
1399 &format!("/api/admin/users/{id}"),
1400 &json!({"password": "x1234567"}),
1401 )
1402 .await;
1403 assert_eq!(r.status, StatusCode::NOT_FOUND);
1404 let r = req(&env, "PROPFIND", "/pim/", &basic("board", ""), &[], "").await;
1405 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
1406
1407 let p = "/pim/principals/board/";
1408 let body = propfind_body(&[
1409 (DAV, "displayname"),
1410 (CALDAV, "calendar-user-type"),
1411 (CALDAV, "calendar-user-address-set"),
1412 (CALDAV, "calendar-home-set"),
1413 ]);
1414 let r = req(&env, "PROPFIND", p, &alice, &[], &body).await;
1415 let ms = parse_multistatus(&r);
1416 assert_eq!(
1417 prop_text(&ms, p, DAV, "displayname").as_deref(),
1418 Some("Board Room")
1419 );
1420 assert_eq!(
1421 prop_text(&ms, p, CALDAV, "calendar-user-type").as_deref(),
1422 Some("ROOM")
1423 );
1424 let addresses = hrefs_of(&prop(&ms, p, CALDAV, "calendar-user-address-set").unwrap());
1425 assert!(addresses.contains(&"mailto:board@rooms.filebrowser.invalid".to_string()));
1426 assert_eq!(
1427 hrefs_of(&prop(&ms, p, CALDAV, "calendar-home-set").unwrap()),
1428 ["/pim/calendars/board/"]
1429 );
1430
1431 // Everyone reads the bookings; only admins write them.
1432 let cal = "/pim/calendars/board/default/";
1433 let r = req(&env, "PROPFIND", cal, &alice, &[("depth", "0")], "").await;
1434 assert_eq!(r.status, StatusCode::MULTI_STATUS);
1435 let r = req(
1436 &env,
1437 "PUT",
1438 &format!("{cal}b.ics"),
1439 &alice,
1440 &[],
1441 &event("b", "x"),
1442 )
1443 .await;
1444 assert_eq!(r.status, StatusCode::FORBIDDEN);
1445 put(
1446 &env,
1447 &basic("admin", "admin1234"),
1448 &format!("{cal}b.ics"),
1449 &event("b", "x"),
1450 )
1451 .await;
1452 assert_eq!(
1453 req(&env, "GET", &format!("{cal}b.ics"), &alice, &[], "")
1454 .await
1455 .status,
1456 StatusCode::OK
1457 );
1458
1459 // In the system address book as a location.
1460 let r = req(&env, "REPORT", DIR, &alice, &[], r#"<card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><d:prop><card:address-data/></d:prop><card:filter><card:prop-filter name="KIND"><card:text-match match-type="equals">location</card:text-match></card:prop-filter></card:filter></card:addressbook-query>"#).await;
1461 assert!(r.text().contains("FN:Board Room"), "{}", r.text());
1462
1463 let r = admin
1464 .put_json(
1465 &format!("/api/admin/rooms/{id}"),
1466 &json!({"display_name": "Boardroom"}),
1467 )
1468 .await;
1469 assert_eq!(r.json()["display_name"], "Boardroom");
1470 assert_eq!(
1471 admin
1472 .get("/api/admin/rooms")
1473 .await
1474 .json()
1475 .as_array()
1476 .unwrap()
1477 .len(),
1478 1
1479 );
1480 assert_eq!(
1481 admin.delete(&format!("/api/admin/rooms/{id}")).await.status,
1482 StatusCode::OK
1483 );
1484 assert_eq!(
1485 req(&env, "PROPFIND", p, &alice, &[], "").await.status,
1486 StatusCode::NOT_FOUND
1487 );
1488}
1489
1490#[tokio::test]
1491async fn principal_search() {
1492 let (env, admin, alice, _) = two_users().await;
1493 admin
1494 .post_json(
1495 "/api/admin/rooms",
1496 &json!({"name": "board", "display_name": "Board Room", "kind": "room"}),
1497 )
1498 .await;
1499 let principals = "/pim/principals/";
1500
1501 let r = req(&env, "PROPFIND", principals, &alice, &[("depth", "1")], "").await;
1502 // The collection, admin, alice, bob and the room.
1503 assert_eq!(parse_multistatus(&r).len(), 5);
1504
1505 let pps = r#"<d:principal-property-search xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" test="anyof">
1506 <d:property-search><d:prop><d:displayname/></d:prop><d:match>BO</d:match></d:property-search>
1507 <d:prop><d:displayname/><c:calendar-user-type/></d:prop>
1508 </d:principal-property-search>"#;
1509 let r = req(&env, "REPORT", principals, &alice, &[("depth", "0")], pps).await;
1510 assert_eq!(
1511 hrefs_in(&r),
1512 ["/pim/principals/board/", "/pim/principals/bob/"]
1513 );
1514 let ms = parse_multistatus(&r);
1515 assert_eq!(
1516 prop_text(&ms, "/pim/principals/board/", CALDAV, "calendar-user-type").as_deref(),
1517 Some("ROOM")
1518 );
1519
1520 let cs = r#"<cs:calendarserver-principal-search xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/" context="location">
1521 <cs:search-token>bo</cs:search-token><d:prop><d:displayname/></d:prop>
1522 </cs:calendarserver-principal-search>"#;
1523 let r = req(&env, "REPORT", principals, &alice, &[], cs).await;
1524 assert_eq!(hrefs_in(&r), ["/pim/principals/board/"]);
1525
1526 let set = r#"<d:principal-search-property-set xmlns:d="DAV:"/>"#;
1527 let r = req(&env, "REPORT", principals, &alice, &[], set).await;
1528 assert_eq!(r.status, StatusCode::OK);
1529 assert!(r.text().contains("calendar-user-address-set"));
1530
1531 // Not a collection report.
1532 let r = req(&env, "REPORT", CAL, &alice, &[], pps).await;
1533 assert_eq!(r.status, StatusCode::FORBIDDEN);
1534}
1535
1536#[tokio::test]
1537async fn bad_filters_are_refused_by_name() {
1538 let (env, auth) = setup().await;
1539 let bad = query(
1540 r#"<c:comp-filter name="VEVENT"><c:time-range start="20260102T000000Z" end="20260101T000000Z"/></c:comp-filter>"#,
1541 "",
1542 );
1543 let r = req(&env, "REPORT", CAL, &auth, &[], &bad).await;
1544 assert_eq!(r.status, StatusCode::FORBIDDEN);
1545 assert!(error_condition(&r).is(CALDAV, "valid-filter"));
1546 let bad = r#"<card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><card:filter test="sometimes"/></card:addressbook-query>"#;
1547 let r = req(&env, "REPORT", BOOK, &auth, &[], bad).await;
1548 assert!(error_condition(&r).is(CARDDAV, "valid-filter"));
1549}
1550