- Root handler now only serves the welcome page for GET/HEAD; all other methods (e.g. OPTIONS, PROPFIND) return 405 with an Allow header instead of always returning 200, fixing client capability probes and PROPFIND misbehavior. - Mount /files/ properly and cache one xwebdav.Handler per authenticated user so its LockSystem persists across requests instead of being recreated per-request (which broke LOCK/UNLOCK). - Remove the username segment from all DAV URLs (/cal/, /card/, /files/ are now identical for every account; the acting user is always resolved via Basic Auth, never the path). - Reintroduce a fixed literal "home" path segment (/cal/home/, /card/home/) to preserve the URL segment depth that go-webdav's caldav/carddav server relies on to classify resources (principal vs. home-set vs. collection vs. object). Removing the username had collapsed this depth, silently misclassifying requests and returning empty <multistatus> responses (DAVx5 "no resources found"). - Replace the store's single global mutex with per-user sharded locks so different users' requests no longer serialize against each other. - Add auth.NewContext test helper, WebDAV handler tests (per-user isolation, lock persistence across requests), and a concurrent multi-user store test. - Update README and copilot-instructions to document the new URL scheme and the go-webdav path-depth classification quirk. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
293 lines
8.8 KiB
Go
293 lines
8.8 KiB
Go
package carddav
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
|
|
vcard "github.com/emersion/go-vcard"
|
|
"github.com/emersion/go-webdav"
|
|
"github.com/emersion/go-webdav/carddav"
|
|
"github.com/yourusername/caldav-server/internal/auth"
|
|
"github.com/yourusername/caldav-server/internal/config"
|
|
"github.com/yourusername/caldav-server/internal/store"
|
|
)
|
|
|
|
// Backend implements carddav.Backend using a filesystem store.
|
|
type Backend struct {
|
|
cfg *config.Config
|
|
store *store.Store
|
|
logger *slog.Logger
|
|
}
|
|
|
|
// NewBackend creates a CardDAV backend.
|
|
func NewBackend(cfg *config.Config, st *store.Store, logger *slog.Logger) *Backend {
|
|
return &Backend{cfg: cfg, store: st, logger: logger}
|
|
}
|
|
|
|
// NewHandler returns an http.Handler for the /card/ prefix.
|
|
func NewHandler(cfg *config.Config, st *store.Store, logger *slog.Logger) http.Handler {
|
|
b := NewBackend(cfg, st, logger)
|
|
return &carddav.Handler{Backend: b}
|
|
}
|
|
|
|
// -------- carddav.Backend interface --------
|
|
|
|
func (b *Backend) CurrentUserPrincipal(ctx context.Context) (string, error) {
|
|
if auth.FromContext(ctx) == nil {
|
|
return "", webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
// Must resolve to a path served by this same handler (i.e. under
|
|
// /card/) at exactly one path segment of depth — see cardPrincipalPath.
|
|
return cardPrincipalPath(), nil
|
|
}
|
|
|
|
func (b *Backend) AddressBookHomeSetPath(ctx context.Context) (string, error) {
|
|
if auth.FromContext(ctx) == nil {
|
|
return "", webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
return cardHomePath(), nil
|
|
}
|
|
|
|
func (b *Backend) ListAddressBooks(ctx context.Context) ([]carddav.AddressBook, error) {
|
|
p := auth.FromContext(ctx)
|
|
if p == nil {
|
|
return nil, webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
|
|
user, ok := b.cfg.Users[p.Username]
|
|
if !ok {
|
|
return nil, fmt.Errorf("user not found")
|
|
}
|
|
|
|
var books []carddav.AddressBook
|
|
for _, name := range user.AddressBooks {
|
|
if err := b.store.EnsureCollection(p.Username, "card-"+name); err != nil {
|
|
b.logger.Warn("ensuring address book directory", "book", name, "error", err)
|
|
continue
|
|
}
|
|
books = append(books, b.bookMeta(p.Username, name))
|
|
}
|
|
|
|
// Also include extra books that exist on disk
|
|
disk, _ := b.store.ListCollections(p.Username)
|
|
configured := make(map[string]bool)
|
|
for _, n := range user.AddressBooks {
|
|
configured["card-"+n] = true
|
|
}
|
|
for _, dir := range disk {
|
|
if strings.HasPrefix(dir, "card-") && !configured[dir] {
|
|
name := strings.TrimPrefix(dir, "card-")
|
|
books = append(books, b.bookMeta(p.Username, name))
|
|
}
|
|
}
|
|
|
|
return books, nil
|
|
}
|
|
|
|
func (b *Backend) GetAddressBook(ctx context.Context, bookPath string) (*carddav.AddressBook, error) {
|
|
user, name, err := b.parseBookPath(ctx, bookPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := b.store.GetCollection(user, "card-"+name); err != nil {
|
|
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
|
|
}
|
|
book := b.bookMeta(user, name)
|
|
return &book, nil
|
|
}
|
|
|
|
func (b *Backend) GetAddressObject(ctx context.Context, objPath string, req *carddav.AddressDataRequest) (*carddav.AddressObject, error) {
|
|
user, bookName, objID, err := b.parseObjPath(ctx, objPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
data, err := b.store.GetObject(user, "card-"+bookName, objID)
|
|
if err != nil {
|
|
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
|
|
}
|
|
|
|
return b.decodeObject(objPath, data)
|
|
}
|
|
|
|
func (b *Backend) ListAddressObjects(ctx context.Context, bookPath string, req *carddav.AddressDataRequest) ([]carddav.AddressObject, error) {
|
|
user, bookName, err := b.parseBookPath(ctx, bookPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ids, err := b.store.ListObjects(user, "card-"+bookName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var objs []carddav.AddressObject
|
|
for _, id := range ids {
|
|
data, err := b.store.GetObject(user, "card-"+bookName, id)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
obj, err := b.decodeObject(cardObjectPath(bookName, id), data)
|
|
if err != nil {
|
|
b.logger.Warn("decoding vcard object", "id", id, "error", err)
|
|
continue
|
|
}
|
|
objs = append(objs, *obj)
|
|
}
|
|
return objs, nil
|
|
}
|
|
|
|
func (b *Backend) QueryAddressObjects(ctx context.Context, bookPath string, query *carddav.AddressBookQuery) ([]carddav.AddressObject, error) {
|
|
all, err := b.ListAddressObjects(ctx, bookPath, &query.DataRequest)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return carddav.Filter(query, all)
|
|
}
|
|
|
|
func (b *Backend) CreateAddressBook(ctx context.Context, book *carddav.AddressBook) error {
|
|
p := auth.FromContext(ctx)
|
|
if p == nil {
|
|
return webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
name := path.Base(strings.TrimSuffix(book.Path, "/"))
|
|
return b.store.EnsureCollection(p.Username, "card-"+name)
|
|
}
|
|
|
|
func (b *Backend) DeleteAddressBook(ctx context.Context, bookPath string) error {
|
|
user, name, err := b.parseBookPath(ctx, bookPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return b.store.DeleteCollection(user, "card-"+name)
|
|
}
|
|
|
|
func (b *Backend) PutAddressObject(ctx context.Context, objPath string, card vcard.Card, opts *carddav.PutAddressObjectOptions) (*carddav.AddressObject, error) {
|
|
user, bookName, objID, err := b.parseObjPath(ctx, objPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var buf strings.Builder
|
|
enc := vcard.NewEncoder(&buf)
|
|
if err := enc.Encode(card); err != nil {
|
|
return nil, fmt.Errorf("encoding vcard: %w", err)
|
|
}
|
|
|
|
data := []byte(buf.String())
|
|
if err := b.store.PutObject(user, "card-"+bookName, objID, data); err != nil {
|
|
return nil, fmt.Errorf("storing address object: %w", err)
|
|
}
|
|
|
|
return b.decodeObject(objPath, data)
|
|
}
|
|
|
|
func (b *Backend) DeleteAddressObject(ctx context.Context, objPath string) error {
|
|
user, bookName, objID, err := b.parseObjPath(ctx, objPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := b.store.DeleteObject(user, "card-"+bookName, objID); err != nil {
|
|
return webdav.NewHTTPError(http.StatusNotFound, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// -------- helpers --------
|
|
|
|
func (b *Backend) bookMeta(user, name string) carddav.AddressBook {
|
|
return carddav.AddressBook{
|
|
Path: cardHomePath() + name + "/",
|
|
Name: name,
|
|
Description: fmt.Sprintf("%s's %s address book", user, name),
|
|
MaxResourceSize: 10 * 1024 * 1024,
|
|
}
|
|
}
|
|
|
|
func (b *Backend) decodeObject(objPath string, data []byte) (*carddav.AddressObject, error) {
|
|
dec := vcard.NewDecoder(strings.NewReader(string(data)))
|
|
card, err := dec.Decode()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decoding vcard: %w", err)
|
|
}
|
|
|
|
etag := fmt.Sprintf(`"%x"`, hashBytes(data))
|
|
|
|
return &carddav.AddressObject{
|
|
Path: objPath,
|
|
ModTime: time.Now(),
|
|
ContentLength: int64(len(data)),
|
|
ETag: etag,
|
|
Card: card,
|
|
}, nil
|
|
}
|
|
|
|
func (b *Backend) parseBookPath(ctx context.Context, bookPath string) (user, bookName string, err error) {
|
|
p := auth.FromContext(ctx)
|
|
if p == nil {
|
|
return "", "", webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
user = p.Username
|
|
parts := strings.Split(strings.Trim(bookPath, "/"), "/")
|
|
// expected: card/home/<bookname>/
|
|
if len(parts) < 3 {
|
|
return "", "", webdav.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid address book path"))
|
|
}
|
|
bookName = parts[2]
|
|
return user, bookName, nil
|
|
}
|
|
|
|
func (b *Backend) parseObjPath(ctx context.Context, objPath string) (user, bookName, objID string, err error) {
|
|
p := auth.FromContext(ctx)
|
|
if p == nil {
|
|
return "", "", "", webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
|
}
|
|
user = p.Username
|
|
parts := strings.Split(strings.Trim(objPath, "/"), "/")
|
|
// expected: card/home/<bookname>/<objid>
|
|
if len(parts) < 4 {
|
|
return "", "", "", webdav.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid object path"))
|
|
}
|
|
bookName = parts[2]
|
|
objID = path.Base(objPath)
|
|
return user, bookName, objID, nil
|
|
}
|
|
|
|
// cardPrincipalPath, cardHomePath, and cardObjectPath are the same for
|
|
// every user: authorization is resolved from the Basic Auth identity, not
|
|
// from the URL, so no username segment is needed in the path.
|
|
//
|
|
// The fixed "home" segment (in place of a username) is required, not
|
|
// cosmetic: go-webdav's carddav server classifies a request purely by how
|
|
// many path segments it has relative to the handler's mount point — 1
|
|
// segment is treated as the principal, 2 as the addressbook-home-set, 3 as
|
|
// an address book, 4 as an address object. Removing that segment entirely
|
|
// would make the home-set and address-book paths misclassified as
|
|
// principal/home-set respectively, breaking discovery (empty PROPFIND
|
|
// responses).
|
|
func cardPrincipalPath() string {
|
|
return "/card/"
|
|
}
|
|
|
|
func cardHomePath() string {
|
|
return "/card/home/"
|
|
}
|
|
|
|
func cardObjectPath(bookName, objID string) string {
|
|
return fmt.Sprintf("/card/home/%s/%s", bookName, objID)
|
|
}
|
|
|
|
func hashBytes(data []byte) uint64 {
|
|
var h uint64 = 14695981039346656037
|
|
for _, b := range data {
|
|
h ^= uint64(b)
|
|
h *= 1099511628211
|
|
}
|
|
return h
|
|
}
|