caldav: sync-collection only on calendars, and review fixes

- sync-collection answers 403 unless the path is a calendar, and not a
  schedule inbox or outbox. A missing sync-level is level 1.
- DAV:sync-token is not returned for DAV:allprop (RFC 6578 section 4).
- schedule-response carries calendar-data only for a 2.x request-status.
- XML responses with a status other than 200 (207 and errors) set
  Content-Type before WriteHeader, so it is no longer dropped.
- Docs: sync-tokens are URIs; FreeBusyBackend advertises
  calendar-auto-schedule, so the backend owns scheduling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alex Dunmow 2026-11-26 07:55:09 +08:00
parent b044a6de1a
commit 089a0be495
4 changed files with 85 additions and 28 deletions

View File

@ -85,7 +85,8 @@ type Calendar struct {
// http://calendarserver.org/ns/ namespace. It changes whenever any object // http://calendarserver.org/ns/ namespace. It changes whenever any object
// in the calendar changes. // in the calendar changes.
CTag string CTag string
// SyncToken is the value of the DAV:sync-token property (RFC 6578). // SyncToken is the value of the DAV:sync-token property (RFC 6578). It
// must be a URI (RFC 6578 section 6.2).
SyncToken string SyncToken string
// Transparent marks a calendar whose events don't count as busy time. It // Transparent marks a calendar whose events don't count as busy time. It
// is served as CALDAV:schedule-calendar-transp (RFC 6638 section 9.1). // is served as CALDAV:schedule-calendar-transp (RFC 6638 section 9.1).
@ -160,7 +161,8 @@ type SyncQuery struct {
Limit int // <= 0 means unlimited Limit int // <= 0 means unlimited
} }
// SyncResponse contains the returned sync-token for next time // SyncResponse contains the returned sync-token for next time. A server's
// sync-token must be a URI (RFC 6578 section 6.2).
type SyncResponse struct { type SyncResponse struct {
SyncToken string SyncToken string
Updated []CalendarObject Updated []CalendarObject
@ -177,7 +179,7 @@ var ErrInvalidSyncToken = errors.New("caldav: invalid sync token")
type SyncBackend interface { type SyncBackend interface {
// SyncCalendar returns the objects changed and deleted in the calendar at // SyncCalendar returns the objects changed and deleted in the calendar at
// path since token, and the token for the next sync. An empty token asks // path since token, and the token for the next sync. An empty token asks
// for every object. // for every object. Tokens must be URIs (RFC 6578 section 6.2).
SyncCalendar(ctx context.Context, path, token string, req *CalendarCompRequest) (*SyncResponse, error) SyncCalendar(ctx context.Context, path, token string, req *CalendarCompRequest) (*SyncResponse, error)
} }
@ -194,6 +196,10 @@ type PrincipalBackend interface {
// FreeBusyBackend is an optional Backend interface answering free/busy // FreeBusyBackend is an optional Backend interface answering free/busy
// requests POSTed to the schedule outbox (RFC 6638 section 5). The Backend // requests POSTed to the schedule outbox (RFC 6638 section 5). The Backend
// must also implement PrincipalBackend. // must also implement PrincipalBackend.
//
// Implementing it advertises calendar-auto-schedule in the DAV header, so
// clients stop sending invitations themselves: the Backend then owns
// scheduling for every object it stores.
type FreeBusyBackend interface { type FreeBusyBackend interface {
// FreeBusy answers a VFREEBUSY request with one VFREEBUSY per ATTENDEE of // FreeBusy answers a VFREEBUSY request with one VFREEBUSY per ATTENDEE of
// the request, each carrying that ATTENDEE. A VFREEBUSY may carry a // the request, each carrying that ATTENDEE. A VFREEBUSY may carry a

View File

@ -302,10 +302,24 @@ func (h *Handler) handleSyncCollection(r *http.Request, w http.ResponseWriter, s
return internal.HTTPErrorf(http.StatusForbidden, "caldav: sync-collection REPORT not supported") return internal.HTTPErrorf(http.StatusForbidden, "caldav: sync-collection REPORT not supported")
} }
// Calendars hold no nested collections, so infinite is answered as 1. // Calendars hold no nested collections, so infinite is answered as 1.
if sync.SyncLevel != "1" && sync.SyncLevel != "infinite" { if sync.SyncLevel != "" && sync.SyncLevel != "1" && sync.SyncLevel != "infinite" {
return internal.HTTPErrorf(http.StatusBadRequest, "caldav: invalid sync-level %q", sync.SyncLevel) return internal.HTTPErrorf(http.StatusBadRequest, "caldav: invalid sync-level %q", sync.SyncLevel)
} }
b := backend{
Backend: h.Backend,
Prefix: strings.TrimSuffix(h.Prefix, "/"),
}
if b.resourceTypeAtPath(r.URL.Path) != resourceTypeCalendar {
return internal.HTTPErrorf(http.StatusForbidden, "caldav: sync-collection REPORT is only supported on calendars")
}
boxPath, _, err := b.scheduleBox(r.Context(), r.URL.Path)
if err != nil {
return err
} else if boxPath != "" {
return internal.HTTPErrorf(http.StatusForbidden, "caldav: sync-collection REPORT is only supported on calendars")
}
dataReq, err := decodeCalendarDataProp(sync.Prop) dataReq, err := decodeCalendarDataProp(sync.Prop)
if err != nil { if err != nil {
return err return err
@ -324,10 +338,6 @@ func (h *Handler) handleSyncCollection(r *http.Request, w http.ResponseWriter, s
return err return err
} }
b := backend{
Backend: h.Backend,
Prefix: strings.TrimSuffix(h.Prefix, "/"),
}
propfind := internal.PropFind{Prop: sync.Prop} propfind := internal.PropFind{Prop: sync.Prop}
var resps []internal.Response var resps []internal.Response
for _, co := range res.Updated { for _, co := range res.Updated {
@ -409,6 +419,9 @@ func (h *Handler) handlePost(w http.ResponseWriter, r *http.Request) error {
if p := comp.Props.Get(ical.PropRequestStatus); p != nil { if p := comp.Props.Get(ical.PropRequestStatus); p != nil {
status.RequestStatus = p.Value status.RequestStatus = p.Value
} }
if !strings.HasPrefix(status.RequestStatus, "2.") {
break
}
cal := ical.NewCalendar() cal := ical.NewCalendar()
cal.Props = reply.Props cal.Props = reply.Props
cal.Children = []*ical.Component{comp} cal.Children = []*ical.Component{comp}
@ -670,31 +683,37 @@ func (b *backend) propFindUserPrincipal(ctx context.Context, propfind *internal.
return internal.NewPropFindResponse(principalPath, propfind, props) return internal.NewPropFindResponse(principalPath, propfind, props)
} }
// propFindScheduleBox returns nil if reqPath is neither the schedule inbox nor // scheduleBox returns an empty boxPath if reqPath is neither the schedule
// the schedule outbox. // inbox nor the schedule outbox.
func (b *backend) propFindScheduleBox(ctx context.Context, propfind *internal.PropFind, reqPath string) (*internal.Response, error) { func (b *backend) scheduleBox(ctx context.Context, reqPath string) (boxPath string, boxType xml.Name, err error) {
pb, ok := b.Backend.(PrincipalBackend) pb, ok := b.Backend.(PrincipalBackend)
if !ok { if !ok {
return nil, nil return "", xml.Name{}, nil
} }
inboxPath, err := pb.ScheduleInboxPath(ctx) inboxPath, err := pb.ScheduleInboxPath(ctx)
if err != nil { if err != nil {
return nil, err return "", xml.Name{}, err
} }
outboxPath, err := pb.ScheduleOutboxPath(ctx) outboxPath, err := pb.ScheduleOutboxPath(ctx)
if err != nil { if err != nil {
return nil, err return "", xml.Name{}, err
} }
var boxPath string
var boxType xml.Name
switch path.Clean(reqPath) { switch path.Clean(reqPath) {
case path.Clean(inboxPath): case path.Clean(inboxPath):
boxPath, boxType = inboxPath, scheduleInboxName return inboxPath, scheduleInboxName, nil
case path.Clean(outboxPath): case path.Clean(outboxPath):
boxPath, boxType = outboxPath, scheduleOutboxName return outboxPath, scheduleOutboxName, nil
default: }
return nil, nil return "", xml.Name{}, nil
}
// propFindScheduleBox returns nil if reqPath is neither the schedule inbox nor
// the schedule outbox.
func (b *backend) propFindScheduleBox(ctx context.Context, propfind *internal.PropFind, reqPath string) (*internal.Response, error) {
boxPath, boxType, err := b.scheduleBox(ctx, reqPath)
if err != nil || boxPath == "" {
return nil, err
} }
props := map[xml.Name]internal.PropFindFunc{ props := map[xml.Name]internal.PropFindFunc{
@ -782,7 +801,8 @@ func (b *backend) propFindCalendar(ctx context.Context, propfind *internal.PropF
if cal.CTag != "" { if cal.CTag != "" {
props[getCTagName] = internal.PropFindValue(&getCTag{CTag: cal.CTag}) props[getCTagName] = internal.PropFindValue(&getCTag{CTag: cal.CTag})
} }
if cal.SyncToken != "" { // RFC 6578 section 4: DAV:sync-token is not returned for DAV:allprop.
if cal.SyncToken != "" && propfind.AllProp == nil {
props[internal.SyncTokenName] = internal.PropFindValue(&internal.SyncToken{Token: cal.SyncToken}) props[internal.SyncTokenName] = internal.PropFindValue(&internal.SyncToken{Token: cal.SyncToken})
} }
if cal.Transparent { if cal.Transparent {

View File

@ -305,9 +305,8 @@ func (schedBackend) FreeBusy(ctx context.Context, req *ical.Calendar) (*ical.Cal
fb.Props.Set(&ical.Prop{Name: ical.PropAttendee, Params: ical.Params{}, Value: attendee.Value}) fb.Props.Set(&ical.Prop{Name: ical.PropAttendee, Params: ical.Params{}, Value: attendee.Value})
if strings.HasPrefix(attendee.Value, "mailto:bernard") { 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.PropRequestStatus, Params: ical.Params{}, Value: "3.7;Invalid calendar user"})
} else {
fb.Props.Set(&ical.Prop{Name: ical.PropFreeBusy, Params: ical.Params{}, Value: "20261127T010000Z/20261127T020000Z"})
} }
fb.Props.Set(&ical.Prop{Name: ical.PropFreeBusy, Params: ical.Params{}, Value: "20261127T010000Z/20261127T020000Z"})
reply.Children = append(reply.Children, fb) reply.Children = append(reply.Children, fb)
} }
return reply, nil return reply, nil
@ -361,6 +360,11 @@ func TestPropFindCalendarCTagSyncToken(t *testing.T) {
} }
} }
_, 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/"}}}} h = &Handler{Backend: testBackend{calendars: []Calendar{{Path: "/user/calendars/cal/"}}}}
_, resp = serve(t, h, "PROPFIND", "/user/calendars/cal/", "", "") _, resp = serve(t, h, "PROPFIND", "/user/calendars/cal/", "", "")
for _, unwanted := range []string{"getctag", "sync-token", "schedule-calendar-transp", "supported-report-set"} { for _, unwanted := range []string{"getctag", "sync-token", "schedule-calendar-transp", "supported-report-set"} {
@ -384,6 +388,9 @@ func TestSyncCollection(t *testing.T) {
if res.StatusCode != http.StatusMultiStatus { if res.StatusCode != http.StatusMultiStatus {
t.Fatalf("full sync: status %d:\n%s", res.StatusCode, resp) 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>`} { 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) { if !strings.Contains(resp, want) {
t.Errorf("full sync: missing %s in response:\n%s", want, resp) t.Errorf("full sync: missing %s in response:\n%s", want, resp)
@ -411,6 +418,22 @@ func TestSyncCollection(t *testing.T) {
if res.StatusCode != http.StatusForbidden || !strings.Contains(resp, "valid-sync-token") { 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) 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) { func TestPropFindPrincipalScheduling(t *testing.T) {
@ -501,6 +524,9 @@ func TestFreeBusyPost(t *testing.T) {
if bernard.Recipient != "mailto:bernard@example.com" || bernard.RequestStatus != "3.7;Invalid calendar user" { 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) 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) res, _ = serve(t, &Handler{Backend: testBackend{}}, http.MethodPost, "/user/outbox/", "text/calendar", body)
if res.StatusCode != http.StatusMethodNotAllowed { if res.StatusCode != http.StatusMethodNotAllowed {

View File

@ -21,8 +21,7 @@ func ServeError(w http.ResponseWriter, err error) {
var errElt *Error var errElt *Error
if errors.As(err, &errElt) { if errors.As(err, &errElt) {
w.WriteHeader(code) serveXMLStatus(w, code).Encode(errElt)
ServeXML(w).Encode(errElt)
return return
} }
@ -51,15 +50,21 @@ func IsRequestBodyEmpty(r *http.Request) bool {
} }
func ServeXML(w http.ResponseWriter) *xml.Encoder { func ServeXML(w http.ResponseWriter) *xml.Encoder {
w.Header().Add("Content-Type", "application/xml; charset=\"utf-8\"") return serveXMLStatus(w, http.StatusOK)
}
// serveXMLStatus sets Content-Type before WriteHeader, which ignores later
// header changes.
func serveXMLStatus(w http.ResponseWriter, code int) *xml.Encoder {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(code)
w.Write([]byte(xml.Header)) w.Write([]byte(xml.Header))
return xml.NewEncoder(w) return xml.NewEncoder(w)
} }
func ServeMultiStatus(w http.ResponseWriter, ms *MultiStatus) error { func ServeMultiStatus(w http.ResponseWriter, ms *MultiStatus) error {
// TODO: streaming // TODO: streaming
w.WriteHeader(http.StatusMultiStatus) return serveXMLStatus(w, http.StatusMultiStatus).Encode(ms)
return ServeXML(w).Encode(ms)
} }
type Backend interface { type Backend interface {