fix(dav): repair CalDAV/CardDAV client connectivity (#480)

Standard CalDAV/CardDAV clients (Thunderbird, DAVx5, Apple
Calendar/Contacts) failed to connect, mounted collections read-only, or
could not discover address books, even though curl worked. Three
protocol-compliance gaps caused this:

1. Missing Basic-auth challenge on /caldav and /carddav.
   The 401 returned for these surfaces carried no `WWW-Authenticate`
   header (only /webdav did). Spec-compliant clients never send
   credentials preemptively the way `curl -u` does — they wait for the
   challenge — so Thunderbird never authenticated and failed with
   "discovery failed" / 401. Extend the challenge to all DAV surfaces via
   shared `is_dav_path` / `dav_basic_auth_challenge` helpers.

2. Calendars always advertised read-only.
   The `current-user-privilege-set` write gate compared `owner_id`
   against the literal string "current_user_id", which never matched a
   real UUID, so `<D:write/>` was never emitted and clients mounted every
   calendar read-only. Thread the caller's id through the CalDAV adapter
   and grant write when the caller owns the calendar.

3. CardDAV discovery was incomplete.
   There was no `/.well-known/carddav` route and the root PROPFIND
   exposed neither `current-user-principal` nor `addressbook-home-set`,
   so clients could not locate address books. Add the well-known redirect
   and root/principal discovery responses mirroring the CalDAV adapter.

Adds unit tests for the auth challenge predicate, the calendar
owner/non-owner privilege split, and the CardDAV root/principal discovery
responses.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016cVV9nRQjP6G6a8zbNUWMw
This commit is contained in:
Claude
2026-06-19 08:38:27 +00:00
parent 8c325302b4
commit fe852d3b79
8 changed files with 605 additions and 48 deletions
+30 -9
View File
@@ -17,6 +17,19 @@ use crate::application::adapters::webdav_adapter::{
};
use crate::application::dtos::calendar_dto::{CalendarDto, CalendarEventDto};
/// Returns whether `caller_id` owns `calendar`.
///
/// CalDAV clients (DAVx5, Apple Calendar, Thunderbird) only mount a collection
/// read-write when its `current-user-privilege-set` advertises `<D:write/>`, so
/// this gate decides read-only vs read-write for the caller. `caller_id` and
/// [`CalendarDto::owner_id`] are both the user's UUID rendered via
/// `Uuid::to_string()`, so a direct comparison is exact. Calendars merely shared
/// with the caller (non-owner access) stay read-only for now — this never
/// over-grants write.
fn caller_owns_calendar(calendar: &CalendarDto, caller_id: &str) -> bool {
!caller_id.is_empty() && calendar.owner_id == caller_id
}
/// CalDAV report type
#[derive(Debug, PartialEq)]
pub enum CalDavReportType {
@@ -205,6 +218,7 @@ impl CalDavAdapter {
request: &PropFindRequest,
base_href: &str,
username: &str,
caller_id: &str,
) -> Result<()> {
let mut xml_writer = Writer::new(writer);
@@ -227,6 +241,7 @@ impl CalDavAdapter {
calendar,
request,
&format!("{}{}/", base_href, calendar.id),
caller_id,
)?;
}
@@ -242,6 +257,7 @@ impl CalDavAdapter {
calendars: &[CalendarDto],
request: &PropFindRequest,
base_href: &str,
caller_id: &str,
) -> Result<()> {
let mut xml_writer = Writer::new(writer);
@@ -261,6 +277,7 @@ impl CalDavAdapter {
calendar,
request,
&format!("{}{}/", base_href, calendar.id),
caller_id,
)?;
}
@@ -557,6 +574,7 @@ impl CalDavAdapter {
calendar: &CalendarDto,
request: &PropFindRequest,
href: &str,
caller_id: &str,
) -> Result<()> {
// Start response element
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
@@ -576,7 +594,7 @@ impl CalDavAdapter {
match &request.prop_find_type {
PropFindType::AllProp => {
// Write all standard properties for a calendar
Self::write_calendar_standard_props(xml_writer, calendar)?;
Self::write_calendar_standard_props(xml_writer, calendar, caller_id)?;
}
PropFindType::PropName => {
// Write only property names (empty elements)
@@ -584,7 +602,7 @@ impl CalDavAdapter {
}
PropFindType::Prop(props) => {
// Write requested properties
Self::write_calendar_requested_props(xml_writer, calendar, props)?;
Self::write_calendar_requested_props(xml_writer, calendar, props, caller_id)?;
}
}
@@ -609,6 +627,7 @@ impl CalDavAdapter {
fn write_calendar_standard_props<W: Write>(
xml_writer: &mut Writer<W>,
calendar: &CalendarDto,
caller_id: &str,
) -> Result<()> {
// Common WebDAV properties
@@ -676,9 +695,10 @@ impl CalDavAdapter {
xml_writer.write_event(Event::Empty(BytesStart::new("D:read")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
// Only add write privilege if user owns the calendar or has write access
if calendar.owner_id == "current_user_id" {
// This should be replaced with actual user check
// Advertise write only when the caller owns the calendar. Clients
// (DAVx5, Apple Calendar, Thunderbird) mount the collection read-only
// unless this privilege is present.
if caller_owns_calendar(calendar, caller_id) {
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:write")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
@@ -735,6 +755,7 @@ impl CalDavAdapter {
xml_writer: &mut Writer<W>,
calendar: &CalendarDto,
props: &[QualifiedName],
caller_id: &str,
) -> Result<()> {
for prop in props {
match (prop.namespace.as_str(), prop.name.as_str()) {
@@ -780,9 +801,8 @@ impl CalDavAdapter {
xml_writer.write_event(Event::Empty(BytesStart::new("D:read")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
// Only add write privilege if user owns the calendar or has write access
if calendar.owner_id == "current_user_id" {
// This should be replaced with actual user check
// Advertise write only when the caller owns the calendar.
if caller_owns_calendar(calendar, caller_id) {
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:write")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
@@ -882,6 +902,7 @@ impl CalDavAdapter {
request: &PropFindRequest,
base_href: &str,
depth: &str,
caller_id: &str,
) -> Result<()> {
let mut xml_writer = Writer::new(writer);
@@ -894,7 +915,7 @@ impl CalDavAdapter {
))?;
// Write the calendar collection itself
Self::write_calendar_response(&mut xml_writer, calendar, request, base_href)?;
Self::write_calendar_response(&mut xml_writer, calendar, request, base_href, caller_id)?;
// If depth > 0, include event resources
if depth != "0" {
@@ -171,6 +171,7 @@ mod tests {
&calendars,
&request,
"/caldav/",
"user-001",
);
assert!(
@@ -210,6 +211,7 @@ mod tests {
&request,
"/caldav/cal-001",
"0",
"user-001",
);
assert!(
@@ -240,6 +242,7 @@ mod tests {
&request,
"/caldav/cal-001",
"1",
"user-001",
);
assert!(
@@ -258,6 +261,54 @@ mod tests {
);
}
#[test]
fn test_owner_gets_write_privilege_but_non_owner_is_read_only() {
// Regression for #480: the privilege gate previously compared owner_id
// against the literal "current_user_id", so <D:write/> was never emitted
// and every CalDAV client mounted calendars read-only.
let calendar = sample_calendar(); // owner_id = "user-001"
let request = PropFindRequest {
prop_find_type: PropFindType::AllProp,
};
// Owner → read + write.
let mut owner_out = Vec::new();
CalDavAdapter::generate_calendar_collection_propfind(
&mut owner_out,
&calendar,
&[],
&request,
"/caldav/cal-001/",
"0",
"user-001",
)
.expect("owner propfind");
let owner_xml = String::from_utf8(owner_out).expect("utf8");
assert!(
owner_xml.contains("D:write"),
"Owner must be granted <D:write/>, got: {owner_xml}"
);
// A different caller (e.g. a read-only share) → read only, never write.
let mut other_out = Vec::new();
CalDavAdapter::generate_calendar_collection_propfind(
&mut other_out,
&calendar,
&[],
&request,
"/caldav/cal-001/",
"0",
"a-different-user",
)
.expect("non-owner propfind");
let other_xml = String::from_utf8(other_out).expect("utf8");
assert!(other_xml.contains("D:read"), "Non-owner keeps <D:read/>");
assert!(
!other_xml.contains("D:write"),
"Non-owner must NOT get <D:write/>, got: {other_xml}"
);
}
// ========================
// Calendar events response tests
// ========================
@@ -434,6 +485,7 @@ mod tests {
&request,
"/caldav/",
"testuser",
"user-001",
);
assert!(
result.is_ok(),
@@ -483,6 +535,7 @@ mod tests {
&request,
"/caldav/",
"testuser",
"user-001",
);
assert!(result.is_ok());
@@ -565,6 +618,7 @@ mod tests {
&request,
"/caldav/cal-001/",
"0",
"user-001",
);
assert!(result.is_ok(), "Failed: {:?}", result.err());
+257 -8
View File
@@ -17,6 +17,20 @@ use crate::application::adapters::webdav_adapter::{
use crate::application::dtos::address_book_dto::AddressBookDto;
use crate::application::dtos::contact_dto::ContactDto;
/// Render a requested property as a namespaced response element name, mapping
/// the known namespaces to their response prefixes (`D:` for DAV, `CR:` for
/// CardDAV). Used for the catch-all arms of the requested-property writers so
/// the prefix mapping lives in exactly one place.
fn carddav_prop_name(prop: &QualifiedName) -> String {
if prop.namespace == "urn:ietf:params:xml:ns:carddav" {
format!("CR:{}", prop.name)
} else if prop.namespace == "DAV:" {
format!("D:{}", prop.name)
} else {
prop.name.clone()
}
}
/// CardDAV report type
#[derive(Debug, PartialEq)]
pub enum CardDavReportType {
@@ -163,6 +177,96 @@ impl CardDavAdapter {
Ok(())
}
/// Generate a PROPFIND response for the CardDAV root `/carddav/`.
///
/// Mirrors the CalDAV root: emits a discovery entry for `/carddav/` itself
/// advertising `current-user-principal` and `addressbook-home-set` (the
/// properties DAVx5 / Apple Contacts read to locate address books), then —
/// at Depth > 0 — one entry per address book. Without these discovery
/// properties clients never find the address books at all.
pub fn generate_root_propfind_response<W: Write>(
writer: W,
address_books: &[AddressBookDto],
request: &PropFindRequest,
base_href: &str,
username: &str,
) -> Result<()> {
let mut xml_writer = Writer::new(writer);
xml_writer.write_event(Event::Start(
BytesStart::new("D:multistatus").with_attributes([
("xmlns:D", "DAV:"),
("xmlns:CR", "urn:ietf:params:xml:ns:carddav"),
("xmlns:CS", "http://calendarserver.org/ns/"),
]),
))?;
Self::write_carddav_root_response(&mut xml_writer, request, base_href, username)?;
for book in address_books {
Self::write_addressbook_response(
&mut xml_writer,
book,
request,
&format!("{}{}/", base_href, book.id),
)?;
}
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
Ok(())
}
/// Generate a PROPFIND response for a CardDAV user principal resource at
/// `/carddav/principals/{username}/`.
///
/// Returns `addressbook-home-set` so clients can resolve the collection
/// holding the user's address books, plus a self-referential
/// `current-user-principal`.
pub fn generate_principal_propfind_response<W: Write>(
writer: W,
request: &PropFindRequest,
username: &str,
) -> Result<()> {
let mut xml_writer = Writer::new(writer);
xml_writer.write_event(Event::Start(
BytesStart::new("D:multistatus").with_attributes([
("xmlns:D", "DAV:"),
("xmlns:CR", "urn:ietf:params:xml:ns:carddav"),
("xmlns:CS", "http://calendarserver.org/ns/"),
]),
))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
let href = format!("/carddav/principals/{}/", username);
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&href)))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:propstat")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:prop")))?;
match &request.prop_find_type {
PropFindType::AllProp | PropFindType::PropName => {
Self::write_carddav_principal_props(&mut xml_writer, username)?;
}
PropFindType::Prop(props) => {
Self::write_carddav_principal_requested_props(&mut xml_writer, username, props)?;
}
}
xml_writer.write_event(Event::End(BytesEnd::new("D:prop")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:status")))?;
xml_writer.write_event(Event::Text(BytesText::new("HTTP/1.1 200 OK")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:status")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:propstat")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:response")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
Ok(())
}
/// Generate PROPFIND for a single address book collection + contacts
pub fn generate_addressbook_collection_propfind<W: Write>(
writer: W,
@@ -384,14 +488,159 @@ impl CardDavAdapter {
.write_event(Event::End(BytesEnd::new("D:current-user-privilege-set")))?;
}
_ => {
let prop_name = if prop.namespace == "urn:ietf:params:xml:ns:carddav" {
format!("CR:{}", prop.name)
} else if prop.namespace == "DAV:" {
format!("D:{}", prop.name)
} else {
prop.name.clone()
};
xml_writer.write_event(Event::Empty(BytesStart::new(&prop_name)))?;
xml_writer
.write_event(Event::Empty(BytesStart::new(carddav_prop_name(prop))))?;
}
}
}
Ok(())
}
/// Write a populated `current-user-principal` element pointing at the user's
/// CardDAV principal. Shared by the root and principal discovery responses.
fn write_current_user_principal<W: Write>(
xml_writer: &mut Writer<W>,
username: &str,
) -> Result<()> {
xml_writer.write_event(Event::Start(BytesStart::new("D:current-user-principal")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/carddav/principals/{}/",
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:current-user-principal")))?;
Ok(())
}
/// Write a populated `addressbook-home-set` element pointing at the user's
/// address-book home collection. Shared by the root and principal responses.
fn write_addressbook_home_set<W: Write>(
xml_writer: &mut Writer<W>,
username: &str,
) -> Result<()> {
xml_writer.write_event(Event::Start(BytesStart::new("CR:addressbook-home-set")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(&format!(
"/carddav/{}/",
username
))))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer.write_event(Event::End(BytesEnd::new("CR:addressbook-home-set")))?;
Ok(())
}
/// Write the root `/carddav/` discovery entry.
fn write_carddav_root_response<W: Write>(
xml_writer: &mut Writer<W>,
request: &PropFindRequest,
href: &str,
username: &str,
) -> Result<()> {
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
xml_writer.write_event(Event::Text(BytesText::new(href)))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:propstat")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:prop")))?;
match &request.prop_find_type {
PropFindType::AllProp => {
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
Self::write_current_user_principal(xml_writer, username)?;
Self::write_addressbook_home_set(xml_writer, username)?;
}
PropFindType::PropName => {
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
xml_writer
.write_event(Event::Empty(BytesStart::new("D:current-user-principal")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("CR:addressbook-home-set")))?;
}
PropFindType::Prop(props) => {
for prop in props {
match (prop.namespace.as_str(), prop.name.as_str()) {
("DAV:", "resourcetype") => {
xml_writer
.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
xml_writer
.write_event(Event::Empty(BytesStart::new("D:collection")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
}
("DAV:", "current-user-principal") => {
Self::write_current_user_principal(xml_writer, username)?;
}
("urn:ietf:params:xml:ns:carddav", "addressbook-home-set") => {
Self::write_addressbook_home_set(xml_writer, username)?;
}
_ => {
xml_writer.write_event(Event::Empty(BytesStart::new(
carddav_prop_name(prop),
)))?;
}
}
}
}
}
xml_writer.write_event(Event::End(BytesEnd::new("D:prop")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:status")))?;
xml_writer.write_event(Event::Text(BytesText::new("HTTP/1.1 200 OK")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:status")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:propstat")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:response")))?;
Ok(())
}
/// Write the standard properties for a CardDAV principal resource.
fn write_carddav_principal_props<W: Write>(
xml_writer: &mut Writer<W>,
username: &str,
) -> Result<()> {
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:principal")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
xml_writer.write_event(Event::Start(BytesStart::new("D:displayname")))?;
xml_writer.write_event(Event::Text(BytesText::new(username)))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:displayname")))?;
Self::write_addressbook_home_set(xml_writer, username)?;
Self::write_current_user_principal(xml_writer, username)?;
Ok(())
}
/// Write the requested properties for a CardDAV principal resource.
fn write_carddav_principal_requested_props<W: Write>(
xml_writer: &mut Writer<W>,
username: &str,
props: &[QualifiedName],
) -> Result<()> {
for prop in props {
match (prop.namespace.as_str(), prop.name.as_str()) {
("DAV:", "resourcetype") => {
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
xml_writer.write_event(Event::Empty(BytesStart::new("D:principal")))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
}
("DAV:", "displayname") => {
xml_writer.write_event(Event::Start(BytesStart::new("D:displayname")))?;
xml_writer.write_event(Event::Text(BytesText::new(username)))?;
xml_writer.write_event(Event::End(BytesEnd::new("D:displayname")))?;
}
("DAV:", "current-user-principal") => {
Self::write_current_user_principal(xml_writer, username)?;
}
("urn:ietf:params:xml:ns:carddav", "addressbook-home-set") => {
Self::write_addressbook_home_set(xml_writer, username)?;
}
_ => {
xml_writer
.write_event(Event::Empty(BytesStart::new(carddav_prop_name(prop))))?;
}
}
}
@@ -307,6 +307,97 @@ mod tests {
);
}
#[test]
fn test_root_propfind_advertises_principal_and_home_set() {
// Regression for #480: without these discovery properties DAVx5 / Apple
// Contacts never locate the user's address books.
let books = vec![sample_address_book()];
let request = PropFindRequest {
prop_find_type: PropFindType::AllProp,
};
let mut output = Vec::new();
CardDavAdapter::generate_root_propfind_response(
&mut output,
&books,
&request,
"/carddav/",
"testuser",
)
.expect("root propfind");
let xml = String::from_utf8(output).expect("utf8");
assert!(
xml.contains("/carddav/principals/testuser/"),
"Root must expose current-user-principal href, got: {xml}"
);
assert!(
xml.contains("/carddav/testuser/"),
"Root must expose addressbook-home-set href, got: {xml}"
);
// Depth 1 also enumerates the books.
assert!(xml.contains("ab-001"), "Should list address book");
}
#[test]
fn test_root_propfind_prop_request_returns_populated_discovery() {
// A DAVx5-style targeted request for the two discovery properties.
let request = PropFindRequest {
prop_find_type: PropFindType::Prop(vec![
QualifiedName {
namespace: "DAV:".to_string(),
name: "current-user-principal".to_string(),
},
QualifiedName {
namespace: "urn:ietf:params:xml:ns:carddav".to_string(),
name: "addressbook-home-set".to_string(),
},
]),
};
let mut output = Vec::new();
CardDavAdapter::generate_root_propfind_response(
&mut output,
&[],
&request,
"/carddav/",
"testuser",
)
.expect("root propfind");
let xml = String::from_utf8(output).expect("utf8");
assert!(xml.contains("/carddav/principals/testuser/"));
assert!(xml.contains("/carddav/testuser/"));
// Properties must be populated, not empty self-closing placeholders.
assert!(!xml.contains("<D:current-user-principal/>"));
assert!(!xml.contains("<CR:addressbook-home-set/>"));
}
#[test]
fn test_principal_propfind_returns_home_set() {
let request = PropFindRequest {
prop_find_type: PropFindType::AllProp,
};
let mut output = Vec::new();
CardDavAdapter::generate_principal_propfind_response(&mut output, &request, "testuser")
.expect("principal propfind");
let xml = String::from_utf8(output).expect("utf8");
assert!(
xml.contains("/carddav/principals/testuser/"),
"Principal href should be present"
);
assert!(
xml.contains("/carddav/testuser/"),
"addressbook-home-set should be present"
);
assert!(
xml.contains("D:principal"),
"resourcetype should include principal"
);
}
#[test]
fn test_generate_addressbook_collection_propfind_depth_0() {
let addressbook = sample_address_book();