This commit is contained in:
Lennart J. Kurzweg (Nx2)
2026-03-23 14:07:48 +01:00
parent d0b67cfbbb
commit d55fff9f4a
4 changed files with 121 additions and 37 deletions

View File

@@ -1,6 +1,6 @@
server: server:
bind_address: "0.0.0.0:8080" bind_address: "0.0.0.0:14243"
public_url: "http://localhost:8080" public_url: "http://nxc.nx2.site"
redaction_text: "[-]" redaction_text: "[-]"
default_class: "CONFIDENTIAL" default_class: "CONFIDENTIAL"
@@ -12,30 +12,24 @@ users:
password: "123" password: "123"
groups: groups:
- family - family
- klosterberg
- parent - parent
- name: "diane" - name: "diane"
password: "123" password: "123"
groups: groups:
- family - family
- klosterberg
- parent - parent
- name: "georg" - name: "georg"
password: "123" password: "123"
groups: groups:
- family - family
- kids
- name: "lennart" - name: "lennart"
password: "123" password: "123"
groups: groups:
- family - family
- kids
- name: "tessa" - name: "tessa"
password: "123" password: "123"
groups: groups:
- family - family
- kids
- klosterberg
- name: "testuser" - name: "testuser"
password: "123" password: "123"
- name: "shared" - name: "shared"
@@ -62,3 +56,4 @@ aggregates:
access: access:
- group: "family" - group: "family"
mode: "read-only" mode: "read-only"
- ics: "future-only"

View File

