//! Public feeds, import and export of calendars and address books.
mod common;
use axum::http::{Method, StatusCode};
use common::*;
use serde_json::{Value, json};
const PW: &str = "secret12345";
const CAL: &str = "/pim/calendars/alice/default/";
struct Io {
env: Env,
alice: Client,
}
impl Io {
async fn new() -> Self {
let env = Env::new().await;
let admin = env.admin().await;
create_user(&admin, "alice", PW, &[]).await;
create_user(&admin, "bob", PW, &[]).await;
let alice = login(&env, "alice", PW).await;
Io { env, alice }
}
async fn dav(&self, user: &str, verb: &str, path: &str, body: &str) -> Resp {
let auth = basic(user, PW);
// Without Depth, PROPFIND lists only the collection itself.
Client::new(self.env.app.clone())
.raw(
Method::from_bytes(verb.as_bytes()).unwrap(),
path,
&[("authorization", &auth), ("depth", "1")],
body.as_bytes().to_vec(),
)
.await
}
async fn anon(&self, path: &str, headers: &[(&str, &str)]) -> Resp {
Client::new(self.env.app.clone())
.raw(Method::GET, path, headers, Vec::new())
.await
}
/// The id of alice's collection with this CalDAV/CardDAV URL.
async fn id(&self, url: &str) -> i64 {
let list = self.alice.get("/api/pim/collections").await.json();
list.as_array()
.unwrap()
.iter()
.find(|c| c["url"] == url)
.unwrap_or_else(|| panic!("no collection {url}: {list}"))["id"]
.as_i64()
.unwrap()
}
async fn link(&self, id: i64, body: Value) -> String {
let r = self
.alice
.post_json(&format!("/api/pim/collections/{id}/links"), &body)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
r.json()["path"].as_str().unwrap().to_string()
}
async fn import(&self, id: i64, body: &str) -> Value {
let r = self
.alice
.raw(
Method::POST,
&format!("/api/pim/collections/{id}/import"),
&[("content-type", "text/calendar")],
body.as_bytes().to_vec(),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
r.json()
}
}
fn event(uid: &str, summary: &str, extra: &str) -> String {
format!(
"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"
)
}
#[tokio::test]
async fn feeds() {
let io = Io::new().await;
let cal = io.id(CAL).await;
let book = io.id("/pim/addressbooks/alice/default/").await;
for uid in ["a", "b"] {
let r = io
.dav(
"alice",
"PUT",
&format!("{CAL}{uid}.ics"),
&event(
uid,
"Secret plan",
"BEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER:-PT5M\r\nEND:VALARM\r\n",
),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.text());
}
let r = io
.dav(
"alice",
"PUT",
&format!("{CAL}p.ics"),
&event("p", "Doctor", "CLASS:PRIVATE\r\n"),
)
.await;
assert_eq!(r.status, StatusCode::CREATED);
let full = io.link(cal, json!({})).await;
assert!(
full.starts_with("/feed/") && full.ends_with(".ics"),
"{full}"
);
let r = io.anon(&full, &[]).await;
assert_eq!(r.status, StatusCode::OK);
assert!(
r.header("content-type")
.unwrap()
.starts_with("text/calendar")
);
let text = r.text();
assert!(
text.contains("UID:a\r\n") && text.contains("UID:b\r\n"),
"{text}"
);
assert!(text.contains("X-WR-CALNAME:"));
assert!(text.contains("Secret plan"));
// A public link shows private events as busy time only.
assert!(
!text.contains("Doctor") && text.contains("SUMMARY:Busy"),
"{text}"
);
let etag = r.header("etag").unwrap();
let r = io.anon(&full, &[("if-none-match", &etag)]).await;
assert_eq!(r.status, StatusCode::NOT_MODIFIED);
// The extension is optional.
let bare = full.trim_end_matches(".ics");
assert_eq!(io.anon(bare, &[]).await.status, StatusCode::OK);
// A change gives a new ETag.
io.dav("alice", "PUT", &format!("{CAL}c.ics"), &event("c", "x", ""))
.await;
let r = io.anon(&full, &[("if-none-match", &etag)]).await;
assert_eq!(r.status, StatusCode::OK);
let busy = io.link(cal, json!({ "busy_only": true })).await;
let text = io.anon(&busy, &[]).await.text();
assert!(text.contains("SUMMARY:Busy"), "{text}");
assert!(
!text.contains("Secret plan") && !text.contains("VALARM"),
"{text}"
);
assert!(!text.contains("UID:a\r\n"), "UIDs are hashed: {text}");
// The owner's export keeps everything.
let export = io
.alice
.get(&format!("/api/pim/collections/{cal}/export"))
.await
.text();
assert!(export.contains("Doctor"));
let locked = io.link(cal, json!({ "password": "feedpass123" })).await;
let r = io.anon(&locked, &[]).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
assert!(r.header("www-authenticate").is_some());
let wrong = basic("", "nope-nope");
for _ in 0..3 {
let r = io.anon(&locked, &[("authorization", &wrong)]).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
}
let right = basic("anyone", "feedpass123");
assert_eq!(
io.anon(&locked, &[("authorization", &right)]).await.status,
StatusCode::OK
);
let expired = io
.link(cal, json!({ "expires_at": "2000-01-01T00:00:00Z" }))
.await;
assert_eq!(io.anon(&expired, &[]).await.status, StatusCode::GONE);
let cards = io.link(book, json!({})).await;
assert!(cards.ends_with(".vcf"));
let r = io.anon(&cards, &[]).await;
assert!(r.header("content-type").unwrap().starts_with("text/vcard"));
let r = io
.alice
.post_json(
&format!("/api/pim/collections/{book}/links"),
&json!({ "busy_only": true }),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
// Only the owner sees and manages the links.
let bob = login(&io.env, "bob", PW).await;
assert_eq!(
bob.get(&format!("/api/pim/collections/{cal}/links"))
.await
.status,
StatusCode::NOT_FOUND
);
let list = io
.alice
.get(&format!("/api/pim/collections/{cal}/links"))
.await
.json();
assert_eq!(list.as_array().unwrap().len(), 4);
let first = list[0]["id"].as_i64().unwrap();
let r = io
.alice
.delete(&format!("/api/pim/collections/{cal}/links/{first}"))
.await;
assert_eq!(r.status, StatusCode::OK);
assert_eq!(io.anon(&full, &[]).await.status, StatusCode::NOT_FOUND);
// A deleted collection takes its links along.
let r = io
.dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
.await;
assert_eq!(r.status, StatusCode::CREATED);
let work = io.id("/pim/calendars/alice/work/").await;
let gone = io.link(work, json!({})).await;
assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::OK);
io.dav("alice", "DELETE", "/pim/calendars/alice/work/", "")
.await;
assert_eq!(io.anon(&gone, &[]).await.status, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn import_splits_and_updates() {
let io = Io::new().await;
let cal = io.id(CAL).await;
let file = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:x\r\nMETHOD:PUBLISH\r\n\
BEGIN:VEVENT\r\nUID:m\r\nDTSTART:20260105T100000Z\r\nRRULE:FREQ=DAILY;COUNT=3\r\nEND:VEVENT\r\n\
BEGIN:VEVENT\r\nUID:m\r\nRECURRENCE-ID:20260106T100000Z\r\nDTSTART:20260106T120000Z\r\nEND:VEVENT\r\n\
BEGIN:VEVENT\r\nDTSTART:20260107T100000Z\r\nSUMMARY:no uid\r\nEND:VEVENT\r\n\
BEGIN:VEVENT\r\nUID:nostart\r\nSUMMARY:no start\r\nEND:VEVENT\r\n\
BEGIN:VFREEBUSY\r\nUID:fb\r\nEND:VFREEBUSY\r\nEND:VCALENDAR\r\n";
let r = io.import(cal, file).await;
assert_eq!(r["created"], 2, "{r}");
assert_eq!(r["updated"], 0);
assert_eq!(r["skipped_total"], 2);
let reasons: Vec<&str> = r["skipped"]
.as_array()
.unwrap()
.iter()
.map(|s| s["reason"].as_str().unwrap())
.collect();
assert!(reasons.contains(&"supported-calendar-component"), "{r}");
assert!(reasons.contains(&"valid-calendar-data"), "{r}");
// The same file again updates, also the event that had no UID.
let r = io.import(cal, file).await;
assert_eq!(
(r["created"].as_i64(), r["updated"].as_i64()),
(Some(0), Some(2))
);
let r = io.dav("alice", "PROPFIND", CAL, "").await;
let listing = r.text();
assert_eq!(listing.matches(".ics").count(), 2, "{listing}");
let export = io
.alice
.get(&format!("/api/pim/collections/{cal}/export"))
.await;
let text = export.text();
assert!(!text.contains("METHOD"));
assert!(text.contains("RECURRENCE-ID:20260106T100000Z"));
assert!(text.contains("DTSTAMP:"), "import adds DTSTAMP: {text}");
}
#[tokio::test]
async fn import_sends_nothing_and_keeps_uniqueness() {
let io = Io::new().await;
let cal = io.id(CAL).await;
let meeting = event(
"meet",
"Meeting",
"ORGANIZER:mailto:alice@dovenest.invalid\r\nATTENDEE:mailto:bob@dovenest.invalid\r\n",
);
let r = io.import(cal, &meeting).await;
assert_eq!(r["created"], 1, "{r}");
// Stored as a scheduling object, with a Schedule-Tag like after a PUT.
let listing = io.dav("alice", "PROPFIND", CAL, "").await.text();
let href = listing
.split("")
.filter_map(|s| s.split("").next())
.find(|h| h.ends_with(".ics"))
.unwrap_or_else(|| panic!("{listing}"))
.to_string();
let r = io.dav("alice", "GET", &href, "").await;
assert!(r.header("schedule-tag").is_some());
// bob got neither a copy nor a message.
for path in ["/pim/calendars/bob/default/", "/pim/calendars/bob/inbox/"] {
let r = io.dav("bob", "PROPFIND", path, "").await;
assert!(!r.text().contains(".ics"), "{path}: {}", r.text());
}
// One scheduling object per UID and owner (RFC 6638, 3.2.4.1).
io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/work/", "")
.await;
let work = io.id("/pim/calendars/alice/work/").await;
let r = io.import(work, &meeting).await;
assert_eq!(r["created"], 0);
assert_eq!(r["skipped"][0]["uid"], "meet");
assert_eq!(
r["skipped"][0]["reason"],
"unique-scheduling-object-resource"
);
// A read-only loan cannot be imported into.
let bob = login(&io.env, "bob", PW).await;
io.alice
.post_json(
&format!("/api/pim/collections/{cal}/shares"),
&json!({ "user": "bob", "mode": "ro" }),
)
.await;
let r = bob
.raw(
Method::POST,
&format!("/api/pim/collections/{cal}/import"),
&[("content-type", "text/calendar")],
event("x", "x", "").into_bytes(),
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
// But exported.
let r = bob.get(&format!("/api/pim/collections/{cal}/export")).await;
assert_eq!(r.status, StatusCode::OK);
}
#[tokio::test]
async fn export_round_trip() {
let io = Io::new().await;
let cal = io.id(CAL).await;
io.import(cal, &event("r1", "One", "")).await;
io.import(cal, &event("r2", "Two", "")).await;
let url = format!("/api/pim/collections/{cal}/export");
let r = io.alice.get(&url).await;
assert_eq!(r.status, StatusCode::OK);
let disposition = r.header("content-disposition").unwrap();
assert!(disposition.starts_with("attachment;") && disposition.contains(".ics"));
let exported = r.text();
// Download only: there is no saving into a folder.
let r = io.alice.post_json(&url, &json!({})).await;
assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
// The export imports back as the same objects.
io.dav("alice", "MKCALENDAR", "/pim/calendars/alice/copy/", "")
.await;
let copy = io.id("/pim/calendars/alice/copy/").await;
let r = io.import(copy, &exported).await;
assert_eq!(r["created"], 2, "{r}");
// vCards, one without UID.
let book = io.id("/pim/addressbooks/alice/default/").await;
let cards = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:One\r\nEND:VCARD\r\n\
BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Two\r\nEND:VCARD\r\n";
let r = io.import(book, cards).await;
assert_eq!(r["created"], 2, "{r}");
let r = io.import(book, cards).await;
assert_eq!(r["updated"], 2, "{r}");
// The system address book has no collection id of its own.
let r = io.alice.get("/api/pim/system/export").await;
assert_eq!(r.status, StatusCode::OK);
assert!(r.header("content-disposition").unwrap().contains(".vcf"));
assert!(r.text().contains("FN:alice"));
}
#[tokio::test]
async fn import_as_a_new_collection() {
let io = Io::new().await;
let post = |query: &str, body: String| {
let (client, query) = (&io.alice, query.to_string());
async move {
let r = client
.raw(
Method::POST,
&format!("/api/pim/import?{query}"),
&[("content-type", "text/calendar")],
body.into_bytes(),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
r.json()
}
};
let before = collections(&io.alice).await;
let vevent = |uid: &str, summary: &str| {
format!(
"BEGIN:VEVENT\r\nUID:{uid}\r\nDTSTAMP:20260101T000000Z\r\nDTSTART:20260101T100000Z\r\nSUMMARY:{summary}\r\nEND:VEVENT\r\n"
)
};
// The file names itself and its color.
let ics = format!(
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:Ferien\r\nX-APPLE-CALENDAR-COLOR:#FF2968FF\r\n{}END:VCALENDAR\r\n",
vevent("f1", "Sommer")
);
let r = post("kind=calendar&file=holidays.ics&color=%2322c55e", ics).await;
assert_eq!(r["created"], 1, "{r}");
assert_eq!(r["collection"]["name"], "Ferien", "{r}");
assert_eq!(r["collection"]["color"], "#FF2968FF", "{r}");
// A typed name wins; without a color in the file the requested one counts.
let plain = format!(
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nCOLOR:teal\r\n{}END:VCALENDAR\r\n",
vevent("f2", "Winter")
);
let r = post("kind=calendar&name=Mine&file=x.ics&color=%2322c55e", plain).await;
assert_eq!(r["collection"]["name"], "Mine", "{r}");
assert_eq!(r["collection"]["color"], "#22c55e", "{r}");
// An address book takes the file name.
let vcf = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:c1\r\nFN:Ann\r\nN:;Ann;;;\r\nEND:VCARD\r\n";
let r = post("kind=addressbook&file=Team%20contacts.vcf", vcf.to_string()).await;
assert_eq!(r["collection"]["name"], "Team contacts", "{r}");
assert_eq!(r["collection"]["kind"], "addressbook", "{r}");
assert_eq!(collections(&io.alice).await, before + 3);
// Nothing importable: reported, and no empty collection is left behind.
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";
let r = post("kind=calendar&file=bad.ics", broken.to_string()).await;
assert_eq!(r["collection"], Value::Null, "{r}");
assert_eq!(r["skipped_total"], 1, "{r}");
assert_eq!(collections(&io.alice).await, before + 3);
}
async fn collections(c: &Client) -> usize {
c.get("/api/pim/collections")
.await
.json()
.as_array()
.unwrap()
.len()
}
#[tokio::test]
async fn share_candidates_leave_out_owner_borrowers_and_disabled() {
let io = Io::new().await;
let admin = login(&io.env, "admin", "admin1234").await;
create_user(&admin, "carol", PW, &[]).await;
create_user(&admin, "dave", PW, &[]).await;
let dave = user_id(&admin, "dave").await;
let r = admin
.put_json(
&format!("/api/admin/users/{dave}"),
&json!({"active": false}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
let r = admin
.post_json(
"/api/admin/rooms",
&json!({"name": "atrium", "kind": "room"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
let id = io.id(CAL).await;
let r = io
.alice
.post_json(
&format!("/api/pim/collections/{id}/shares"),
&json!({"user": "bob", "mode": "ro"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
let names = |v: Value| -> Vec {
v.as_array()
.unwrap()
.iter()
.map(|c| c["name"].as_str().unwrap().to_string())
.collect()
};
let r = io
.alice
.get(&format!("/api/pim/collections/{id}/shares/candidates"))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
// Not alice herself, not bob (a borrower), not dave (disabled), no room.
assert_eq!(names(r.json()), ["admin", "carol"]);
// Only the owner may ask.
let bob = login(&io.env, "bob", PW).await;
let r = bob
.get(&format!("/api/pim/collections/{id}/shares/candidates"))
.await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn a_skipped_import_into_a_new_user_leaves_only_the_default_calendar() {
use server::db::PimKind;
let io = Io::new().await;
let client = login(&io.env, "bob", PW).await;
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";
let r = client
.raw(
Method::POST,
"/api/pim/import?kind=calendar&file=bad.ics",
&[("content-type", "text/calendar")],
broken.as_bytes().to_vec(),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
assert_eq!(r.json()["collection"], Value::Null);
assert_eq!(r.json()["skipped_total"], 1);
let db = &io.env.state.db;
let bob = db.find_user_by_name("bob").await.unwrap().unwrap();
let pid = db.principal_of(bob.id).await.unwrap();
let slugs: Vec<_> = db
.pim_collections(pid, PimKind::Calendar)
.await
.unwrap()
.into_iter()
.map(|c| c.slug)
.filter(|s| s != "inbox" && s != "outbox")
.collect();
assert_eq!(slugs, ["default"]);
}