Files
nidus/cmd/server/main.go
T
arnefandCopilot daa51d62b1 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>
2026-08-18 20:10:31 +02:00

253 lines
7.3 KiB
Go

package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/caldav"
"github.com/yourusername/caldav-server/internal/carddav"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
filewebdav "github.com/yourusername/caldav-server/internal/webdav"
)
func main() {
var cfgPath string
flag.StringVar(&cfgPath, "config", "config.yaml", "path to configuration file")
flag.Parse()
// ---- Configuration ----
cfg, err := config.Load(cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
os.Exit(1)
}
// ---- Logging ----
logger := buildLogger(cfg)
logger.Info("starting DAV server",
"host", cfg.Server.Host,
"port", cfg.Server.Port,
"base_url", cfg.Server.BaseURL,
"tls", cfg.TLS.Enabled)
// ---- Storage ----
st, err := store.NewStore(cfg.Storage.DataDir)
if err != nil {
logger.Error("initialising store", "error", err)
os.Exit(1)
}
// ---- Database (calendar/address-book sharing, future user mgmt) ----
dbPath := filepath.Join(cfg.Storage.DataDir, "nidus.db")
dbase, err := db.Open(dbPath)
if err != nil {
logger.Error("initialising database", "error", err)
os.Exit(1)
}
defer dbase.Close()
// Pre-create default collections for each user
for username, user := range cfg.Users {
for _, cal := range user.Calendars {
if err := st.EnsureCollection(username, "cal-"+cal); err != nil {
logger.Warn("creating calendar collection", "user", username, "cal", cal, "error", err)
}
}
for _, book := range user.AddressBooks {
if err := st.EnsureCollection(username, "card-"+book); err != nil {
logger.Warn("creating address book collection", "user", username, "book", book, "error", err)
}
}
}
// ---- Middleware ----
authMw := auth.NewMiddleware(cfg, logger)
// ---- Handlers ----
calHandler := caldav.NewHandler(cfg, st, dbase, logger)
cardHandler := carddav.NewHandler(cfg, st, dbase, logger)
fileHandler := filewebdav.NewHandler(cfg, cfg.Storage.DataDir, logger)
mux := buildMux(cfg, authMw, calHandler, cardHandler, fileHandler, logger)
// ---- HTTP Server ----
addr := net.JoinHostPort(cfg.Server.Host, fmt.Sprintf("%d", cfg.Server.Port))
srv := &http.Server{
Addr: addr,
Handler: withRequestLogging(mux, logger),
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
// ---- Graceful shutdown ----
idleConnsClosed := make(chan struct{})
go func() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.Info("shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.Error("graceful shutdown failed", "error", err)
}
close(idleConnsClosed)
}()
logger.Info("server ready", "addr", addr)
if cfg.TLS.Enabled {
err = srv.ListenAndServeTLS(cfg.TLS.CertFile, cfg.TLS.KeyFile)
} else {
err = srv.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
}
<-idleConnsClosed
logger.Info("server stopped")
}
// buildMux creates the top-level HTTP multiplexer.
func buildMux(
cfg *config.Config,
authMw *auth.Middleware,
calHandler, cardHandler, fileHandler http.Handler,
logger *slog.Logger,
) *http.ServeMux {
mux := http.NewServeMux()
// /.well-known/ redirects for auto-discovery
mux.HandleFunc("/.well-known/caldav", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, cfg.Server.BaseURL+"/cal/", http.StatusMovedPermanently)
})
mux.HandleFunc("/.well-known/carddav", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, cfg.Server.BaseURL+"/card/", http.StatusMovedPermanently)
})
// Health check (unauthenticated)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
// CalDAV, CardDAV, and file WebDAV — all behind Basic Auth
mux.Handle("/cal/", authMw.Wrap(calHandler))
mux.Handle("/card/", authMw.Wrap(cardHandler))
mux.Handle("/files/", authMw.Wrap(fileHandler))
// Root — simple HTML welcome page (unauthenticated)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// Only plain GET/HEAD get the welcome page. Any other method
// (PROPFIND, LOCK, PUT, ...) hitting "/" means a client is pointed
// at the wrong URL — reject it explicitly instead of returning a
// misleading 200 OK, which breaks WebDAV clients expecting 207.
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "not a WebDAV collection; use /cal/, /card/ or /files/", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, welcomePage, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL, cfg.Server.BaseURL)
})
return mux
}
// withRequestLogging wraps a handler with access-log middleware.
func withRequestLogging(next http.Handler, logger *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, code: http.StatusOK}
next.ServeHTTP(rw, r)
logger.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", rw.code,
"duration_ms", time.Since(start).Milliseconds(),
"remote_addr", r.RemoteAddr,
)
})
}
// responseWriter captures the status code for logging.
type responseWriter struct {
http.ResponseWriter
code int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.code = code
rw.ResponseWriter.WriteHeader(code)
}
// buildLogger creates a slog.Logger based on config.
func buildLogger(cfg *config.Config) *slog.Logger {
level := slog.LevelInfo
switch cfg.Logging.Level {
case "debug":
level = slog.LevelDebug
case "warn":
level = slog.LevelWarn
case "error":
level = slog.LevelError
}
var handler slog.Handler
opts := &slog.HandlerOptions{Level: level}
if cfg.Logging.Format == "json" {
handler = slog.NewJSONHandler(os.Stdout, opts)
} else {
handler = slog.NewTextHandler(os.Stdout, opts)
}
return slog.New(handler)
}
const welcomePage = `<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>DAV Server</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 640px; margin: 4rem auto; padding: 0 1rem; }
h1 { color: #333; }
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }
ul { line-height: 2; }
</style>
</head>
<body>
<h1>🗓 DAV Server</h1>
<p>This server provides CalDAV, CardDAV, and WebDAV access.</p>
<h2>Endpoints</h2>
<ul>
<li><strong>CalDAV</strong> — <code>%s/cal/</code></li>
<li><strong>CardDAV</strong> — <code>%s/card/</code></li>
<li><strong>WebDAV files</strong> — <code>%s/files/</code></li>
</ul>
<h2>Auto-discovery</h2>
<ul>
<li><code>%s/.well-known/caldav</code></li>
<li><code>%s/.well-known/carddav</code></li>
</ul>
<p><em>Authentication: HTTP Basic Auth</em></p>
</body>
</html>`