Add calendar/address-book sharing backend
Introduce internal/db, a small SQLite-backed store (pure-Go
modernc.org/sqlite, no CGO) at <data_dir>/nidus.db holding
calendar_shares and addressbook_shares grant tables (owner, resource
name, shared-with user, read/write permission). This is the first step
towards user management and a web UI: a real datastore that a future
admin CLI/UI can build on, instead of the static config.yaml.
Wire sharing into the CalDAV/CardDAV backends:
- ListCalendars/ListAddressBooks now also include resources shared with
the requesting user, exposed under the synthetic local name
"<owner>~<name>" in the grantee's own home-set — no separate account,
no data copying, the object still physically lives under the owner's
store.Store namespace.
- All read paths (Get/List/QueryCalendarObjects, address book
equivalents) resolve the synthetic name back to (owner, real name) and
require any share (read or write) to exist.
- All write paths (Put/Delete object, DeleteCalendar/AddressBook)
additionally require a write-permission share; read-only shares get a
403 Forbidden.
- CreateCalendar/CreateAddressBook remain scoped to the acting user's own
namespace — sharing an existing collection is done via ShareCalendar/
ShareAddressBook, not by creating one directly in someone else's name.
Add internal/db/shares_test.go (grant/lookup/update/unshare/list
semantics) and internal/{caldav,carddav}/backend_test.go (shared
calendar/address book visibility, write permission enforcement,
unauthorized access rejection). Update README (features, new "Sharing
calendars and address books" section, project layout, dependencies) and
copilot-instructions.md to document the new package and sharing model.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+112
-27
@@ -14,24 +14,34 @@ import (
|
||||
"github.com/emersion/go-webdav/caldav"
|
||||
"github.com/yourusername/caldav-server/internal/auth"
|
||||
"github.com/yourusername/caldav-server/internal/config"
|
||||
"github.com/yourusername/caldav-server/internal/db"
|
||||
"github.com/yourusername/caldav-server/internal/store"
|
||||
)
|
||||
|
||||
// sharedNameSep separates the owner from the calendar name in the
|
||||
// synthetic name used for calendars shared with another user, e.g.
|
||||
// "alice~work" for alice's "work" calendar as seen by whoever it was
|
||||
// shared with. It must not collide with characters allowed in real
|
||||
// calendar names (validated wherever calendar names are taken as input).
|
||||
const sharedNameSep = "~"
|
||||
|
||||
// Backend implements caldav.Backend using a filesystem store.
|
||||
type Backend struct {
|
||||
cfg *config.Config
|
||||
store *store.Store
|
||||
dbase *db.DB // may be nil if sharing is not configured
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewBackend creates a CalDAV backend.
|
||||
func NewBackend(cfg *config.Config, st *store.Store, logger *slog.Logger) *Backend {
|
||||
return &Backend{cfg: cfg, store: st, logger: logger}
|
||||
// NewBackend creates a CalDAV backend. dbase may be nil, in which case
|
||||
// calendar sharing is disabled (only a user's own calendars are visible).
|
||||
func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) *Backend {
|
||||
return &Backend{cfg: cfg, store: st, dbase: dbase, logger: logger}
|
||||
}
|
||||
|
||||
// NewHandler returns an http.Handler for the /cal/ prefix.
|
||||
func NewHandler(cfg *config.Config, st *store.Store, logger *slog.Logger) http.Handler {
|
||||
b := NewBackend(cfg, st, logger)
|
||||
func NewHandler(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) http.Handler {
|
||||
b := NewBackend(cfg, st, dbase, logger)
|
||||
return &caldav.Handler{Backend: b}
|
||||
}
|
||||
|
||||
@@ -74,7 +84,7 @@ func (b *Backend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error)
|
||||
b.logger.Warn("ensuring calendar directory", "calendar", name, "error", err)
|
||||
continue
|
||||
}
|
||||
cals = append(cals, b.calendarMeta(p.Username, name))
|
||||
cals = append(cals, b.calendarMeta(p.Username, name, name))
|
||||
}
|
||||
|
||||
// Also include any extra calendars that exist on disk but aren't in config
|
||||
@@ -86,7 +96,22 @@ func (b *Backend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error)
|
||||
for _, dir := range disk {
|
||||
if strings.HasPrefix(dir, "cal-") && !configured[dir] {
|
||||
name := strings.TrimPrefix(dir, "cal-")
|
||||
cals = append(cals, b.calendarMeta(p.Username, name))
|
||||
cals = append(cals, b.calendarMeta(p.Username, name, name))
|
||||
}
|
||||
}
|
||||
|
||||
// Include calendars other users have shared with this one.
|
||||
if b.dbase != nil {
|
||||
shares, err := b.dbase.CalendarsSharedWith(p.Username)
|
||||
if err != nil {
|
||||
b.logger.Warn("listing shared calendars", "error", err)
|
||||
}
|
||||
for _, sh := range shares {
|
||||
if _, err := b.store.GetCollection(sh.Owner, "cal-"+sh.CalendarName); err != nil {
|
||||
continue // owner's calendar no longer exists
|
||||
}
|
||||
localName := sharedCalendarName(sh.Owner, sh.CalendarName)
|
||||
cals = append(cals, b.calendarMeta(sh.Owner, sh.CalendarName, localName))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,24 +119,32 @@ func (b *Backend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error)
|
||||
}
|
||||
|
||||
func (b *Backend) GetCalendar(ctx context.Context, calPath string) (*caldav.Calendar, error) {
|
||||
user, name, err := b.parseCalPath(ctx, calPath)
|
||||
requester, localName, err := b.parseCalPath(ctx, calPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := b.store.GetCollection(user, "cal-"+name); err != nil {
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := b.store.GetCollection(owner, "cal-"+realName); err != nil {
|
||||
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
|
||||
}
|
||||
cal := b.calendarMeta(user, name)
|
||||
cal := b.calendarMeta(owner, realName, localName)
|
||||
return &cal, nil
|
||||
}
|
||||
|
||||
func (b *Backend) GetCalendarObject(ctx context.Context, objPath string, req *caldav.CalendarCompRequest) (*caldav.CalendarObject, error) {
|
||||
user, calName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
requester, localName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data, err := b.store.GetObject(user, "cal-"+calName, objID)
|
||||
data, err := b.store.GetObject(owner, "cal-"+realName, objID)
|
||||
if err != nil {
|
||||
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
|
||||
}
|
||||
@@ -120,23 +153,27 @@ func (b *Backend) GetCalendarObject(ctx context.Context, objPath string, req *ca
|
||||
}
|
||||
|
||||
func (b *Backend) ListCalendarObjects(ctx context.Context, calPath string, req *caldav.CalendarCompRequest) ([]caldav.CalendarObject, error) {
|
||||
user, calName, err := b.parseCalPath(ctx, calPath)
|
||||
requester, localName, err := b.parseCalPath(ctx, calPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids, err := b.store.ListObjects(user, "cal-"+calName)
|
||||
ids, err := b.store.ListObjects(owner, "cal-"+realName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var objs []caldav.CalendarObject
|
||||
for _, id := range ids {
|
||||
data, err := b.store.GetObject(user, "cal-"+calName, id)
|
||||
data, err := b.store.GetObject(owner, "cal-"+realName, id)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
obj, err := b.decodeObject(calObjectPath(calName, id), data)
|
||||
obj, err := b.decodeObject(calObjectPath(localName, id), data)
|
||||
if err != nil {
|
||||
b.logger.Warn("decoding calendar object", "id", id, "error", err)
|
||||
continue
|
||||
@@ -160,21 +197,32 @@ func (b *Backend) CreateCalendar(ctx context.Context, calendar *caldav.Calendar)
|
||||
if p == nil {
|
||||
return webdav.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
|
||||
}
|
||||
// Derive collection name from the trailing path segment.
|
||||
// Derive collection name from the trailing path segment. Calendars are
|
||||
// always created under the acting user's own namespace — sharing an
|
||||
// existing calendar is done via ShareCalendar, not by creating one
|
||||
// directly in someone else's name.
|
||||
name := path.Base(strings.TrimSuffix(calendar.Path, "/"))
|
||||
return b.store.EnsureCollection(p.Username, "cal-"+name)
|
||||
}
|
||||
|
||||
func (b *Backend) DeleteCalendar(ctx context.Context, calPath string) error {
|
||||
user, name, err := b.parseCalPath(ctx, calPath)
|
||||
requester, localName, err := b.parseCalPath(ctx, calPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return b.store.DeleteCollection(user, "cal-"+name)
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return b.store.DeleteCollection(owner, "cal-"+realName)
|
||||
}
|
||||
|
||||
func (b *Backend) PutCalendarObject(ctx context.Context, objPath string, calendar *ical.Calendar, opts *caldav.PutCalendarObjectOptions) (*caldav.CalendarObject, error) {
|
||||
user, calName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
requester, localName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -186,7 +234,7 @@ func (b *Backend) PutCalendarObject(ctx context.Context, objPath string, calenda
|
||||
}
|
||||
|
||||
data := []byte(buf.String())
|
||||
if err := b.store.PutObject(user, "cal-"+calName, objID, data); err != nil {
|
||||
if err := b.store.PutObject(owner, "cal-"+realName, objID, data); err != nil {
|
||||
return nil, fmt.Errorf("storing calendar object: %w", err)
|
||||
}
|
||||
|
||||
@@ -194,11 +242,15 @@ func (b *Backend) PutCalendarObject(ctx context.Context, objPath string, calenda
|
||||
}
|
||||
|
||||
func (b *Backend) DeleteCalendarObject(ctx context.Context, objPath string) error {
|
||||
user, calName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
requester, localName, objID, err := b.parseObjPath(ctx, objPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.store.DeleteObject(user, "cal-"+calName, objID); err != nil {
|
||||
owner, realName, _, err := b.resolveCalendar(requester, localName, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.store.DeleteObject(owner, "cal-"+realName, objID); err != nil {
|
||||
return webdav.NewHTTPError(http.StatusNotFound, err)
|
||||
}
|
||||
return nil
|
||||
@@ -206,11 +258,44 @@ func (b *Backend) DeleteCalendarObject(ctx context.Context, objPath string) erro
|
||||
|
||||
// -------- helpers --------
|
||||
|
||||
func (b *Backend) calendarMeta(user, name string) caldav.Calendar {
|
||||
// sharedCalendarName builds the synthetic local name a shared calendar is
|
||||
// exposed under to the user it was shared with.
|
||||
func sharedCalendarName(owner, calName string) string {
|
||||
return owner + sharedNameSep + calName
|
||||
}
|
||||
|
||||
// resolveCalendar maps a local calendar name (as seen in a URL path by
|
||||
// requester) to its real owner and on-disk name, checking permissions
|
||||
// along the way. If localName contains sharedNameSep, it's treated as a
|
||||
// reference to another user's calendar and looked up in the shares table;
|
||||
// otherwise it's assumed to be one of requester's own calendars.
|
||||
//
|
||||
// If requireWrite is true, a share must grant PermWrite or this returns a
|
||||
// 403 Forbidden error. Owners always have full access to their own
|
||||
// calendars.
|
||||
func (b *Backend) resolveCalendar(requester, localName string, requireWrite bool) (owner, realName string, perm db.Permission, err error) {
|
||||
if ownerName, calName, ok := strings.Cut(localName, sharedNameSep); ok {
|
||||
if b.dbase == nil {
|
||||
return "", "", "", webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("sharing not enabled"))
|
||||
}
|
||||
share, err := b.dbase.CalendarShareFor(ownerName, calName, requester)
|
||||
if err != nil {
|
||||
return "", "", "", webdav.NewHTTPError(http.StatusForbidden, fmt.Errorf("calendar not shared with you"))
|
||||
}
|
||||
if requireWrite && share.Permission != db.PermWrite {
|
||||
return "", "", "", webdav.NewHTTPError(http.StatusForbidden, fmt.Errorf("read-only share"))
|
||||
}
|
||||
return ownerName, calName, share.Permission, nil
|
||||
}
|
||||
return requester, localName, db.PermWrite, nil
|
||||
}
|
||||
|
||||
func (b *Backend) calendarMeta(owner, realName, localName string) caldav.Calendar {
|
||||
desc := fmt.Sprintf("%s's %s calendar", owner, realName)
|
||||
return caldav.Calendar{
|
||||
Path: calHomePath() + name + "/",
|
||||
Name: name,
|
||||
Description: fmt.Sprintf("%s's %s calendar", user, name),
|
||||
Path: calHomePath() + localName + "/",
|
||||
Name: localName,
|
||||
Description: desc,
|
||||
SupportedComponentSet: []string{"VEVENT", "VTODO", "VJOURNAL"},
|
||||
MaxResourceSize: 10 * 1024 * 1024, // 10 MiB
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package caldav
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
ical "github.com/emersion/go-ical"
|
||||
"github.com/yourusername/caldav-server/internal/auth"
|
||||
"github.com/yourusername/caldav-server/internal/config"
|
||||
"github.com/yourusername/caldav-server/internal/db"
|
||||
"github.com/yourusername/caldav-server/internal/store"
|
||||
)
|
||||
|
||||
func newTestBackend(t *testing.T) (*Backend, *db.DB) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
|
||||
st, err := store.NewStore(filepath.Join(dir, "data"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
dbase, err := db.Open(filepath.Join(dir, "test.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("db.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { dbase.Close() })
|
||||
|
||||
cfg := &config.Config{
|
||||
Users: map[string]config.UserConfig{
|
||||
"alice": {Calendars: []string{"work"}},
|
||||
"bob": {Calendars: []string{"personal"}},
|
||||
},
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return NewBackend(cfg, st, dbase, logger), dbase
|
||||
}
|
||||
|
||||
func ctxFor(username string) context.Context {
|
||||
return auth.NewContext(context.Background(), &auth.Principal{Username: username})
|
||||
}
|
||||
|
||||
// minimalEvent returns a minimal, valid VCALENDAR/VEVENT for use in tests.
|
||||
func minimalEvent() *ical.Calendar {
|
||||
const raw = "BEGIN:VCALENDAR\r\n" +
|
||||
"VERSION:2.0\r\n" +
|
||||
"PRODID:-//nidus//test//EN\r\n" +
|
||||
"BEGIN:VEVENT\r\n" +
|
||||
"UID:event1@nidus.test\r\n" +
|
||||
"DTSTAMP:20240101T000000Z\r\n" +
|
||||
"DTSTART:20240101T100000Z\r\n" +
|
||||
"SUMMARY:Test Event\r\n" +
|
||||
"END:VEVENT\r\n" +
|
||||
"END:VCALENDAR\r\n"
|
||||
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("minimalEvent: %v", err))
|
||||
}
|
||||
return cal
|
||||
}
|
||||
|
||||
func TestListCalendarsIncludesSharedCalendar(t *testing.T) {
|
||||
b, dbase := newTestBackend(t)
|
||||
|
||||
if err := dbase.ShareCalendar("alice", "work", "bob", db.PermRead); err != nil {
|
||||
t.Fatalf("ShareCalendar: %v", err)
|
||||
}
|
||||
// The shared calendar must exist on disk for it to be listed; normally
|
||||
// this happens when alice's own ListCalendars runs and ensures it.
|
||||
if _, err := b.ListCalendars(ctxFor("alice")); err != nil {
|
||||
t.Fatalf("ListCalendars(alice): %v", err)
|
||||
}
|
||||
|
||||
cals, err := b.ListCalendars(ctxFor("bob"))
|
||||
if err != nil {
|
||||
t.Fatalf("ListCalendars: %v", err)
|
||||
}
|
||||
|
||||
var found bool
|
||||
wantName := sharedCalendarName("alice", "work")
|
||||
for _, c := range cals {
|
||||
if c.Name == wantName {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("shared calendar %q not found in ListCalendars result: %+v", wantName, cals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedCalendarReadOnlyRejectsWrite(t *testing.T) {
|
||||
b, dbase := newTestBackend(t)
|
||||
|
||||
if err := dbase.ShareCalendar("alice", "work", "bob", db.PermRead); err != nil {
|
||||
t.Fatalf("ShareCalendar: %v", err)
|
||||
}
|
||||
|
||||
localName := sharedCalendarName("alice", "work")
|
||||
objPath := calObjectPath(localName, "event1.ics")
|
||||
|
||||
_, err := b.PutCalendarObject(ctxFor("bob"), objPath, minimalEvent(), nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error writing to read-only shared calendar, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedCalendarWriteAllowed(t *testing.T) {
|
||||
b, dbase := newTestBackend(t)
|
||||
|
||||
if err := dbase.ShareCalendar("alice", "work", "bob", db.PermWrite); err != nil {
|
||||
t.Fatalf("ShareCalendar: %v", err)
|
||||
}
|
||||
|
||||
localName := sharedCalendarName("alice", "work")
|
||||
objPath := calObjectPath(localName, "event1.ics")
|
||||
|
||||
if _, err := b.PutCalendarObject(ctxFor("bob"), objPath, minimalEvent(), nil); err != nil {
|
||||
t.Fatalf("PutCalendarObject with write share: %v", err)
|
||||
}
|
||||
|
||||
// The object should now be visible under alice's own calendar too,
|
||||
// since it's stored in her namespace.
|
||||
obj, err := b.GetCalendarObject(ctxFor("alice"), calObjectPath("work", "event1.ics"), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GetCalendarObject as owner: %v", err)
|
||||
}
|
||||
if obj == nil {
|
||||
t.Fatal("expected non-nil object")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnauthorizedUserCannotAccessUnsharedCalendar(t *testing.T) {
|
||||
b, _ := newTestBackend(t)
|
||||
|
||||
localName := sharedCalendarName("alice", "work")
|
||||
_, err := b.GetCalendar(ctxFor("bob"), calHomePath()+localName+"/")
|
||||
if err == nil {
|
||||
t.Fatal("expected error accessing unshared calendar, got nil")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user