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, &[("docs", "rw"), ("src", "ro")]).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 root_id(&self, index: usize) -> i64 {
59 self.alice.get("/api/auth/me").await.json()["roots"][index]["id"]
60 .as_i64()
61 .unwrap()
62 }
63
64 async fn link(&self, id: i64, body: Value) -> String {
65 let r = self
66 .alice
67 .post_json(&format!("/api/pim/collections/{id}/links"), &body)
68 .await;
69 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
70 r.json()["path"].as_str().unwrap().to_string()
71 }
72
73 async fn import(&self, id: i64, body: &str) -> Value {
74 let r = self
75 .alice
76 .raw(
77 Method::POST,
78 &format!("/api/pim/collections/{id}/import"),
79 &[("content-type", "text/calendar")],
80 body.as_bytes().to_vec(),
81 )
82 .await;
83 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
84 r.json()
85 }
86}
87
88fn event(uid: &str, summary: &str, extra: &str) -> String {
89 format!(
90 "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"
91 )
92}
93
94#[tokio::test]
95async fn feeds() {
96 let io = Io::new().await;
97 let cal = io.id(CAL).await;
98 let book = io.id("/pim/addressbooks/alice/default/").await;
99 for uid in ["a", "b"] {
100 let r = io
101 .dav(
102 "alice",
103 "PUT",
104 &format!("{CAL}{uid}.ics"),
105 &event(
106 uid,
107 "Secret plan",
108 "BEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER:-PT5M\r\nEND:VALARM\r\n",
109 ),
110 )
111 .await;
112 assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
113 }
114
115 let r = io
116 .dav(
117 "alice",
118 "PUT",
119 &format!("{CAL}p.ics"),
120 &event("p", "Doctor", "CLASS:PRIVATE\r\n"),
121 )
122 .await;
123 assert_eq!(r.status, StatusCode::CREATED);
124
125 let full = io.link(cal, json!({})).await;
126 assert!(
127 full.starts_with("/feed/") && full.ends_with(".ics"),
128 "{full}"
129 );
130 let r = io.anon(&full, &[]).await;
131 assert_eq!(r.status, StatusCode::OK);
132 assert!(
133 r.header("content-type")
134 .unwrap()
135 .starts_with("text/calendar")
136 );
137 let text = r.text();
138 assert!(
139 text.contains("UID:a\r\n") && text.contains("UID:b\r\n"),
140 "{text}"
141 );
142 assert!(text.contains("X-WR-CALNAME:"));
143 assert!(text.contains("Secret plan"));
144 // A public link shows private events as busy time only.
145 assert!(
146 !text.contains("Doctor") && text.contains("SUMMARY:Busy"),
147 "{text}"
148 );
149 let etag = r.header("etag").unwrap();
150 let r = io.anon(&full, &[("if-none-match", &etag)]).await;
151 assert_eq!(r.status, StatusCode::NOT_MODIFIED);
152 // The extension is optional.
153 let bare = full.trim_end_matches(".ics");
154 assert_eq!(io.anon(bare, &[]).await.status, StatusCode::OK);
155
156 // A change gives a new ETag.
157 io.dav("alice", "PUT", &format!("{CAL}c.ics"), &event("c", "x", ""))
158 .await;
159 let r = io.anon(&full, &[("if-none-match", &etag)]).await;
160 assert_eq!(r.status, StatusCode::OK);
161
162 let busy = io.link(cal, json!({ "busy_only": true })).await;
163 let text = io.anon(&busy, &[]).await.text();
164 assert!(text.contains("SUMMARY:Busy"), "{text}");
165 assert!(
166 !text.contains("Secret plan") && !text.contains("VALARM"),
167 "{text}"
168 );
169 assert!(!text.contains("UID:a\r\n"), "UIDs are hashed: {text}");
170 // The owner's export keeps everything.
171 let export = io
172 .alice
173 .get(&format!("/api/pim/collections/{cal}/export"))
174 .await
175 .text();
176 assert!(export.contains("Doctor"));
177
178 let locked = io.link(cal, json!({ "password": "feedpass123" })).await;
179 let r = io.anon(&locked, &[]).await;
180 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
181 assert!(r.header("www-authenticate").is_some());
182 let wrong = basic("", "nope-nope");
183 for _ in 0..3 {
184 let r = io.anon(&locked, &[("authorization", &wrong)]).await;
185 assert_eq!(r.status, StatusCode::UNAUTHORIZED);
186 }
187 let right = basic("anyone", "feedpass123");
188 assert_eq!(
189 io.anon(&locked, &[("authorization", &right)]).await.status,
190 StatusCode::OK
191 );
192
193 let expired = io
194 .link(cal, json!({ "expires_at": "2000-01-01T00:00:00Z" }))
195 .await;
196 assert_eq!(io.anon(&expired, &[]).await.status, StatusCode::GONE);
197
198 let cards = io.link(book, json!({})).await;
199 assert!(cards.ends_with(".vcf"));
200 let r = io.anon(&cards, &[]).await;
201 assert!(r.header("content-type").unwrap().starts_with("text/vcard"));
202 let r = io
203 .alice
204 .post_json(
205 &format!("/api/pim/collections/{book}/links"),
206 &json!({ "busy_only": true }),
207 )
208 .await;
209 assert_eq!(r.status, StatusCode::BAD_REQUEST);
210
211 // Only the owner sees and manages the links.
212 let bob = login(&io.env, "bob", PW).await;
213 assert_eq!(
214 bob.get(&format!("/api/pim/collections/{cal}/links"))
215 .await
216 .status,
217 StatusCode::NOT_FOUND
218 );
219 let list = io
220 .alice
221 .get(&format!("/api/pim/collections/{cal}/links"))
222 .await
223 .json();
224 assert_eq!(list.as_array().unwrap().len(), 4);
225 let first = list[0]["id"].as_i64().unwrap();
226 let r = io
227 .alice
228 .delete(&format!("/api/pim/collections/{cal}/links/{first}"))
229 .await;
230 assert_eq!(r.status, StatusCode::OK);
231 assert_eq!(io.anon(&full, &[]).await.status, StatusCode::NOT_FOUND);
232
233 // A deleted collection takes its links along.
234 let r = io
235 .dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
236 .await;
237 assert_eq!(r.status, StatusCode::CREATED);
238 let work = io.id("/pim/calendars/alice/work/").await;
239 let gone = io.link(work, json!({})).await;
240 assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::OK);
241 io.dav("alice", "DELETE", "/pim/calendars/alice/work/", "")
242 .await;
243 assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::NOT_FOUND);
244}
245
246#[tokio::test]
247async fn import_splits_and_updates() {
248 let io = Io::new().await;
249 let cal = io.id(CAL).await;
250 let file = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:x\r\nMETHOD:PUBLISH\r\n\
251 BEGIN:VEVENT\r\nUID:m\r\nDTSTART:20260105T100000Z\r\nRRULE:FREQ=DAILY;COUNT=3\r\nEND:VEVENT\r\n\
252 BEGIN:VEVENT\r\nUID:m\r\nRECURRENCE-ID:20260106T100000Z\r\nDTSTART:20260106T120000Z\r\nEND:VEVENT\r\n\
253 BEGIN:VEVENT\r\nDTSTART:20260107T100000Z\r\nSUMMARY:no uid\r\nEND:VEVENT\r\n\
254 BEGIN:VFREEBUSY\r\nUID:fb\r\nEND:VFREEBUSY\r\nEND:VCALENDAR\r\n";
255 let r = io.import(cal, file).await;
256 assert_eq!(r["created"], 2, "{r}");
257 assert_eq!(r["updated"], 0);
258 assert_eq!(r["skipped_total"], 1);
259 assert_eq!(r["skipped"][0]["reason"], "supported-calendar-component");
260
261 // The same file again updates, also the event that had no UID.
262 let r = io.import(cal, file).await;
263 assert_eq!(
264 (r["created"].as_i64(), r["updated"].as_i64()),
265 (Some(0), Some(2))
266 );
267
268 let r = io.dav("alice", "PROPFIND", CAL, "").await;
269 let listing = r.text();
270 assert_eq!(listing.matches(".ics</").count(), 2, "{listing}");
271 let export = io
272 .alice
273 .get(&format!("/api/pim/collections/{cal}/export"))
274 .await;
275 let text = export.text();
276 assert!(!text.contains("METHOD"));
277 assert!(text.contains("RECURRENCE-ID:20260106T100000Z"));
278 assert!(text.contains("DTSTAMP:"), "import adds DTSTAMP: {text}");
279}
280
281#[tokio::test]
282async fn import_sends_nothing_and_keeps_uniqueness() {
283 let io = Io::new().await;
284 let cal = io.id(CAL).await;
285 let meeting = event(
286 "meet",
287 "Meeting",
288 "ORGANIZER:mailto:alice@filebrowser.invalid\r\nATTENDEE:mailto:bob@filebrowser.invalid\r\n",
289 );
290 let r = io.import(cal, &meeting).await;
291 assert_eq!(r["created"], 1, "{r}");
292 // Stored as a scheduling object, with a Schedule-Tag like after a PUT.
293 let listing = io.dav("alice", "PROPFIND", CAL, "").await.text();
294 let href = listing
295 .split("<d:href>")
296 .filter_map(|s| s.split("</d:href>").next())
297 .find(|h| h.ends_with(".ics"))
298 .unwrap_or_else(|| panic!("{listing}"))
299 .to_string();
300 let r = io.dav("alice", "GET", &href, "").await;
301 assert!(r.header("schedule-tag").is_some());
302 // bob got neither a copy nor a message.
303 for path in ["/pim/calendars/bob/default/", "/pim/calendars/bob/inbox/"] {
304 let r = io.dav("bob", "PROPFIND", path, "").await;
305 assert!(!r.text().contains(".ics</"), "{path}: {}", r.text());
306 }
307
308 // One scheduling object per UID and owner (RFC 6638, 3.2.4.1).
309 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
310 .await;
311 let work = io.id("/pim/calendars/alice/work/").await;
312 let r = io.import(work, &meeting).await;
313 assert_eq!(r["created"], 0);
314 assert_eq!(r["skipped"][0]["uid"], "meet");
315 assert_eq!(
316 r["skipped"][0]["reason"],
317 "unique-scheduling-object-resource"
318 );
319
320 // A read-only loan cannot be imported into.
321 let bob = login(&io.env, "bob", PW).await;
322 io.alice
323 .post_json(
324 &format!("/api/pim/collections/{cal}/shares"),
325 &json!({ "user": "bob", "mode": "ro" }),
326 )
327 .await;
328 let r = bob
329 .raw(
330 Method::POST,
331 &format!("/api/pim/collections/{cal}/import"),
332 &[("content-type", "text/calendar")],
333 event("x", "x", "").into_bytes(),
334 )
335 .await;
336 assert_eq!(r.status, StatusCode::FORBIDDEN);
337 // But exported.
338 let r = bob.get(&format!("/api/pim/collections/{cal}/export")).await;
339 assert_eq!(r.status, StatusCode::OK);
340}
341
342#[tokio::test]
343async fn root_files_and_round_trip() {
344 let io = Io::new().await;
345 let cal = io.id(CAL).await;
346 let (docs, src) = (io.root_id(0).await, io.root_id(1).await);
347 std::fs::write(io.env.file("docs/in.ics"), event("r1", "From a file", "")).unwrap();
348 std::fs::write(io.env.file("src/ro.ics"), event("r2", "Read-only root", "")).unwrap();
349
350 for (root, path) in [(docs, "in.ics"), (src, "ro.ics")] {
351 let r = io
352 .alice
353 .post_json(
354 &format!("/api/pim/collections/{cal}/import"),
355 &json!({ "root_id": root, "path": path }),
356 )
357 .await;
358 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
359 assert_eq!(r.json()["created"], 1);
360 }
361 let r = io
362 .alice
363 .post_json(
364 &format!("/api/pim/collections/{cal}/import"),
365 &json!({ "root_id": docs, "path": "../../etc/passwd" }),
366 )
367 .await;
368 assert_eq!(r.status, StatusCode::FORBIDDEN);
369
370 let r = io
371 .alice
372 .get(&format!("/api/pim/collections/{cal}/export"))
373 .await;
374 assert_eq!(r.status, StatusCode::OK);
375 let disposition = r.header("content-disposition").unwrap();
376 assert!(disposition.starts_with("attachment;") && disposition.contains(".ics"));
377 let exported = r.text();
378
379 let url = format!("/api/pim/collections/{cal}/export");
380 let into = |root: i64| json!({ "root_id": root, "path": "out.ics" });
381 let r = io.alice.post_json(&url, &into(docs)).await;
382 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
383 assert_eq!(
384 std::fs::read_to_string(io.env.file("docs/out.ics")).unwrap(),
385 exported
386 );
387 let r = io.alice.post_json(&url, &into(docs)).await;
388 assert_eq!(r.status, StatusCode::CONFLICT);
389 let r = io.alice.post_json(&url, &into(src)).await;
390 assert_eq!(r.status, StatusCode::FORBIDDEN);
391
392 // The export imports back as the same objects.
393 io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/copy/", "")
394 .await;
395 let copy = io.id("/pim/calendars/alice/copy/").await;
396 let r = io.import(copy, &exported).await;
397 assert_eq!(r["created"], 2, "{r}");
398
399 // vCards, one without UID.
400 let book = io.id("/pim/addressbooks/alice/default/").await;
401 let cards = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:One\r\nEND:VCARD\r\n\
402 BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Two\r\nEND:VCARD\r\n";
403 let r = io.import(book, cards).await;
404 assert_eq!(r["created"], 2, "{r}");
405 let r = io.import(book, cards).await;
406 assert_eq!(r["updated"], 2, "{r}");
407
408 // The system address book has no collection id of its own.
409 let r = io.alice.get("/api/pim/system/export").await;
410 assert_eq!(r.status, StatusCode::OK);
411 assert!(r.header("content-disposition").unwrap().contains(".vcf"));
412 let people = r.text();
413 assert!(people.contains("FN:alice"), "{people}");
414 let into = json!({ "root_id": docs, "path": "people.vcf" });
415 let r = io.alice.post_json("/api/pim/system/export", &into).await;
416 assert_eq!(r.status, StatusCode::OK, "{}", r.text());
417 assert_eq!(
418 std::fs::read_to_string(io.env.file("docs/people.vcf")).unwrap(),
419 people
420 );
421}
422