@@ -11,6 +11,7 @@ import (
"os/exec" "os/exec"
"path" "path"
"strings" "strings"
"time"
"github.com/emersion/go-ical" "github.com/emersion/go-ical"
"github.com/emersion/go-webdav" "github.com/emersion/go-webdav"
@@ -21,6 +22,11 @@ import (
"nxcaldav/internal/config" "nxcaldav/internal/config"
) )
type publicInfo struct {
InternalPath string
Mode string // e.g., "future-only"
}
// DBBackend implements the caldav.Backend interface using a PostgreSQL database. // DBBackend implements the caldav.Backend interface using a PostgreSQL database.
// It manages users, calendars, and their events/tasks with built-in support for // It manages users, calendars, and their events/tasks with built-in support for
// access control, privacy redaction, and aggregate (virtual) calendars. // access control, privacy redaction, and aggregate (virtual) calendars.
@@ -30,6 +36,7 @@ type DBBackend struct {
defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL") defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL")
aggregates map[string]*config.Aggregate // In-memory map of path -> virtual calendar definitions 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 userAggs map[string][]string // In-memory map of user -> list of aggregate paths they can see
publicAccess map[string]publicInfo // In-memory map of public path -> internal info
} }
// NewDBBackend creates a new database-backed CalDAV provider. // NewDBBackend creates a new database-backed CalDAV provider.
@@ -48,6 +55,7 @@ func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) {
defaultClass: cfg.Server.DefaultClass, defaultClass: cfg.Server.DefaultClass,
aggregates: make(map[string]*config.Aggregate), aggregates: make(map[string]*config.Aggregate),
userAggs: make(map[string][]string), userAggs: make(map[string][]string),
publicAccess: make(map[string]publicInfo),
} }
// Step 1: Ensure database tables are ready // Step 1: Ensure database tables are ready
@@ -153,6 +161,7 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
b.aggregates = make(map[string]*config.Aggregate) b.aggregates = make(map[string]*config.Aggregate)
b.userAggs = make(map[string][]string) b.userAggs = make(map[string][]string)
b.publicAccess = make(map[string]publicInfo)
// --- Phase 1: User Sync --- // --- Phase 1: User Sync ---
for _, u := range cfg.Users { for _, u := range cfg.Users {
@@ -230,6 +239,17 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
return err return err
} }
} }
// Check for public access (ICS)
for _, a := range c.Access {
if a.ICS != "" {
pubPath := fmt.Sprintf("/public/%s/%s.ics", c.Owner, c.ID)
b.publicAccess[pubPath] = publicInfo{
InternalPath: path,
Mode: a.ICS,
}
}
}
} }
// --- Phase 3: Aggregate Setup --- // --- Phase 3: Aggregate Setup ---
@@ -246,6 +266,14 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error {
aggAccess := make(map[string]bool) aggAccess := make(map[string]bool)
aggAccess[agg.Owner] = true aggAccess[agg.Owner] = true
for _, a := range agg.Access { for _, a := range agg.Access {
if a.ICS != "" {
pubPath := fmt.Sprintf("/public/%s/%s.ics", agg.Owner, agg.ID)
b.publicAccess[pubPath] = publicInfo{
InternalPath: p_,
Mode: a.ICS,
}
}
var tUsers []string var tUsers []string
if a.User != "" { if a.User != "" {
tUsers = append(tUsers, a.User) tUsers = append(tUsers, a.User)
@@ -319,7 +347,7 @@ func (b *DBBackend) CurrentUserPrincipal(ctx context.Context) (string, error) {
func (b *DBBackend) getUsername(ctx context.Context) (string, error) { func (b *DBBackend) getUsername(ctx context.Context) (string, error) {
principal, err := b.CurrentUserPrincipal(ctx) principal, err := b.CurrentUserPrincipal(ctx)
if err != nil { if err != nil {
return "", err return "", nil // No principal means anonymous/public
} }
return strings.Trim(principal, "/"), nil return strings.Trim(principal, "/"), nil
} }
@@ -441,6 +469,76 @@ func (b *DBBackend) filterCalendar(ctx context.Context, ownerName string, origin
return filtered, nil return filtered, nil
} }
// ServePublicICS handles public GET requests for .ics files.
// It applies privacy redaction and optional time-range filtering (e.g. "future-only").
func (b *DBBackend) ServePublicICS(w http.ResponseWriter, r *http.Request) {
info, ok := b.publicAccess[r.URL.Path]
if !ok {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
// For public access, we use an empty context (no principal)
// which ensures filterCalendar applies full redaction.
ctx := r.Context()
var objects []caldav.CalendarObject
var err error
if agg, ok := b.aggregates[info.InternalPath]; ok {
objects, err = b.listAggregateObjects(ctx, info.InternalPath, agg)
} else {
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`, info.InternalPath).Scan(&calID, &ownerName)
if err == nil {
objects, err = b.listCalendarObjectsRaw(ctx, calID, ownerName)
}
}
if err != nil {
log.Printf("Error fetching public objects: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
outCal := ical.NewCalendar()
outCal.Props.SetText("PRODID", "-//nxcaldav//Public ICS//EN")
outCal.Props.SetText("VERSION", "2.0")
now := time.Now()
for _, obj := range objects {
for _, child := range obj.Data.Children {
if child.Name != "VEVENT" && child.Name != "VTODO" {
continue
}
if info.Mode == "future-only" {
var end time.Time
if prop := child.Props.Get("DTEND"); prop != nil {
end, _ = prop.DateTime(time.UTC)
} else if prop := child.Props.Get("DTSTART"); prop != nil {
end, _ = prop.DateTime(time.UTC)
}
if !end.IsZero() && end.Before(now) {
continue
}
}
outCal.Children = append(outCal.Children, child)
}
}
w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
if err := ical.NewEncoder(w).Encode(outCal); err != nil {
log.Printf("Error encoding public ICS: %v", err)
}
}
// --- CalDAV Backend Implementation --- // --- CalDAV Backend Implementation ---
// CalendarHomeSetPath returns the root path for a user's calendars (e.g., "/alice/calendars/"). // CalendarHomeSetPath returns the root path for a user's calendars (e.g., "/alice/calendars/").
@@ -561,6 +659,10 @@ func (b *DBBackend) ListCalendarObjects(ctx context.Context, p string, req *cald
return nil, err return nil, err
} }
return b.listCalendarObjectsRaw(ctx, calID, ownerName)
}
func (b *DBBackend) listCalendarObjectsRaw(ctx context.Context, calID int, ownerName string) ([]caldav.CalendarObject, error) {
rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID) rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -609,49 +711,29 @@ func (b *DBBackend) listAggregateObjects(ctx context.Context, aggPath string, ag
continue continue
} }
rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID) objs, err := b.listCalendarObjectsRaw(ctx, calID, ownerName)
if err != nil { if err != nil {
continue continue
} }
for rows.Next() { for _, obj := range objs {
var obj caldav.CalendarObject // Prepend source name so Diane knows this is a "[calendar]" event
var dataStr string for _, child := range obj.Data.Children {
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" { if child.Name == "VEVENT" || child.Name == "VTODO" {
summary := child.Props.Get("SUMMARY") descr := child.Props.Get("DESCRIPTION")
val := "" val := ""
if summary != nil { if descr != nil {
val = summary.Value val = descr.Value
} }
child.Props.SetText("SUMMARY", fmt.Sprintf("[%s] %s", sourceID, val)) child.Props.SetText("DESCRIPTION", fmt.Sprintf("[%s]\n%s", sourceID, val))
} }
} }
// Virtualize the path so Thunderbird doesn't reject the file // Virtualize the path so Thunderbird doesn't reject the file
fileName := path.Base(obj.Path) fileName := path.Base(obj.Path)
obj.Path = aggPath + sourceID + "__" + fileName obj.Path = aggPath + sourceID + "__" + fileName
obj.Data = filtered
res = append(res, obj) res = append(res, obj)
} }
rows.Close()
} }
return res, nil return res, nil
} }

View File

@@ -12,6 +12,7 @@ type Access struct {
Group string `yaml:"group,omitempty"` Group string `yaml:"group,omitempty"`
Groups string `yaml:"groups,omitempty"` Groups string `yaml:"groups,omitempty"`
Mode string `yaml:"mode"` // "read-only" or "read-write" Mode string `yaml:"mode"` // "read-only" or "read-write"
ICS string `yaml:"ics,omitempty"`
} }
type Calendar struct { type Calendar struct {

View File

@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"strings"
"time" "time"
"github.com/emersion/go-webdav/caldav" "github.com/emersion/go-webdav/caldav"
@@ -27,6 +28,11 @@ func main() {
handler := &caldav.Handler{Backend: be} handler := &caldav.Handler{Backend: be}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/public/") {
be.ServePublicICS(w, r)
return
}
user, password, ok := r.BasicAuth() user, password, ok := r.BasicAuth()
if !ok { if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`) w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`)