This commit is contained in:
Lennart J. Kurzweg (Nx2)
2026-03-22 18:48:45 +01:00
parent 41e36a4545
commit 1d99749f72
12 changed files with 567 additions and 216 deletions

View File

@@ -1,6 +1,7 @@
package backend
import (
"slices"
"bytes"
"context"
"errors"
@@ -8,6 +9,7 @@ import (
"log"
"net/http"
"os/exec"
"path"
"strings"
"github.com/emersion/go-ical"
@@ -19,11 +21,21 @@ import (
"nxcaldav/internal/config"
)
// DBBackend implements the caldav.Backend interface using a PostgreSQL database.
// It manages users, calendars, and their events/tasks with built-in support for
// access control, privacy redaction, and aggregate (virtual) calendars.
type DBBackend struct {
pool *pgxpool.Pool
redactionText string
pool *pgxpool.Pool // Connection pool to PostgreSQL
redactionText string // Text used to hide confidential event details (e.g. "[REDACED]")
defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL")
aggregates map[string]*config.Aggregate // In-memory map of path -> virtual calendar definitions
userAggs map[string][]string // In-memory map of user -> list of aggregate paths they can see
}
// NewDBBackend creates a new database-backed CalDAV provider.
// It is called once during main.go startup.
// It initializes the database connection, ensures the tables exist (Schema),
// and synchronizes the config.yaml data into the database tables.
func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) {
pool, err := pgxpool.New(ctx, cfg.Database.URL)
if err != nil {
@@ -33,12 +45,17 @@ func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) {
b := &DBBackend{
pool: pool,
redactionText: cfg.Server.Redaction,
defaultClass: cfg.Server.DefaultClass,
aggregates: make(map[string]*config.Aggregate),
userAggs: make(map[string][]string),
}
// Step 1: Ensure database tables are ready
if err := b.initSchema(ctx); err != nil {
return nil, err
}
// Step 2: Sync users/calendars from YAML to DB
if err := b.syncConfig(ctx, cfg); err != nil {
return nil, err
}
@@ -46,6 +63,9 @@ func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) {
return b, nil
}
// initSchema runs the DDL queries to create the necessary tables if they don't exist.
// We use ON DELETE CASCADE extensively so that deleting a user or calendar
// automatically wipes all related events and access rules in the DB.
func (b *DBBackend) initSchema(ctx context.Context) error {
queries := []string{
`CREATE TABLE IF NOT EXISTS users (
@@ -84,6 +104,10 @@ func (b *DBBackend) initSchema(ctx context.Context) error {
return nil
}
// resolvePassword prepares a password for storage.
// It is called by syncConfig for every user.
// 1. If PasswordCmd is set, it runs the bash command to get the password.
// 2. If the password is not already a bcrypt hash, it hashes it.
func (b *DBBackend) resolvePassword(u config.User) (string, error) {
var raw string
if u.PasswordCmd != "" {
@@ -98,12 +122,11 @@ func (b *DBBackend) resolvePassword(u config.User) (string, error) {
}
// If it already looks like a bcrypt hash, return as is.
// bcrypt hashes usually start with $2a$ or $2b$ or $2y$.
if strings.HasPrefix(raw, "$2") {
return raw, nil
}
// Otherwise, hash it.
// Hash the raw password before DB entry
hash, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.DefaultCost)
if err != nil {
return "", err
@@ -111,6 +134,12 @@ func (b *DBBackend) resolvePassword(u config.User) (string, error) {
return string(hash), nil
}
// syncConfig reconciles the YAML configuration with the PostgreSQL state.
// It is called once at server startup.
// 1. Inserts/Updates all users and their hashed passwords.
// 2. Inserts/Updates all calendars and their access/group rules.
// 3. Builds the in-memory Aggregate maps for fast lookup during requests.
// 4. Performs an 'Orphan Check' to warn the user about DB entries not in config.
func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
tx, err := b.pool.Begin(ctx)
if err != nil {
@@ -120,10 +149,17 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
configUserNames := make(map[string]bool)
configCalendarPaths := make(map[string]bool)
groupMembers := make(map[string][]string)
// Sync Users
b.aggregates = make(map[string]*config.Aggregate)
b.userAggs = make(map[string][]string)
// --- Phase 1: User Sync ---
for _, u := range cfg.Users {
configUserNames[u.Name] = true
for _, g := range u.Groups {
groupMembers[g] = append(groupMembers[g], u.Name)
}
hashed, err := b.resolvePassword(u)
if err != nil {
return err
@@ -138,7 +174,7 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
}
}
// Sync Calendars and Access
// --- Phase 2: Calendar & Access Sync ---
for _, c := range cfg.Calendars {
path := fmt.Sprintf("/%s/calendars/%s/", c.Owner, c.ID)
configCalendarPaths[path] = true
@@ -159,86 +195,118 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
return err
}
// Re-build access rules for this calendar
_, err = tx.Exec(ctx, "DELETE FROM calendar_access WHERE calendar_id = $1", calID)
if err != nil {
return err
}
calendarAccessModes := make(map[string]string)
for _, a := range c.Access {
var tUsers []string
if a.User != "" {
tUsers = append(tUsers, a.User)
}
if a.Group != "" {
tUsers = append(tUsers, groupMembers[a.Group]...)
}
if a.Groups != "" {
tUsers = append(tUsers, groupMembers[a.Groups]...)
}
for _, u := range tUsers {
calendarAccessModes[u] = a.Mode
}
}
for uName, mode := range calendarAccessModes {
var userID int
err := tx.QueryRow(ctx, "SELECT id FROM users WHERE name = $1", a.User).Scan(&userID)
err := tx.QueryRow(ctx, "SELECT id FROM users WHERE name = $1", uName).Scan(&userID)
if err != nil {
return fmt.Errorf("access user %s not found: %v", a.User, err)
return fmt.Errorf("access user %s not found: %v", uName, err)
}
_, err = tx.Exec(ctx, "INSERT INTO calendar_access (calendar_id, user_id, mode) VALUES ($1, $2, $3)",
calID, userID, a.Mode)
calID, userID, mode)
if err != nil {
return err
}
}
}
// Orphaned User Check
// --- Phase 3: Aggregate Setup ---
// Aggregates are virtual, so we only track them in memory for routing.
for _, agg := range cfg.Aggregates {
p_ := fmt.Sprintf("/%s/calendars/%s/", agg.Owner, agg.ID)
if configCalendarPaths[p_] {
return fmt.Errorf("aggregate %s collides with real calendar path", p_)
}
aggCopy := agg
b.aggregates[p_] = &aggCopy
aggAccess := make(map[string]bool)
aggAccess[agg.Owner] = true
for _, a := range agg.Access {
var tUsers []string
if a.User != "" {
tUsers = append(tUsers, a.User)
}
if a.Group != "" {
tUsers = append(tUsers, groupMembers[a.Group]...)
}
if a.Groups != "" {
tUsers = append(tUsers, groupMembers[a.Groups]...)
}
for _, u := range tUsers {
aggAccess[u] = true
}
}
for uName := range aggAccess {
b.userAggs[uName] = append(b.userAggs[uName], p_)
}
}
// --- Phase 4: Orphan Checks ---
// Logs a warning if the DB contains users/calendars no longer in the YAML.
userRows, err := tx.Query(ctx, "SELECT name FROM users")
if err != nil {
return err
}
var dbUsers []string
for userRows.Next() {
var name string
if err := userRows.Scan(&name); err != nil {
return err
if err == nil {
for userRows.Next() {
var name string
if err := userRows.Scan(&name); err == nil && !configUserNames[name] {
log.Printf("WARNING: Orphaned user found in database: %s", name)
}
}
dbUsers = append(dbUsers, name)
userRows.Close()
}
userRows.Close()
for _, name := range dbUsers {
if !configUserNames[name] {
log.Printf("WARNING: Orphaned user found in database: %s (Not in config.yaml)", name)
}
}
// Orphaned Calendar Check
calRows, err := tx.Query(ctx, "SELECT path FROM calendars")
if err != nil {
return err
}
var dbPaths []string
for calRows.Next() {
var p string
if err := calRows.Scan(&p); err != nil {
return err
}
dbPaths = append(dbPaths, p)
}
calRows.Close()
for _, p := range dbPaths {
if !configCalendarPaths[p] {
log.Printf("WARNING: Orphaned calendar found in database: %s (Not in config.yaml)", p)
if err == nil {
for calRows.Next() {
var p string
if err := calRows.Scan(&p); err == nil && !configCalendarPaths[p] {
log.Printf("WARNING: Orphaned calendar found in database: %s", p)
}
}
calRows.Close()
}
return tx.Commit(ctx)
}
// VerifyUser checks Basic Auth credentials against the database.
// It is called by the auth middleware in main.go for every HTTP request.
func (b *DBBackend) VerifyUser(ctx context.Context, username, password string) (bool, error) {
var hash string
err := b.pool.QueryRow(ctx, "SELECT password FROM users WHERE name = $1", username).Scan(&hash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
return false, err
return false, nil // User not found
}
// Securely compare bcrypt hash with the provided plain-text password
err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil, nil
}
// UserPrincipalBackend implementation
// --- UserPrincipalBackend Implementation ---
// CurrentUserPrincipal returns the principal path injected into the context during authentication.
func (b *DBBackend) CurrentUserPrincipal(ctx context.Context) (string, error) {
principal, ok := ctx.Value("principal").(string)
if !ok {
@@ -247,6 +315,7 @@ func (b *DBBackend) CurrentUserPrincipal(ctx context.Context) (string, error) {
return principal, nil
}
// getUsername is a helper to extract the user name from a principal path (e.g. "/alice/").
func (b *DBBackend) getUsername(ctx context.Context) (string, error) {
principal, err := b.CurrentUserPrincipal(ctx)
if err != nil {
@@ -255,6 +324,11 @@ func (b *DBBackend) getUsername(ctx context.Context) (string, error) {
return strings.Trim(principal, "/"), nil
}
// --- Internal Security & Privacy Helpers ---
// checkAccess verifies if the current user has the required permission for a real calendar.
// It returns the internal database ID of the calendar if access is granted.
// It is called before any read (PROPFIND, GET, REPORT) or write (PUT, DELETE) operation.
func (b *DBBackend) checkAccess(ctx context.Context, calendarPath string, requiredMode string) (int, error) {
username, err := b.getUsername(ctx)
if err != nil {
@@ -279,10 +353,12 @@ func (b *DBBackend) checkAccess(ctx context.Context, calendarPath string, requir
return 0, err
}
// Owners always have full access
if ownerName == username {
return calID, nil
}
// Check the calendar_access table for specific permissions
var mode string
err = b.pool.QueryRow(ctx, `
SELECT mode FROM calendar_access
@@ -295,6 +371,7 @@ func (b *DBBackend) checkAccess(ctx context.Context, calendarPath string, requir
return 0, err
}
// Enforce Read-Only mode
if requiredMode == "write" && mode != "read-write" {
return 0, webdav.NewHTTPError(http.StatusForbidden, errors.New("read-only access"))
}
@@ -302,18 +379,20 @@ func (b *DBBackend) checkAccess(ctx context.Context, calendarPath string, requir
return calID, nil
}
func (b *DBBackend) filterCalendar(ctx context.Context, calendarID int, original *ical.Calendar) (*ical.Calendar, error) {
// filterCalendar is the privacy enforcement engine of the server.
// It is called every time a calendar object is retrieved from the database
// for a user who is NOT the owner.
// It applies the following rules based on the 'CLASS' property of an event/task:
// 1. PRIVATE: Removes the object entirely.
// 2. CONFIDENTIAL: Redacts the summary to the configured 'redactionText' while keeping time data.
// 3. PUBLIC: Passes the object through unchanged.
func (b *DBBackend) filterCalendar(ctx context.Context, ownerName string, original *ical.Calendar) (*ical.Calendar, error) {
username, err := b.getUsername(ctx)
if err != nil {
return nil, err
}
var ownerName string
err = b.pool.QueryRow(ctx, "SELECT u.name FROM users u JOIN calendars c ON c.owner_id = u.id WHERE c.id = $1", calendarID).Scan(&ownerName)
if err != nil {
return nil, err
}
// Owners see everything unredacted
if username == ownerName {
return original, nil
}
@@ -327,15 +406,19 @@ func (b *DBBackend) filterCalendar(ctx context.Context, calendarID int, original
continue
}
class := "PUBLIC"
class := b.defaultClass;
log.Printf("class: %s",class)
if prop := child.Props.Get("CLASS"); prop != nil {
class = strings.ToUpper(prop.Value)
log.Printf("class: %s",class)
}
switch class {
case "PRIVATE":
// Don't include private items in the response
continue
case "CONFIDENTIAL":
// Strip all details except time/meta and set a generic summary
redacted := ical.NewComponent(child.Name)
propsToKeep := []string{
"UID", "DTSTAMP", "DTSTART", "DTEND", "DURATION", "CLASS",
@@ -348,20 +431,23 @@ func (b *DBBackend) filterCalendar(ctx context.Context, calendarID int, original
}
redacted.Props.SetText("SUMMARY", b.redactionText)
filtered.Children = append(filtered.Children, redacted)
default:
case "PUBLIC":
log.Printf("pub: %s", child.Name);
filtered.Children = append(filtered.Children, child)
}
}
if len(filtered.Children) == 0 {
return nil, nil
return nil, nil // Entire file is hidden
}
return filtered, nil
}
// CalDAV Backend implementation
// --- CalDAV Backend Implementation ---
// CalendarHomeSetPath returns the root path for a user's calendars (e.g., "/alice/calendars/").
// Called during CalDAV discovery.
func (b *DBBackend) CalendarHomeSetPath(ctx context.Context) (string, error) {
username, err := b.getUsername(ctx)
if err != nil {
@@ -370,12 +456,15 @@ func (b *DBBackend) CalendarHomeSetPath(ctx context.Context) (string, error) {
return fmt.Sprintf("/%s/calendars/", username), nil
}
// ListCalendars returns all calendars (real and virtual) the user has access to.
// Called during PROPFIND on the user's HomeSetPath.
func (b *DBBackend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error) {
username, err := b.getUsername(ctx)
if err != nil {
return nil, err
}
// Find real calendars (Owned or Shared)
rows, err := b.pool.Query(ctx, `
SELECT path, name FROM calendars
WHERE owner_id = (SELECT id FROM users WHERE name = $1)
@@ -395,16 +484,39 @@ func (b *DBBackend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error
cal.SupportedComponentSet = []string{"VEVENT", "VTODO"}
res = append(res, cal)
}
// Add virtual aggregate calendars
for _, p := range b.userAggs[username] {
agg := b.aggregates[p]
res = append(res, caldav.Calendar{
Path: p,
Name: agg.ID,
SupportedComponentSet: []string{"VEVENT", "VTODO"},
})
}
return res, nil
}
func (b *DBBackend) GetCalendar(ctx context.Context, path string) (*caldav.Calendar, error) {
if !strings.HasSuffix(path, "/") {
path += "/"
// GetCalendar retrieves metadata for a specific calendar.
// Called when a client wants to verify a calendar's settings.
func (b *DBBackend) GetCalendar(ctx context.Context, p string) (*caldav.Calendar, error) {
if !strings.HasSuffix(p, "/") {
p += "/"
}
// Check if this is an Aggregate route
if agg, ok := b.aggregates[p]; ok {
return &caldav.Calendar{
Path: p,
Name: agg.ID,
SupportedComponentSet: []string{"VEVENT", "VTODO"},
}, nil
}
// Normal database lookup
var cal caldav.Calendar
err := b.pool.QueryRow(ctx, "SELECT path, name FROM calendars WHERE path = $1", path).Scan(&cal.Path, &cal.Name)
err := b.pool.QueryRow(ctx, "SELECT path, name FROM calendars WHERE path = $1", p).Scan(&cal.Path, &cal.Name)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("calendar not found"))
@@ -415,18 +527,41 @@ func (b *DBBackend) GetCalendar(ctx context.Context, path string) (*caldav.Calen
return &cal, nil
}
// CreateCalendar is disabled because we manage calendars via config.yaml.
func (b *DBBackend) CreateCalendar(ctx context.Context, calendar *caldav.Calendar) error {
return webdav.NewHTTPError(http.StatusForbidden, errors.New("calendar creation only via config"))
}
func (b *DBBackend) ListCalendarObjects(ctx context.Context, path string, req *caldav.CalendarCompRequest) ([]caldav.CalendarObject, error) {
calID, err := b.checkAccess(ctx, path, "read")
// ListCalendarObjects returns the list of all events/tasks in a calendar.
// Called during initial sync (PROPFIND Depth:1) or full-calendar reports.
func (b *DBBackend) ListCalendarObjects(ctx context.Context, p string, req *caldav.CalendarCompRequest) ([]caldav.CalendarObject, error) {
if !strings.HasSuffix(p, "/") {
p += "/"
}
username, _ := b.getUsername(ctx)
log.Printf("[ListCalendarObjects] user=%s path=%s", username, p)
// Route to virtual aggregate logic if needed
if agg, ok := b.aggregates[p]; ok {
// Verify Diane/User can actually see this aggregate
hasAccess := slices.Contains(b.userAggs[username], p)
if !hasAccess {
return nil, webdav.NewHTTPError(http.StatusForbidden, errors.New("access denied to aggregate"))
}
return b.listAggregateObjects(ctx, p, agg)
}
// Normal calendar logic
calID, err := b.checkAccess(ctx, p, "read")
if err != nil {
return nil, err
}
if !strings.HasSuffix(path, "/") {
path += "/"
var ownerName string
err = b.pool.QueryRow(ctx, "SELECT u.name FROM users u JOIN calendars c ON c.owner_id = u.id WHERE c.id = $1", calID).Scan(&ownerName)
if err != nil {
return nil, err
}
rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID)
@@ -445,14 +580,12 @@ func (b *DBBackend) ListCalendarObjects(ctx context.Context, path string, req *c
calData, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode()
if err != nil {
return nil, err
continue
}
filteredData, err := b.filterCalendar(ctx, calID, calData)
if err != nil {
return nil, err
}
if filteredData == nil {
// Apply privacy filters (Private/Confidential)
filteredData, err := b.filterCalendar(ctx, ownerName, calData)
if err != nil || filteredData == nil {
continue
}
obj.Data = filteredData
@@ -461,21 +594,157 @@ func (b *DBBackend) ListCalendarObjects(ctx context.Context, path string, req *c
return res, nil
}
func (b *DBBackend) GetCalendarObject(ctx context.Context, path string, req *caldav.CalendarCompRequest) (*caldav.CalendarObject, error) {
lastSlash := strings.LastIndex(path, "/")
if lastSlash == -1 {
return nil, webdav.NewHTTPError(http.StatusBadRequest, errors.New("invalid object path"))
}
parentPath := path[:lastSlash+1]
// listAggregateObjects merges multiple real calendars into one virtual view.
// It rewrites paths so the client thinks items are in the virtual directory.
func (b *DBBackend) listAggregateObjects(ctx context.Context, aggPath string, agg *config.Aggregate) ([]caldav.CalendarObject, error) {
var res []caldav.CalendarObject
for _, sourceID := range agg.Sources {
sourcePath := fmt.Sprintf("/%s/calendars/%s/", agg.Owner, sourceID)
var calID int
var ownerName string
err := b.pool.QueryRow(ctx, `
SELECT c.id, u.name FROM calendars c
JOIN users u ON c.owner_id = u.id
WHERE c.path = $1`, sourcePath).Scan(&calID, &ownerName)
if err != nil {
continue
}
calID, err := b.checkAccess(ctx, parentPath, "read")
rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID)
if err != nil {
continue
}
for rows.Next() {
var obj caldav.CalendarObject
var dataStr string
if err := rows.Scan(&obj.Path, &dataStr, &obj.ETag); err != nil {
rows.Close()
return nil, err
}
calData, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode()
if err != nil {
continue
}
// Apply Privacy rules for the aggregate viewer
filtered, err := b.filterCalendar(ctx, ownerName, calData)
if err != nil || filtered == nil {
continue
}
// Prepend source name so Diane knows this is a "[school]" event
for _, child := range filtered.Children {
if child.Name == "VEVENT" || child.Name == "VTODO" {
summary := child.Props.Get("SUMMARY")
val := ""
if summary != nil {
val = summary.Value
}
child.Props.SetText("SUMMARY", fmt.Sprintf("[%s] %s", sourceID, val))
}
}
// Virtualize the path so Thunderbird doesn't reject the file
fileName := path.Base(obj.Path)
obj.Path = aggPath + sourceID + "__" + fileName
obj.Data = filtered
res = append(res, obj)
}
rows.Close()
}
return res, nil
}
// GetCalendarObject retrieves a single event or task file.
// Called during GET, multiget REPORT, or when clicking an event in the client.
func (b *DBBackend) GetCalendarObject(ctx context.Context, p string, req *caldav.CalendarCompRequest) (*caldav.CalendarObject, error) {
username, _ := b.getUsername(ctx)
log.Printf("[GetCalendarObject] user=%s path=%s", username, p)
dirPath := path.Dir(p) + "/"
fileName := path.Base(p)
// Step 1: Check if this is a request for a virtual item in an aggregate
if agg, ok := b.aggregates[dirPath]; ok {
hasAccess := slices.Contains(b.userAggs[username], dirPath)
if !hasAccess {
return nil, webdav.NewHTTPError(http.StatusForbidden, errors.New("access denied to aggregate"))
}
// Parse the virtual path back to real source
parts := strings.SplitN(fileName, "__", 2)
if len(parts) < 2 {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("invalid aggregate item path"))
}
sourceID := parts[0]
realFileName := parts[1]
sourcePath := fmt.Sprintf("/%s/calendars/%s/", agg.Owner, sourceID)
var calID int
var ownerName string
err := b.pool.QueryRow(ctx, "SELECT c.id, u.name FROM calendars c JOIN users u ON c.owner_id = u.id WHERE c.path = $1", sourcePath).Scan(&calID, &ownerName)
if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("source calendar not found"))
}
var obj caldav.CalendarObject
var dataStr string
realObjPath := sourcePath + realFileName
err = b.pool.QueryRow(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1 AND path = $2", calID, realObjPath).Scan(&obj.Path, &dataStr, &obj.ETag)
if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("item not found in source"))
}
calData, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode()
if err != nil {
return nil, err
}
filteredData, err := b.filterCalendar(ctx, ownerName, calData)
if err != nil || filteredData == nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("item filtered out"))
}
// Re-apply labels for the virtual view
for _, child := range filteredData.Children {
if child.Name == "VEVENT" || child.Name == "VTODO" {
summary := child.Props.Get("SUMMARY")
val := ""
if summary != nil {
val = summary.Value
}
child.Props.SetText("SUMMARY", fmt.Sprintf("[%s] %s", sourceID, val))
}
}
obj.Data = filteredData
obj.Path = p
return &obj, nil
}
// Step 2: Handle normal real calendar objects
if !strings.HasSuffix(dirPath, "/") {
dirPath += "/"
}
calID, err := b.checkAccess(ctx, dirPath, "read")
if err != nil {
return nil, err
}
var ownerName string
err = b.pool.QueryRow(ctx, "SELECT u.name FROM users u JOIN calendars c ON c.owner_id = u.id WHERE c.id = $1", calID).Scan(&ownerName)
if err != nil {
return nil, err
}
var obj caldav.CalendarObject
var dataStr string
err = b.pool.QueryRow(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1 AND path = $2", calID, path).Scan(&obj.Path, &dataStr, &obj.ETag)
err = b.pool.QueryRow(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1 AND path = $2", calID, p).Scan(&obj.Path, &dataStr, &obj.ETag)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("calendar object not found"))
@@ -488,25 +757,26 @@ func (b *DBBackend) GetCalendarObject(ctx context.Context, path string, req *cal
return nil, err
}
filteredData, err := b.filterCalendar(ctx, calID, calData)
if err != nil {
return nil, err
}
if filteredData == nil {
// Apply privacy filtering
filteredData, err := b.filterCalendar(ctx, ownerName, calData)
if err != nil || filteredData == nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, errors.New("calendar object not found"))
}
obj.Data = filteredData
return &obj, nil
}
func (b *DBBackend) PutCalendarObject(ctx context.Context, path string, calendar *ical.Calendar, opts *caldav.PutCalendarObjectOptions) (*caldav.CalendarObject, error) {
lastSlash := strings.LastIndex(path, "/")
if lastSlash == -1 {
return nil, webdav.NewHTTPError(http.StatusBadRequest, errors.New("invalid object path"))
// PutCalendarObject saves or updates an event/task.
// Called during PUT requests when a user saves a change in their calendar app.
func (b *DBBackend) PutCalendarObject(ctx context.Context, p string, calendar *ical.Calendar, opts *caldav.PutCalendarObjectOptions) (*caldav.CalendarObject, error) {
dirPath := path.Dir(p) + "/"
// Aggregates are read-only
if _, ok := b.aggregates[dirPath]; ok {
return nil, webdav.NewHTTPError(http.StatusForbidden, errors.New("aggregates are read-only"))
}
parentPath := path[:lastSlash+1]
calID, err := b.checkAccess(ctx, parentPath, "write")
calID, err := b.checkAccess(ctx, dirPath, "write")
if err != nil {
return nil, err
}
@@ -518,34 +788,36 @@ func (b *DBBackend) PutCalendarObject(ctx context.Context, path string, calendar
dataStr := buf.String()
etag := fmt.Sprintf(`"%d"`, len(calendar.Events()))
// Use Upsert logic to handle both creation and updates
_, err = b.pool.Exec(ctx, `
INSERT INTO calendar_objects (calendar_id, path, data, etag) VALUES ($1, $2, $3, $4)
ON CONFLICT (calendar_id, path) DO UPDATE SET data = EXCLUDED.data, etag = EXCLUDED.etag`,
calID, path, dataStr, etag)
calID, p, dataStr, etag)
if err != nil {
return nil, err
}
return &caldav.CalendarObject{
Path: path,
Path: p,
Data: calendar,
ETag: etag,
}, nil
}
func (b *DBBackend) DeleteCalendarObject(ctx context.Context, path string) error {
lastSlash := strings.LastIndex(path, "/")
if lastSlash == -1 {
return webdav.NewHTTPError(http.StatusBadRequest, errors.New("invalid object path"))
// DeleteCalendarObject removes an event or task.
// Called during DELETE requests.
func (b *DBBackend) DeleteCalendarObject(ctx context.Context, p string) error {
dirPath := path.Dir(p) + "/"
if _, ok := b.aggregates[dirPath]; ok {
return webdav.NewHTTPError(http.StatusForbidden, errors.New("aggregates are read-only"))
}
parentPath := path[:lastSlash+1]
calID, err := b.checkAccess(ctx, parentPath, "write")
calID, err := b.checkAccess(ctx, dirPath, "write")
if err != nil {
return err
}
commandTag, err := b.pool.Exec(ctx, "DELETE FROM calendar_objects WHERE calendar_id = $1 AND path = $2", calID, path)
commandTag, err := b.pool.Exec(ctx, "DELETE FROM calendar_objects WHERE calendar_id = $1 AND path = $2", calID, p)
if err != nil {
return err
}
@@ -555,6 +827,11 @@ func (b *DBBackend) DeleteCalendarObject(ctx context.Context, path string) error
return nil
}
func (b *DBBackend) QueryCalendarObjects(ctx context.Context, path string, query *caldav.CalendarQuery) ([]caldav.CalendarObject, error) {
return b.ListCalendarObjects(ctx, path, nil)
// QueryCalendarObjects filters items based on a CalDAV query (e.g. time range).
// Currently, it just lists all objects and lets the client filter, but
// we use it to enforce privacy rules for the initial report.
func (b *DBBackend) QueryCalendarObjects(ctx context.Context, path_ string, query *caldav.CalendarQuery) ([]caldav.CalendarObject, error) {
username, _ := b.getUsername(ctx)
log.Printf("[QueryCalendarObjects] user=%s path=%s", username, path_)
return b.ListCalendarObjects(ctx, path_, nil)
}

View File

@@ -32,6 +32,13 @@ func NewMemBackend(cfg *config.Config) *MemBackend {
calendarAccess: make(map[string]map[string]string),
}
groupMembers := make(map[string][]string)
for _, u := range cfg.Users {
for _, g := range u.Groups {
groupMembers[g] = append(groupMembers[g], u.Name)
}
}
for _, c := range cfg.Calendars {
path := fmt.Sprintf("/%s/calendars/%s/", c.Owner, c.ID)
cal := &caldav.Calendar{
@@ -45,8 +52,22 @@ func NewMemBackend(cfg *config.Config) *MemBackend {
accessMap := make(map[string]string)
for _, a := range c.Access {
accessMap[a.User] = a.Mode
b.userCalendars[a.User] = append(b.userCalendars[a.User], path)
var tUsers []string
if a.User != "" {
tUsers = append(tUsers, a.User)
}
if a.Group != "" {
tUsers = append(tUsers, groupMembers[a.Group]...)
}
if a.Groups != "" {
tUsers = append(tUsers, groupMembers[a.Groups]...)
}
for _, u := range tUsers {
if _, exists := accessMap[u]; !exists {
b.userCalendars[u] = append(b.userCalendars[u], path)
}
accessMap[u] = a.Mode
}
}
b.calendarAccess[path] = accessMap
}
@@ -121,7 +142,7 @@ func (b *MemBackend) filterCalendar(ctx context.Context, calendarPath string, or
continue
}
class := "PUBLIC"
class := "CONFIDENTIAL"
if prop := child.Props.Get("CLASS"); prop != nil {
class = strings.ToUpper(prop.Value)
}

View File

@@ -2,13 +2,16 @@ package config
import (
"os"
"slices"
"gopkg.in/yaml.v3"
)
type Access struct {
User string `yaml:"user"`
Mode string `yaml:"mode"` // "read-only" or "read-write"
User string `yaml:"user,omitempty"`
Group string `yaml:"group,omitempty"`
Groups string `yaml:"groups,omitempty"`
Mode string `yaml:"mode"` // "read-only" or "read-write"
}
type Calendar struct {
@@ -17,10 +20,18 @@ type Calendar struct {
Access []Access `yaml:"access,omitempty"`
}
type Aggregate struct {
ID string `yaml:"id"`
Owner string `yaml:"owner"`
Sources []string `yaml:"sources"` // Calendar IDs
Access []Access `yaml:"access,omitempty"`
}
type User struct {
Name string `yaml:"name"`
Password string `yaml:"password"`
PasswordCmd string `yaml:"password_cmd"`
Name string `yaml:"name"`
Password string `yaml:"password"`
PasswordCmd string `yaml:"password_cmd"`
Groups []string `yaml:"groups,omitempty"`
}
type DatabaseConfig struct {
@@ -28,16 +39,18 @@ type DatabaseConfig struct {
}
type ServerConfig struct {
BindAddress string `yaml:"bind_address"`
PublicURL string `yaml:"public_url"`
Redaction string `yaml:"redaction_text"`
BindAddress string `yaml:"bind_address"`
PublicURL string `yaml:"public_url"`
Redaction string `yaml:"redaction_text"`
DefaultClass string `yaml:"default_class"`
}
type Config struct {
Server ServerConfig `yaml:"server"`
Database DatabaseConfig `yaml:"database"`
Users []User `yaml:"users"`
Calendars []Calendar `yaml:"calendars"`
Server ServerConfig `yaml:"server"`
Database DatabaseConfig `yaml:"database"`
Users []User `yaml:"users"`
Calendars []Calendar `yaml:"calendars"`
Aggregates []Aggregate `yaml:"aggregates"`
}
func Load(path string) (*Config, error) {
@@ -53,10 +66,17 @@ func Load(path string) (*Config, error) {
return nil, err
}
cfg.checkConfig()
cfg.setDefaults()
return &cfg, nil
}
func (c *Config) checkConfig() {
if !(slices.Contains([]string{"PUBLIC", "PRIVATE", "CONFIDENTIAL"}, c.Server.DefaultClass)) {
panic("Invaldi Config, default_class")
}
}
func (c *Config) setDefaults() {
if c.Server.BindAddress == "" {
c.Server.BindAddress = ":8080"
@@ -64,6 +84,9 @@ func (c *Config) setDefaults() {
if c.Server.Redaction == "" {
c.Server.Redaction = "Busy"
}
if c.Server.DefaultClass == "" {
c.Server.DefaultClass = "CONFIDENTIAL"
}
if c.Database.URL == "" {
c.Database.URL = "postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable"
}