go-webdav/caldav/server_test.go
Alex Dunmow bcc2aea1d9 caldav: serve principal-URL and, through PrincipalNameBackend, displayname on the principal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:51:22 +08:00

559 lines
20 KiB
Go

package caldav
import (
"context"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/emersion/go-ical"
)
var propFindSupportedCalendarComponentRequest = `
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:prop>
<c:supported-calendar-component-set />
</d:prop>
</d:propfind>
`
var testPropFindSupportedCalendarComponentCases = map[*Calendar][]string{
&Calendar{Path: "/user/calendars/cal"}: []string{"VEVENT"},
&Calendar{Path: "/user/calendars/cal", SupportedComponentSet: []string{"VTODO"}}: []string{"VTODO"},
&Calendar{Path: "/user/calendars/cal", SupportedComponentSet: []string{"VEVENT", "VTODO"}}: []string{"VEVENT", "VTODO"},
}
func TestPropFindSupportedCalendarComponent(t *testing.T) {
for calendar, expected := range testPropFindSupportedCalendarComponentCases {
req := httptest.NewRequest("PROPFIND", calendar.Path, nil)
req.Body = io.NopCloser(strings.NewReader(propFindSupportedCalendarComponentRequest))
req.Header.Set("Content-Type", "application/xml")
w := httptest.NewRecorder()
handler := Handler{Backend: testBackend{calendars: []Calendar{*calendar}}}
handler.ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
resp := string(data)
for _, comp := range expected {
// Would be nicer to do a proper XML-decoding here, but this is probably good enough for now.
if !strings.Contains(resp, comp) {
t.Errorf("Expected component: %v not found in response:\n%v", comp, resp)
}
}
}
}
var propFindUserPrincipal = `
<?xml version="1.0" encoding="UTF-8"?>
<A:propfind xmlns:A="DAV:">
<A:prop>
<A:current-user-principal/>
<A:principal-URL/>
<A:resourcetype/>
</A:prop>
</A:propfind>
`
func TestPropFindRoot(t *testing.T) {
req := httptest.NewRequest("PROPFIND", "/", strings.NewReader(propFindUserPrincipal))
req.Header.Set("Content-Type", "application/xml")
w := httptest.NewRecorder()
calendar := &Calendar{}
handler := Handler{Backend: testBackend{calendars: []Calendar{*calendar}}}
handler.ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
resp := string(data)
if !strings.Contains(resp, `<current-user-principal xmlns="DAV:"><href>/user/</href></current-user-principal>`) {
t.Errorf("No user-principal returned when doing a PROPFIND against root, response:\n%s", resp)
}
}
var reportCalendarData = `
<?xml version="1.0" encoding="UTF-8"?>
<B:calendar-multiget xmlns:A="DAV:" xmlns:B="urn:ietf:params:xml:ns:caldav">
<A:prop>
<B:calendar-data/>
</A:prop>
<A:href>%s</A:href>
</B:calendar-multiget>
`
func TestMultiCalendarBackend(t *testing.T) {
calendarB := Calendar{Path: "/user/calendars/b", SupportedComponentSet: []string{"VTODO"}}
calendars := []Calendar{
Calendar{Path: "/user/calendars/a"},
calendarB,
}
eventSummary := "This is a todo"
event := ical.NewEvent()
event.Name = ical.CompToDo
event.Props.SetText(ical.PropUID, "46bbf47a-1861-41a3-ae06-8d8268c6d41e")
event.Props.SetDateTime(ical.PropDateTimeStamp, time.Now())
event.Props.SetText(ical.PropSummary, eventSummary)
cal := ical.NewCalendar()
cal.Props.SetText(ical.PropVersion, "2.0")
cal.Props.SetText(ical.PropProductID, "-//xyz Corp//NONSGML PDA Calendar Version 1.0//EN")
cal.Children = []*ical.Component{
event.Component,
}
object := CalendarObject{
Path: "/user/calendars/b/test.ics",
Data: cal,
}
req := httptest.NewRequest("PROPFIND", "/user/calendars/", strings.NewReader(propFindUserPrincipal))
req.Header.Set("Content-Type", "application/xml")
w := httptest.NewRecorder()
handler := Handler{Backend: testBackend{
calendars: calendars,
objectMap: map[string][]CalendarObject{
calendarB.Path: []CalendarObject{object},
},
}}
handler.ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
resp := string(data)
for _, calendar := range calendars {
if !strings.Contains(resp, fmt.Sprintf(`<response xmlns="DAV:"><href>%s</href>`, calendar.Path)) {
t.Errorf("Calendar: %v not returned in PROPFIND, response:\n%s", calendar, resp)
}
}
// Now do a PROPFIND for the last calendar
req = httptest.NewRequest("PROPFIND", calendarB.Path, strings.NewReader(propFindSupportedCalendarComponentRequest))
req.Header.Set("Content-Type", "application/xml")
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
res = w.Result()
defer res.Body.Close()
data, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
resp = string(data)
if !strings.Contains(resp, "VTODO") {
t.Errorf("Expected component: VTODO not found in response:\n%v", resp)
}
if !strings.Contains(resp, object.Path) {
t.Errorf("Expected calendar object: %v not found in response:\n%v", object, resp)
}
// Now do a REPORT to get the actual data for the event
req = httptest.NewRequest("REPORT", calendarB.Path, strings.NewReader(fmt.Sprintf(reportCalendarData, object.Path)))
req.Header.Set("Content-Type", "application/xml")
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
res = w.Result()
defer res.Body.Close()
data, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
resp = string(data)
if !strings.Contains(resp, fmt.Sprintf("SUMMARY:%s", eventSummary)) {
t.Errorf("ICAL content not properly returned in response:\n%v", resp)
}
}
type testBackend struct {
calendars []Calendar
objectMap map[string][]CalendarObject
}
func (t testBackend) CreateCalendar(ctx context.Context, calendar *Calendar) error {
return nil
}
func (t testBackend) ListCalendars(ctx context.Context) ([]Calendar, error) {
return t.calendars, nil
}
func (t testBackend) GetCalendar(ctx context.Context, path string) (*Calendar, error) {
for _, cal := range t.calendars {
if cal.Path == path {
return &cal, nil
}
}
return nil, fmt.Errorf("Calendar for path: %s not found", path)
}
func (t testBackend) CalendarHomeSetPath(ctx context.Context) (string, error) {
return "/user/calendars/", nil
}
func (t testBackend) CurrentUserPrincipal(ctx context.Context) (string, error) {
return "/user/", nil
}
func (t testBackend) DeleteCalendarObject(ctx context.Context, path string) error {
return nil
}
func (t testBackend) GetCalendarObject(ctx context.Context, path string, req *CalendarCompRequest) (*CalendarObject, error) {
for _, objs := range t.objectMap {
for _, obj := range objs {
if obj.Path == path {
return &obj, nil
}
}
}
return nil, fmt.Errorf("Couldn't find calendar object at: %s", path)
}
func (t testBackend) PutCalendarObject(ctx context.Context, path string, calendar *ical.Calendar, opts *PutCalendarObjectOptions) (*CalendarObject, error) {
return nil, nil
}
func (t testBackend) ListCalendarObjects(ctx context.Context, path string, req *CalendarCompRequest) ([]CalendarObject, error) {
return t.objectMap[path], nil
}
func (t testBackend) QueryCalendarObjects(ctx context.Context, path string, query *CalendarQuery) ([]CalendarObject, error) {
return nil, nil
}
func TestFindCalendarsColor(t *testing.T) {
h := Handler{Backend: testBackend{calendars: []Calendar{
{Path: "/user/calendars/a/", Color: "#FF2968FF"},
{Path: "/user/calendars/b/"},
}}}
srv := httptest.NewServer(&h)
defer srv.Close()
c, err := NewClient(nil, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
cals, err := c.FindCalendars(context.Background(), "/user/calendars/")
if err != nil {
t.Fatalf("FindCalendars: %v", err)
}
want := map[string]string{
"/user/calendars/a/": "#FF2968FF",
"/user/calendars/b/": "",
}
if len(cals) != len(want) {
t.Fatalf("got %d calendars, want %d", len(cals), len(want))
}
for _, cal := range cals {
if cal.Color != want[cal.Path] {
t.Errorf("%s: Color = %q, want %q", cal.Path, cal.Color, want[cal.Path])
}
}
}
type schedBackend struct {
testBackend
}
func (schedBackend) SyncCalendar(ctx context.Context, path, token string, req *CalendarCompRequest) (*SyncResponse, error) {
switch token {
case "":
return &SyncResponse{SyncToken: "sync-2", Updated: []CalendarObject{syncObject("a"), syncObject("b")}}, nil
case "sync-1":
return &SyncResponse{SyncToken: "sync-2", Updated: []CalendarObject{syncObject("b")}, Deleted: []string{"/user/calendars/cal/gone.ics"}}, nil
}
return nil, ErrInvalidSyncToken
}
func (schedBackend) CalendarUserAddresses(ctx context.Context) ([]string, error) {
return []string{"wilfredo@example.com"}, nil
}
func (schedBackend) PrincipalDisplayName(ctx context.Context) (string, error) {
return "Wilfredo", nil
}
func (schedBackend) ScheduleInboxPath(ctx context.Context) (string, error) {
return "/user/inbox/", nil
}
func (schedBackend) ScheduleOutboxPath(ctx context.Context) (string, error) {
return "/user/outbox/", nil
}
func (schedBackend) FreeBusy(ctx context.Context, req *ical.Calendar) (*ical.Calendar, error) {
reply := ical.NewCalendar()
reply.Props.SetText(ical.PropVersion, "2.0")
reply.Props.SetText(ical.PropProductID, "-//Example//Server//EN")
reply.Props.SetText(ical.PropMethod, "REPLY")
for _, attendee := range req.Children[0].Props.Values(ical.PropAttendee) {
fb := ical.NewComponent(ical.CompFreeBusy)
fb.Props.SetText(ical.PropUID, "4FD3AD926350")
fb.Props.SetDateTime(ical.PropDateTimeStamp, time.Date(2026, 11, 26, 20, 7, 33, 0, time.UTC))
fb.Props.Set(&ical.Prop{Name: ical.PropAttendee, Params: ical.Params{}, Value: attendee.Value})
if strings.HasPrefix(attendee.Value, "mailto:bernard") {
fb.Props.Set(&ical.Prop{Name: ical.PropRequestStatus, Params: ical.Params{}, Value: "3.7;Invalid calendar user"})
}
fb.Props.Set(&ical.Prop{Name: ical.PropFreeBusy, Params: ical.Params{}, Value: "20261127T010000Z/20261127T020000Z"})
reply.Children = append(reply.Children, fb)
}
return reply, nil
}
func syncObject(name string) CalendarObject {
event := ical.NewEvent()
event.Props.SetText(ical.PropUID, name)
event.Props.SetText(ical.PropSummary, "Event "+name)
event.Props.SetDateTime(ical.PropDateTimeStamp, time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC))
event.Props.SetDateTime(ical.PropDateTimeStart, time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC))
cal := ical.NewCalendar()
cal.Props.SetText(ical.PropVersion, "2.0")
cal.Props.SetText(ical.PropProductID, "-//Example//Server//EN")
cal.Children = []*ical.Component{event.Component}
return CalendarObject{Path: "/user/calendars/cal/" + name + ".ics", ETag: "etag-" + name, Data: cal}
}
func serve(t *testing.T, h http.Handler, method, path, contentType, body string) (*http.Response, string) {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
res := w.Result()
data, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return res, string(data)
}
func TestPropFindCalendarCTagSyncToken(t *testing.T) {
h := &Handler{Backend: schedBackend{testBackend{calendars: []Calendar{
{Path: "/user/calendars/cal/", CTag: "ctag-1", SyncToken: "sync-1", Transparent: true},
}}}}
_, resp := serve(t, h, "PROPFIND", "/user/calendars/cal/", "application/xml", `
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/">
<d:prop><cs:getctag/><d:sync-token/><c:schedule-calendar-transp/><d:supported-report-set/></d:prop>
</d:propfind>`)
for _, want := range []string{
`<getctag xmlns="http://calendarserver.org/ns/">ctag-1</getctag>`,
`<sync-token xmlns="DAV:">sync-1</sync-token>`,
`<transparent xmlns="urn:ietf:params:xml:ns:caldav"></transparent>`,
`<sync-collection xmlns="DAV:"></sync-collection>`,
} {
if !strings.Contains(resp, want) {
t.Errorf("missing %s in response:\n%s", want, resp)
}
}
_, resp = serve(t, h, "PROPFIND", "/user/calendars/cal/", "", "")
if strings.Contains(resp, "sync-token") {
t.Errorf("allprop PROPFIND returned sync-token:\n%s", resp)
}
h = &Handler{Backend: testBackend{calendars: []Calendar{{Path: "/user/calendars/cal/"}}}}
_, resp = serve(t, h, "PROPFIND", "/user/calendars/cal/", "", "")
for _, unwanted := range []string{"getctag", "sync-token", "schedule-calendar-transp", "supported-report-set"} {
if strings.Contains(resp, unwanted) {
t.Errorf("unexpected %s in response:\n%s", unwanted, resp)
}
}
}
const syncCollectionRequest = `
<d:sync-collection xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:sync-token>%s</d:sync-token>
<d:sync-level>%s</d:sync-level>
<d:prop><d:getetag/><c:calendar-data/></d:prop>
</d:sync-collection>`
func TestSyncCollection(t *testing.T) {
h := &Handler{Backend: schedBackend{testBackend{calendars: []Calendar{{Path: "/user/calendars/cal/"}}}}}
res, resp := serve(t, h, "REPORT", "/user/calendars/cal/", "application/xml", fmt.Sprintf(syncCollectionRequest, "", "1"))
if res.StatusCode != http.StatusMultiStatus {
t.Fatalf("full sync: status %d:\n%s", res.StatusCode, resp)
}
if ct := res.Header.Get("Content-Type"); ct != "application/xml; charset=utf-8" {
t.Errorf("full sync: Content-Type %q", ct)
}
for _, want := range []string{"/user/calendars/cal/a.ics", "/user/calendars/cal/b.ics", "SUMMARY:Event a", "etag-b", `<sync-token>sync-2</sync-token>`} {
if !strings.Contains(resp, want) {
t.Errorf("full sync: missing %s in response:\n%s", want, resp)
}
}
res, resp = serve(t, h, "REPORT", "/user/calendars/cal/", "application/xml", fmt.Sprintf(syncCollectionRequest, "sync-1", "infinite"))
if res.StatusCode != http.StatusMultiStatus {
t.Fatalf("delta sync: status %d:\n%s", res.StatusCode, resp)
}
if strings.Contains(resp, "a.ics") {
t.Errorf("delta sync: unchanged object returned:\n%s", resp)
}
for _, want := range []string{
"SUMMARY:Event b",
`<response xmlns="DAV:"><href>/user/calendars/cal/gone.ics</href><status>HTTP/1.1 404 Not Found</status></response>`,
`<sync-token>sync-2</sync-token>`,
} {
if !strings.Contains(resp, want) {
t.Errorf("delta sync: missing %s in response:\n%s", want, resp)
}
}
res, resp = serve(t, h, "REPORT", "/user/calendars/cal/", "application/xml", fmt.Sprintf(syncCollectionRequest, "stale", "1"))
if res.StatusCode != http.StatusForbidden || !strings.Contains(resp, "valid-sync-token") {
t.Errorf("unknown token: status %d, want 403 with valid-sync-token:\n%s", res.StatusCode, resp)
}
if ct := res.Header.Get("Content-Type"); ct != "application/xml; charset=utf-8" {
t.Errorf("unknown token: Content-Type %q", ct)
}
noLevel := strings.Replace(fmt.Sprintf(syncCollectionRequest, "", ""), "<d:sync-level></d:sync-level>", "", 1)
res, resp = serve(t, h, "REPORT", "/user/calendars/cal/", "application/xml", noLevel)
if res.StatusCode != http.StatusMultiStatus {
t.Errorf("missing sync-level: status %d, want 207:\n%s", res.StatusCode, resp)
}
for _, path := range []string{"/user/calendars/", "/user/inbox/", "/user/calendars/cal/a.ics"} {
res, resp = serve(t, h, "REPORT", path, "application/xml", fmt.Sprintf(syncCollectionRequest, "", "1"))
if res.StatusCode != http.StatusForbidden {
t.Errorf("%s: status %d, want 403:\n%s", path, res.StatusCode, resp)
}
}
}
func TestPropFindPrincipalScheduling(t *testing.T) {
h := &Handler{Backend: schedBackend{}}
_, resp := serve(t, h, "PROPFIND", "/user/", "application/xml", `
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:prop><c:calendar-user-address-set/><c:schedule-inbox-URL/><c:schedule-outbox-URL/></d:prop>
</d:propfind>`)
for _, want := range []string{
`<calendar-user-address-set xmlns="urn:ietf:params:xml:ns:caldav"><href xmlns="DAV:">mailto:wilfredo@example.com</href></calendar-user-address-set>`,
`<schedule-inbox-URL xmlns="urn:ietf:params:xml:ns:caldav"><href xmlns="DAV:">/user/inbox/</href></schedule-inbox-URL>`,
`<schedule-outbox-URL xmlns="urn:ietf:params:xml:ns:caldav"><href xmlns="DAV:">/user/outbox/</href></schedule-outbox-URL>`,
} {
if !strings.Contains(resp, want) {
t.Errorf("missing %s in response:\n%s", want, resp)
}
}
for path, box := range map[string]string{"/user/inbox/": "schedule-inbox", "/user/outbox/": "schedule-outbox"} {
res, resp := serve(t, h, "PROPFIND", path, "", "")
want := fmt.Sprintf(`<%s xmlns="urn:ietf:params:xml:ns:caldav"></%s>`, box, box)
if res.StatusCode != http.StatusMultiStatus || !strings.Contains(resp, want) || !strings.Contains(resp, "<href>"+path+"</href>") {
t.Errorf("%s: status %d, want resourcetype %s:\n%s", path, res.StatusCode, box, resp)
}
}
_, resp = serve(t, &Handler{Backend: testBackend{}}, "PROPFIND", "/user/", "", "")
if strings.Contains(resp, "schedule-inbox-URL") {
t.Errorf("scheduling property served without PrincipalBackend:\n%s", resp)
}
}
func TestPropFindPrincipalNameAndURL(t *testing.T) {
_, resp := serve(t, &Handler{Backend: schedBackend{}}, "PROPFIND", "/user/", "application/xml", `
<d:propfind xmlns:d="DAV:"><d:prop><d:principal-URL/><d:displayname/></d:prop></d:propfind>`)
for _, want := range []string{
`<principal-URL xmlns="DAV:"><href>/user/</href></principal-URL>`,
`<displayname xmlns="DAV:">Wilfredo</displayname>`,
} {
if !strings.Contains(resp, want) {
t.Errorf("missing %s in response:\n%s", want, resp)
}
}
_, resp = serve(t, &Handler{Backend: testBackend{}}, "PROPFIND", "/user/", "application/xml", `
<d:propfind xmlns:d="DAV:"><d:prop><d:principal-URL/><d:displayname/></d:prop></d:propfind>`)
if !strings.Contains(resp, "principal-URL") || strings.Contains(resp, "Wilfredo") {
t.Errorf("principal-URL is always served, displayname only with PrincipalNameBackend:\n%s", resp)
}
}
func TestOptionsAutoSchedule(t *testing.T) {
res, _ := serve(t, &Handler{Backend: schedBackend{}}, http.MethodOptions, "/user/", "", "")
if dav := res.Header.Get("DAV"); !strings.Contains(dav, "calendar-auto-schedule") {
t.Errorf("DAV header %q lacks calendar-auto-schedule", dav)
}
res, _ = serve(t, &Handler{Backend: testBackend{}}, http.MethodOptions, "/user/", "", "")
if dav := res.Header.Get("DAV"); strings.Contains(dav, "calendar-auto-schedule") {
t.Errorf("DAV header %q has calendar-auto-schedule without FreeBusyBackend", dav)
}
}
const freeBusyRequest = `BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Client//EN
METHOD:REQUEST
BEGIN:VFREEBUSY
UID:4FD3AD926350
DTSTAMP:20261126T200733Z
DTSTART:20261127T000000Z
DTEND:20261128T000000Z
ORGANIZER:mailto:wilfredo@example.com
ATTENDEE:mailto:cyrus@example.com
ATTENDEE:mailto:bernard@example.com
END:VFREEBUSY
END:VCALENDAR
`
func TestFreeBusyPost(t *testing.T) {
h := &Handler{Backend: schedBackend{}}
body := strings.ReplaceAll(freeBusyRequest, "\n", "\r\n")
res, resp := serve(t, h, http.MethodPost, "/user/outbox/", "text/calendar; charset=utf-8", body)
if res.StatusCode != http.StatusOK {
t.Fatalf("status %d:\n%s", res.StatusCode, resp)
}
var sr struct {
Responses []struct {
Recipient string `xml:"recipient>href"`
RequestStatus string `xml:"request-status"`
CalendarData string `xml:"calendar-data"`
} `xml:"response"`
}
if err := xml.Unmarshal([]byte(resp), &sr); err != nil {
t.Fatalf("decode schedule-response: %v\n%s", err, resp)
}
if len(sr.Responses) != 2 {
t.Fatalf("got %d responses, want 2:\n%s", len(sr.Responses), resp)
}
cyrus, bernard := sr.Responses[0], sr.Responses[1]
if cyrus.Recipient != "mailto:cyrus@example.com" || cyrus.RequestStatus != "2.0;Success" {
t.Errorf("cyrus: recipient %q status %q", cyrus.Recipient, cyrus.RequestStatus)
}
if strings.Count(cyrus.CalendarData, "BEGIN:VFREEBUSY") != 1 || !strings.Contains(cyrus.CalendarData, "FREEBUSY:20261127T010000Z/20261127T020000Z") || strings.Contains(cyrus.CalendarData, "bernard") {
t.Errorf("cyrus: calendar-data is not one VFREEBUSY for cyrus:\n%s", cyrus.CalendarData)
}
if bernard.Recipient != "mailto:bernard@example.com" || bernard.RequestStatus != "3.7;Invalid calendar user" {
t.Errorf("bernard: recipient %q status %q", bernard.Recipient, bernard.RequestStatus)
}
if bernard.CalendarData != "" {
t.Errorf("bernard: calendar-data on a failed request-status:\n%s", bernard.CalendarData)
}
res, _ = serve(t, &Handler{Backend: testBackend{}}, http.MethodPost, "/user/outbox/", "text/calendar", body)
if res.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("POST without FreeBusyBackend: status %d, want 405", res.StatusCode)
}
}