Compare commits

..

No commits in common. "f9b91e9a3553d1c766d800deb18fb1d3e2b6b847" and "1901d193ce99382db93e46cffa9223ff6f636508" have entirely different histories.

28 changed files with 37 additions and 765 deletions

View File

@ -1,10 +1,3 @@
# go-webdav (BlissCRM fork)
This is a fork of [emersion/go-webdav](https://github.com/emersion/go-webdav) at v0.8.0, kept for BlissCRM's calendar
server. Its module path is `git.dev.alexdunmow.com/blissful/go-webdav`. BlissCRM adds the CalDAV parts its phones need
(getctag, sync-collection, the user's calendar address, scheduling and free/busy). The licence is unchanged (MIT, see
LICENSE). Upstream changes are merged by hand.
# go-webdav
[![Go Reference](https://pkg.go.dev/badge/github.com/emersion/go-webdav.svg)](https://pkg.go.dev/github.com/emersion/go-webdav)

View File

@ -8,8 +8,8 @@ import (
"time"
"github.com/emersion/go-ical"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
var CapabilityCalendar = webdav.Capability("calendar-access")
@ -69,15 +69,8 @@ type Calendar struct {
Description string
MaxResourceSize int64
SupportedComponentSet []string
// Color is the value of the calendar-color property in the
// http://apple.com/ns/ical/ namespace. That property is not defined by
// CalDAV. The value is a hexadecimal string following the #rrggbb syntax,
// or #rrggbbaa with an alpha channel, as Apple Calendar writes it.
Color string
// ReadOnly reports that the current user may only read this calendar. It
// controls the DAV:current-user-privilege-set reported by the server. The
// client sets it when the server reports a DAV:current-user-privilege-set
// that doesn't grant DAV:write.
// controls the DAV:current-user-privilege-set reported by the server.
ReadOnly bool
}

View File

@ -14,8 +14,8 @@ import (
"time"
"github.com/emersion/go-ical"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
var calendarProps = []xml.Name{
@ -24,8 +24,6 @@ var calendarProps = []xml.Name{
calendarDescriptionName,
maxResourceSizeName,
supportedCalendarComponentSetName,
internal.CurrentUserPrivilegeSetName,
calendarColorName,
}
// DiscoverContextURL performs a DNS-based CardDAV service discovery as
@ -130,11 +128,6 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
return nil, err
}
var color calendarColor
if err := resp.DecodeProp(&color); err != nil && !internal.IsNotFound(err) {
return nil, err
}
var maxResSize maxResourceSize
if err := resp.DecodeProp(&maxResSize); err != nil && !internal.IsNotFound(err) {
return nil, err
@ -148,14 +141,6 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
return nil, err
}
var privSet internal.CurrentUserPrivilegeSet
readOnly := false
if err := resp.DecodeProp(&privSet); err == nil {
readOnly = privSet.ReadOnly()
} else if !internal.IsNotFound(err) {
return nil, err
}
compNames := make([]string, 0, len(supportedCompSet.Comp))
for _, comp := range supportedCompSet.Comp {
compNames = append(compNames, comp.Name)
@ -167,8 +152,6 @@ func decodeCalendar(path string, resp *internal.Response) (*Calendar, error) {
Description: desc.Description,
MaxResourceSize: maxResSize.Size,
SupportedComponentSet: compNames,
Color: color.Color,
ReadOnly: readOnly,
}, nil
}
@ -311,8 +294,7 @@ func decodeCalendarObjectList(ms *internal.MultiStatus) ([]CalendarObject, error
r := bytes.NewReader(calData.Data)
data, err := ical.NewDecoder(r).Decode()
if err != nil {
errs = append(errs, &internal.HrefError{Href: url.URL(resp.Hrefs[0]), Err: err})
continue
return nil, err
}
addrs = append(addrs, CalendarObject{
@ -450,11 +432,8 @@ func (c *Client) GetCalendarObject(ctx context.Context, path string) (*CalendarO
return co, nil
}
// PutCalendarObject stores cal as the calendar object resource at path.
func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.Calendar, opts *PutCalendarObjectOptions) (*CalendarObject, error) {
if opts == nil {
opts = new(PutCalendarObjectOptions)
}
func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.Calendar) (*CalendarObject, error) {
// TODO: add support for If-None-Match and If-Match
// TODO: some servers want a Content-Length header, so we can't stream the
// request body here. See the Radicale issue:
@ -470,12 +449,6 @@ func (c *Client) PutCalendarObject(ctx context.Context, path string, cal *ical.C
return nil, err
}
req.Header.Set("Content-Type", ical.MIMEType)
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {
@ -542,22 +515,6 @@ func (c *Client) SyncCollection(ctx context.Context, path string, query *SyncQue
ModTime: time.Time(getLastMod.LastModified),
ETag: string(getETag.ETag),
}
// Many servers return the calendar-data inline in the sync-collection
// response (the query already requests it via CompRequest); decode it so
// the caller need not follow up with a multiget. When the server omits the
// data, Data is left nil and the caller fetches it as before.
var calData calendarDataResp
if err := resp.DecodeProp(&calData); err == nil {
cal, err := ical.NewDecoder(bytes.NewReader(calData.Data)).Decode()
if err != nil {
return nil, err
}
o.Data = cal
} else if !internal.IsNotFound(err) {
return nil, err
}
ret.Updated = append(ret.Updated, o)
}

View File

@ -1,88 +0,0 @@
package caldav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/emersion/go-ical"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
// minimalCalendar builds a single-VEVENT VCALENDAR valid enough to encode.
func minimalCalendar() *ical.Calendar {
cal := ical.NewCalendar()
cal.Props.SetText(ical.PropVersion, "2.0")
cal.Props.SetText(ical.PropProductID, "-//go-webdav//test//EN")
ev := ical.NewEvent()
ev.Props.SetText(ical.PropUID, "test-uid")
ev.Props.SetDateTime(ical.PropDateTimeStamp, time.Date(2026, 6, 24, 0, 0, 0, 0, time.UTC))
cal.Children = append(cal.Children, ev.Component)
return cal
}
// TestPutCalendarObjectSendsIfMatch verifies the client forwards the
// PutCalendarObjectOptions.IfMatch ETag as an If-Match request header and
// returns the server's new ETag.
func TestPutCalendarObjectSendsIfMatch(t *testing.T) {
var gotIfMatch string
var gotMethod string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
w.Header().Set("ETag", `"new-etag"`)
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutCalendarObjectOptions{IfMatch: webdav.ConditionalMatch(`"old-etag"`)}
co, err := c.PutCalendarObject(context.Background(), "/cal/test-uid.ics", minimalCalendar(), opts)
if err != nil {
t.Fatalf("PutCalendarObject: %v", err)
}
if gotMethod != http.MethodPut {
t.Errorf("method = %q, want PUT", gotMethod)
}
if gotIfMatch != `"old-etag"` {
t.Errorf("If-Match header = %q, want %q", gotIfMatch, `"old-etag"`)
}
if co.ETag != "new-etag" {
t.Errorf("returned ETag = %q, want %q", co.ETag, "new-etag")
}
}
// TestPutCalendarObjectPreconditionFailed verifies a 412 response surfaces as
// an error whose status code consumers can read via webdav.HTTPErrorCode.
func TestPutCalendarObjectPreconditionFailed(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutCalendarObjectOptions{IfMatch: webdav.ConditionalMatch(`"stale"`)}
_, err = c.PutCalendarObject(context.Background(), "/cal/test-uid.ics", minimalCalendar(), opts)
if err == nil {
t.Fatal("PutCalendarObject: want error on 412, got nil")
}
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) {
t.Fatalf("not an HTTP error: %v", err)
}
if httpErr.Code != http.StatusPreconditionFailed {
t.Errorf("status code = %d, want %d", httpErr.Code, http.StatusPreconditionFailed)
}
}

View File

@ -1,78 +0,0 @@
package caldav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
const queryCalendarMalformedResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:response>
<d:href>/cal/good.ics</d:href>
<d:propstat>
<d:prop>
<d:getetag>"good"</d:getetag>
<c:calendar-data>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//go-webdav//test//EN
BEGIN:VEVENT
UID:good
DTSTAMP:20260624T000000Z
END:VEVENT
END:VCALENDAR
</c:calendar-data>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/bad.ics</d:href>
<d:propstat>
<d:prop>
<d:getetag>"bad"</d:getetag>
<c:calendar-data>BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:bad
</c:calendar-data>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestQueryCalendarMalformedObject(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(queryCalendarMalformedResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
objs, err := c.QueryCalendar(context.Background(), "/cal/", &CalendarQuery{
CompFilter: CompFilter{Name: "VCALENDAR"},
})
var hrefErr *internal.HrefError
if !errors.As(err, &hrefErr) {
t.Fatalf("QueryCalendar: want an *internal.HrefError, got %v", err)
}
if hrefErr.Href.Path != "/cal/bad.ics" {
t.Errorf("HrefError.Href = %q, want %q", hrefErr.Href.Path, "/cal/bad.ics")
}
if len(objs) != 1 {
t.Fatalf("got %d objects, want 1", len(objs))
}
if objs[0].Path != "/cal/good.ics" || objs[0].ETag != "good" || objs[0].Data == nil {
t.Errorf("got object %+v, want /cal/good.ics with ETag good and data", objs[0])
}
}

View File

@ -1,99 +0,0 @@
package caldav
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
const findCalendarsReadOnlyResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
<d:response>
<d:href>/cal/read-only/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/write-content/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write-content/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/write/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write/></d:privilege>
<d:privilege><d:write-content/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/cal/unknown/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
<d:propstat>
<d:prop>
<d:current-user-privilege-set/>
</d:prop>
<d:status>HTTP/1.1 404 Not Found</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestFindCalendarsReadOnly(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(findCalendarsReadOnlyResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
cals, err := c.FindCalendars(context.Background(), "/cal/")
if err != nil {
t.Fatalf("FindCalendars: %v", err)
}
want := map[string]bool{
"/cal/read-only/": true,
"/cal/write-content/": true,
"/cal/write/": false,
"/cal/unknown/": false,
}
if len(cals) != len(want) {
t.Fatalf("got %d calendars, want %d", len(cals), len(want))
}
for _, cal := range cals {
if cal.ReadOnly != want[cal.Path] {
t.Errorf("%s: ReadOnly = %v, want %v", cal.Path, cal.ReadOnly, want[cal.Path])
}
}
}

View File

@ -5,7 +5,7 @@ import (
"fmt"
"time"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
const namespace = "urn:ietf:params:xml:ns:caldav"
@ -23,8 +23,6 @@ var (
calendarName = xml.Name{namespace, "calendar"}
calendarDataName = xml.Name{namespace, "calendar-data"}
calendarColorName = xml.Name{"http://apple.com/ns/ical/", "calendar-color"}
)
// https://tools.ietf.org/html/rfc4791#section-6.2.1
@ -43,13 +41,6 @@ type calendarDescription struct {
Description string `xml:",chardata"`
}
// calendar-color is not defined by any RFC. It comes from Apple's
// http://apple.com/ns/ical/ namespace.
type calendarColor struct {
XMLName xml.Name `xml:"http://apple.com/ns/ical/ calendar-color"`
Color string `xml:",chardata"`
}
// https://tools.ietf.org/html/rfc4791#section-5.2.4
type supportedCalendarData struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:caldav supported-calendar-data"`

View File

@ -13,8 +13,8 @@ import (
"time"
"github.com/emersion/go-ical"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
// TODO if nothing more Caldav-specific needs to be added this should be merged with carddav.PutAddressObjectOptions
@ -559,11 +559,6 @@ func (b *backend) propFindCalendar(ctx context.Context, propfind *internal.PropF
Description: cal.Description,
})
}
if cal.Color != "" {
props[calendarColorName] = internal.PropFindValue(&calendarColor{
Color: cal.Color,
})
}
if cal.MaxResourceSize > 0 {
props[maxResourceSizeName] = internal.PropFindValue(&maxResourceSize{
Size: cal.MaxResourceSize,

View File

@ -233,34 +233,3 @@ func (t testBackend) ListCalendarObjects(ctx context.Context, path string, req *
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])
}
}
}

View File

@ -7,8 +7,8 @@ import (
"time"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
var CapabilityAddressBook = webdav.Capability("addressbook")
@ -30,8 +30,6 @@ type AddressBook struct {
SupportedAddressData []AddressDataType
// ReadOnly reports that the current user may only read this address book.
// It controls the DAV:current-user-privilege-set reported by the server.
// The client sets it when the server reports a
// DAV:current-user-privilege-set that doesn't grant DAV:write.
ReadOnly bool
}

View File

@ -9,7 +9,7 @@ import (
"testing"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"github.com/emersion/go-webdav"
)
type testBackend struct {

View File

@ -13,8 +13,8 @@ import (
"time"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
// DiscoverContextURL performs a DNS-based CardDAV service discovery as
@ -84,7 +84,6 @@ func (c *Client) FindAddressBooks(ctx context.Context, addressBookHomeSet string
addressBookDescriptionName,
maxResourceSizeName,
supportedAddressDataName,
internal.CurrentUserPrivilegeSetName,
)
ms, err := c.ic.PropFind(ctx, addressBookHomeSet, internal.DepthOne, propfind)
if err != nil {
@ -131,21 +130,12 @@ func (c *Client) FindAddressBooks(ctx context.Context, addressBookHomeSet string
return nil, err
}
var privSet internal.CurrentUserPrivilegeSet
readOnly := false
if err := resp.DecodeProp(&privSet); err == nil {
readOnly = privSet.ReadOnly()
} else if !internal.IsNotFound(err) {
return nil, err
}
l = append(l, AddressBook{
Path: path,
Name: dispName.Name,
Description: desc.Description,
MaxResourceSize: maxResSize.Size,
SupportedAddressData: decodeSupportedAddressData(&supported),
ReadOnly: readOnly,
})
}
@ -243,8 +233,7 @@ func decodeAddressList(ms *internal.MultiStatus) ([]AddressObject, error) {
r := bytes.NewReader(addrData.Data)
card, err := vcard.NewDecoder(r).Decode()
if err != nil {
errs = append(errs, &internal.HrefError{Href: url.URL(resp.Hrefs[0])})
continue
return nil, err
}
addrs = append(addrs, AddressObject{
@ -395,11 +384,8 @@ func (c *Client) GetAddressObject(ctx context.Context, path string) (*AddressObj
return ao, nil
}
// PutAddressObject stores card as the address object resource at path.
func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.Card, opts *PutAddressObjectOptions) (*AddressObject, error) {
if opts == nil {
opts = new(PutAddressObjectOptions)
}
func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.Card) (*AddressObject, error) {
// TODO: add support for If-None-Match and If-Match
// TODO: some servers want a Content-Length header, so we can't stream the
// request body here. See the Radicale issue:
@ -422,12 +408,6 @@ func (c *Client) PutAddressObject(ctx context.Context, path string, card vcard.C
return nil, err
}
req.Header.Set("Content-Type", vcard.MIMEType)
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {

View File

@ -1,81 +0,0 @@
package carddav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
func minimalCard() vcard.Card {
card := make(vcard.Card)
card.SetValue(vcard.FieldFormattedName, "Alice Gopher")
card.SetValue(vcard.FieldUID, "test-uid")
vcard.ToV4(card)
return card
}
// TestPutAddressObjectSendsIfMatch verifies the client forwards
// PutAddressObjectOptions.IfMatch as an If-Match request header and returns the
// server's new ETag.
func TestPutAddressObjectSendsIfMatch(t *testing.T) {
var gotIfMatch, gotMethod string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
w.Header().Set("ETag", `"new-etag"`)
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutAddressObjectOptions{IfMatch: webdav.ConditionalMatch(`"old-etag"`)}
ao, err := c.PutAddressObject(context.Background(), "/contacts/test-uid.vcf", minimalCard(), opts)
if err != nil {
t.Fatalf("PutAddressObject: %v", err)
}
if gotMethod != http.MethodPut {
t.Errorf("method = %q, want PUT", gotMethod)
}
if gotIfMatch != `"old-etag"` {
t.Errorf("If-Match header = %q, want %q", gotIfMatch, `"old-etag"`)
}
if ao.ETag != "new-etag" {
t.Errorf("returned ETag = %q, want %q", ao.ETag, "new-etag")
}
}
// TestPutAddressObjectPreconditionFailed verifies a 412 response surfaces as an
// error readable via webdav.HTTPErrorCode.
func TestPutAddressObjectPreconditionFailed(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
opts := &PutAddressObjectOptions{IfMatch: webdav.ConditionalMatch(`"stale"`)}
_, err = c.PutAddressObject(context.Background(), "/contacts/test-uid.vcf", minimalCard(), opts)
if err == nil {
t.Fatal("PutAddressObject: want error on 412, got nil")
}
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) {
t.Fatalf("not an HTTP error: %v", err)
}
if httpErr.Code != http.StatusPreconditionFailed {
t.Errorf("status code = %d, want %d", httpErr.Code, http.StatusPreconditionFailed)
}
}

View File

@ -1,69 +0,0 @@
package carddav
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
const findAddressBooksReadOnlyResponse = `<?xml version="1.0" encoding="utf-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
<d:response>
<d:href>/contacts/read-only/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
<d:response>
<d:href>/contacts/all/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>
<d:current-user-privilege-set>
<d:privilege><d:all/></d:privilege>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func TestFindAddressBooksReadOnly(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
w.Write([]byte(findAddressBooksReadOnlyResponse))
}))
defer srv.Close()
c, err := NewClient(http.DefaultClient, srv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
abs, err := c.FindAddressBooks(context.Background(), "/contacts/")
if err != nil {
t.Fatalf("FindAddressBooks: %v", err)
}
want := map[string]bool{
"/contacts/read-only/": true,
"/contacts/all/": false,
}
if len(abs) != len(want) {
t.Fatalf("got %d address books, want %d", len(abs), len(want))
}
for _, ab := range abs {
if ab.ReadOnly != want[ab.Path] {
t.Errorf("%s: ReadOnly = %v, want %v", ab.Path, ab.ReadOnly, want[ab.Path])
}
}
}

View File

@ -4,7 +4,7 @@ import (
"encoding/xml"
"fmt"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
const namespace = "urn:ietf:params:xml:ns:carddav"

View File

@ -12,8 +12,8 @@ import (
"strings"
"github.com/emersion/go-vcard"
"git.dev.alexdunmow.com/blissful/go-webdav"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/internal"
)
type PutAddressObjectOptions struct {

View File

@ -8,7 +8,7 @@ import (
"net/http"
"time"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
// HTTPClient performs HTTP requests. It's implemented by *http.Client.
@ -221,23 +221,12 @@ func (c *Client) Create(ctx context.Context, name string) (io.WriteCloser, error
// RemoveAll deletes a file. If the file is a directory, all of its descendants
// are recursively deleted as well.
func (c *Client) RemoveAll(ctx context.Context, name string, opts *RemoveAllOptions) error {
if opts == nil {
opts = new(RemoveAllOptions)
}
func (c *Client) RemoveAll(ctx context.Context, name string) error {
req, err := c.ic.NewRequest(http.MethodDelete, name, nil)
if err != nil {
return err
}
if opts.IfMatch.IsSet() {
req.Header.Set("If-Match", string(opts.IfMatch))
}
if opts.IfNoneMatch.IsSet() {
req.Header.Set("If-None-Match", string(opts.IfNoneMatch))
}
resp, err := c.ic.Do(req.WithContext(ctx))
if err != nil {
return err

View File

@ -1,78 +0,0 @@
package webdav
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
)
func TestClientRemoveAll(t *testing.T) {
for _, tc := range []struct {
name string
opts *RemoveAllOptions
wantIfMatch string
wantIfNoneMatch string
}{
{name: "nil options"},
{
name: "If-Match",
opts: &RemoveAllOptions{IfMatch: `"abc"`},
wantIfMatch: `"abc"`,
},
{
name: "If-None-Match",
opts: &RemoveAllOptions{IfNoneMatch: "*"},
wantIfNoneMatch: "*",
},
} {
t.Run(tc.name, func(t *testing.T) {
var gotMethod, gotIfMatch, gotIfNoneMatch string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotIfMatch = r.Header.Get("If-Match")
gotIfNoneMatch = r.Header.Get("If-None-Match")
w.WriteHeader(http.StatusNoContent)
}))
defer ts.Close()
c, err := NewClient(nil, ts.URL)
if err != nil {
t.Fatalf("NewClient() = %v", err)
}
if err := c.RemoveAll(context.Background(), "/file", tc.opts); err != nil {
t.Fatalf("RemoveAll() = %v", err)
}
if gotMethod != http.MethodDelete {
t.Errorf("method = %q, want %q", gotMethod, http.MethodDelete)
}
if gotIfMatch != tc.wantIfMatch {
t.Errorf("If-Match = %q, want %q", gotIfMatch, tc.wantIfMatch)
}
if gotIfNoneMatch != tc.wantIfNoneMatch {
t.Errorf("If-None-Match = %q, want %q", gotIfNoneMatch, tc.wantIfNoneMatch)
}
})
}
}
func TestClientRemoveAllPreconditionFailed(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPreconditionFailed)
}))
defer ts.Close()
c, err := NewClient(nil, ts.URL)
if err != nil {
t.Fatalf("NewClient() = %v", err)
}
err = c.RemoveAll(context.Background(), "/file", &RemoveAllOptions{IfMatch: `"abc"`})
var httpErr *internal.HTTPError
if !errors.As(err, &httpErr) || httpErr.Code != http.StatusPreconditionFailed {
t.Fatalf("RemoveAll() = %v, want HTTP error with status %v", err, http.StatusPreconditionFailed)
}
}

View File

@ -7,7 +7,7 @@ import (
"net/http"
"os"
"git.dev.alexdunmow.com/blissful/go-webdav"
"github.com/emersion/go-webdav"
)
func main() {

View File

@ -3,7 +3,7 @@ package webdav
import (
"encoding/xml"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
var (

View File

@ -13,7 +13,7 @@ import (
"path/filepath"
"strings"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
// LocalFileSystem implements FileSystem for a local directory.
@ -252,9 +252,11 @@ func (fs LocalFileSystem) Copy(ctx context.Context, src, dst string, options *Co
// TODO: "Note that an infinite-depth COPY of /A/ into /A/B/ could lead to
// infinite recursion if not handled correctly"
if _, err := os.Stat(srcPath); err != nil {
srcInfo, err := os.Stat(srcPath)
if err != nil {
return false, errFromOS(err)
}
srcPerm := srcInfo.Mode() & os.ModePerm
if _, err := os.Stat(dstPath); err != nil {
if !os.IsNotExist(err) {
@ -275,19 +277,12 @@ func (fs LocalFileSystem) Copy(ctx context.Context, src, dst string, options *Co
return err
}
rel, err := filepath.Rel(srcPath, p)
if err != nil {
return err
}
target := filepath.Join(dstPath, rel)
perm := fi.Mode() & os.ModePerm
if fi.IsDir() {
if err := os.Mkdir(target, perm); err != nil {
if err := os.Mkdir(dstPath, srcPerm); err != nil {
return errFromOS(err)
}
} else {
if err := copyRegularFile(p, target, perm); err != nil {
if err := copyRegularFile(srcPath, dstPath, srcPerm); err != nil {
return err
}
}

View File

@ -1,36 +0,0 @@
package webdav
import (
"context"
"os"
"path/filepath"
"testing"
)
func TestLocalFileSystemCopyDirectory(t *testing.T) {
dir := t.TempDir()
for name, data := range map[string]string{"src/a.txt": "a", "src/sub/b.txt": "b", "dst/old.txt": "old"} {
p := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
}
fs := LocalFileSystem(dir)
if _, err := fs.Copy(context.Background(), "/src", "/dst", &CopyOptions{}); err != nil {
t.Fatalf("Copy() = %v", err)
}
for name, want := range map[string]string{"dst/a.txt": "a", "dst/sub/b.txt": "b"} {
got, err := os.ReadFile(filepath.Join(dir, name))
if err != nil || string(got) != want {
t.Errorf("%s = %q, %v; want %q", name, got, err, want)
}
}
if _, err := os.Stat(filepath.Join(dir, "dst/old.txt")); !os.IsNotExist(err) {
t.Errorf("dst/old.txt still exists after overwrite: %v", err)
}
}

2
go.mod
View File

@ -1,4 +1,4 @@
module git.dev.alexdunmow.com/blissful/go-webdav
module github.com/emersion/go-webdav
go 1.13

View File

@ -461,8 +461,8 @@ type Limit struct {
// https://tools.ietf.org/html/rfc3744#section-5.4
type CurrentUserPrivilegeSet struct {
XMLName xml.Name `xml:"DAV: current-user-privilege-set"`
Privilege []Privilege `xml:"DAV: privilege"`
XMLName xml.Name `xml:"DAV: current-user-privilege-set"`
Privilege []Privilege
}
// https://tools.ietf.org/html/rfc3744#section-5.4
@ -481,15 +481,3 @@ func NewCurrentUserPrivilegeSet(readOnly bool) *CurrentUserPrivilegeSet {
}
return &CurrentUserPrivilegeSet{Privilege: []Privilege{priv}}
}
// ReadOnly reports whether the set doesn't grant DAV:write. The set lists
// aggregate privileges together with the ones they contain (RFC 3744 section
// 5.4), so DAV:write is listed whenever it is granted, also through DAV:all.
func (set *CurrentUserPrivilegeSet) ReadOnly() bool {
for _, priv := range set.Privilege {
if priv.Write != nil {
return false
}
}
return true
}

View File

@ -8,7 +8,6 @@ import (
"mime"
"net/http"
"net/url"
"path"
"strings"
)
@ -285,12 +284,6 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) error {
}
}
// RFC 4918 sections 9.8.5 and 9.9.4: overwriting the destination would
// delete the source.
if path.Clean(r.URL.Path) == path.Clean(dest.Path) {
return HTTPErrorf(http.StatusForbidden, "webdav: source and destination are the same")
}
var created bool
if r.Method == "COPY" {
var recursive bool

View File

@ -9,7 +9,7 @@ import (
"strconv"
"strings"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
// FileSystem is a WebDAV server backend.

View File

@ -1,40 +0,0 @@
package webdav
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestHandlerCopyMoveOntoItself(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "a.txt")
if err := os.WriteFile(p, []byte("a"), 0o644); err != nil {
t.Fatal(err)
}
ts := httptest.NewServer(&Handler{FileSystem: LocalFileSystem(dir)})
defer ts.Close()
for _, method := range []string{"COPY", "MOVE"} {
req, err := http.NewRequest(method, ts.URL+"/a.txt", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Destination", ts.URL+"/a.txt")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("%v onto itself: status = %v, want %v", method, resp.StatusCode, http.StatusForbidden)
}
}
if got, err := os.ReadFile(p); err != nil || string(got) != "a" {
t.Errorf("a.txt = %q, %v; want %q", got, err, "a")
}
}

View File

@ -6,7 +6,7 @@ package webdav
import (
"time"
"git.dev.alexdunmow.com/blissful/go-webdav/internal"
"github.com/emersion/go-webdav/internal"
)
// FileInfo holds information about a WebDAV file.