Files
nidus/internal/web/server_test.go
T
arnefandCopilot 7d4f28de3c Move users, calendars, and address books from config.yaml into the database
BREAKING CHANGE: the users:/config-based collection setup is gone. All
user, calendar, and address-book data now lives in the SQLite DB
(internal/db) and is managed exclusively via nidusctl or the web UI.
Existing deployments must recreate their users after upgrading:
  nidusctl user create <username>
  nidusctl calendar create <username> <name>
  nidusctl addressbook create <username> <name>

- internal/db: new users, calendars, addressbooks tables with FK cascade
  delete; foreign_keys pragma enabled; internal/db/users.go implements
  full CRUD + bcrypt auth (CreateUser, VerifyPassword, ListUsers,
  CreateCalendar/AddressBook, etc).
- internal/config: removed Users/UserConfig entirely.
- internal/auth: Basic Auth now checks credentials via db.DB instead of
  cfg.Users.
- internal/caldav, internal/carddav: ListCalendars/ListAddressBooks and
  Create/Delete now backed by the DB.
- internal/web: login uses db.VerifyPassword; new resources.go adds
  create/delete handlers for calendars/address books at
  /web/resources/{calendar,addressbook}; dashboard gained create forms
  and per-card delete buttons (templ + htmx, no hyperscript).
- tools/nidusctl: new user create/delete/list/passwd commands (masked
  interactive password prompt via golang.org/x/term) plus create/delete/
  list subcommands for calendar/addressbook.
- cmd/server/main.go: pre-creates on-disk collections from the DB at
  startup instead of cfg.Users; warns when no users exist yet.
- Updated tests to seed data via the DB; added resources_test.go for the
  new web UI handlers.
- README.md and .github/copilot-instructions.md updated to document the
  new nidusctl commands and the DB-backed architecture.

Verified end-to-end against a live test server: nidusctl user/calendar/
addressbook create, DAV Basic Auth PROPFIND, web login, dashboard
rendering, and web UI create/delete of resources all confirmed working.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-08-19 12:43:34 +02:00

226 lines
7.0 KiB
Go

package web
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
func newTestServer(t *testing.T) *Server {
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{}
if err := dbase.CreateUser("alice", "password", "", ""); err != nil {
t.Fatalf("CreateUser alice: %v", err)
}
if err := dbase.CreateUser("bob", "password", "", ""); err != nil {
t.Fatalf("CreateUser bob: %v", err)
}
if err := dbase.CreateCalendar("alice", "work"); err != nil {
t.Fatalf("CreateCalendar alice/work: %v", err)
}
if err := dbase.CreateAddressBook("alice", "contacts"); err != nil {
t.Fatalf("CreateAddressBook alice/contacts: %v", err)
}
if err := dbase.CreateCalendar("bob", "personal"); err != nil {
t.Fatalf("CreateCalendar bob/personal: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(cfg, st, dbase, logger)
}
// loginAs performs a login request against handler and returns the
// resulting session cookie.
func loginAs(t *testing.T, handler http.Handler, username, password string) *http.Cookie {
t.Helper()
form := url.Values{"username": {username}, "password": {password}}
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Fatalf("login: expected 303, got %d: %s", rr.Code, rr.Body.String())
}
res := rr.Result()
for _, c := range res.Cookies() {
if c.Name == sessionCookieName {
return c
}
}
t.Fatal("login: no session cookie set")
return nil
}
func TestLoginSuccessAndFailure(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
if cookie.Value == "" {
t.Fatal("expected non-empty session token")
}
// Wrong password.
form := url.Values{"username": {"alice"}, "password": {"wrong"}}
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200 (re-rendered login form) on bad password, got %d", rr.Code)
}
if !strings.Contains(rr.Body.String(), "invalid username or password") {
t.Fatalf("expected error message in body, got: %s", rr.Body.String())
}
}
func TestDashboardRequiresLogin(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Fatalf("expected redirect to login, got %d", rr.Code)
}
if loc := rr.Result().Header.Get("Location"); loc != "/web/login" {
t.Fatalf("expected redirect to /web/login, got %q", loc)
}
}
func TestDashboardShowsOwnResources(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rr.Code)
}
body := rr.Body.String()
if !strings.Contains(body, "work") || !strings.Contains(body, "contacts") {
t.Fatalf("expected dashboard to list alice's calendar/address book, got: %s", body)
}
}
func TestShareUnshareCalendarFlow(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
// Share alice's "work" calendar with bob, write access.
form := url.Values{"resource": {"work"}, "shared_with": {"bob"}, "permission": {"write"}}
req := httptest.NewRequest(http.MethodPost, "/shares/calendar", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("share: expected 200, got %d: %s", rr.Code, rr.Body.String())
}
if !strings.Contains(rr.Body.String(), "bob") {
t.Fatalf("expected updated card to mention bob, got: %s", rr.Body.String())
}
shares, err := s.dbase.SharesOfCalendar("alice", "work")
if err != nil {
t.Fatalf("SharesOfCalendar: %v", err)
}
if len(shares) != 1 || shares[0].SharedWith != "bob" {
t.Fatalf("expected one share for bob, got %+v", shares)
}
// Unshare — htmx v2 sends DELETE params as a URL query string.
req = httptest.NewRequest(http.MethodDelete, "/shares/calendar?resource=work&shared_with=bob", nil)
req.AddCookie(cookie)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("unshare: expected 200, got %d: %s", rr.Code, rr.Body.String())
}
if !strings.Contains(rr.Body.String(), "Not shared with anyone") {
t.Fatalf("expected card to show no shares, got: %s", rr.Body.String())
}
shares, err = s.dbase.SharesOfCalendar("alice", "work")
if err != nil {
t.Fatalf("SharesOfCalendar: %v", err)
}
if len(shares) != 0 {
t.Fatalf("expected no shares after unshare, got %+v", shares)
}
}
func TestCannotShareResourceNotOwned(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
// alice doesn't own "personal" (that's bob's calendar).
form := url.Values{"resource": {"personal"}, "shared_with": {"bob"}, "permission": {"write"}}
req := httptest.NewRequest(http.MethodPost, "/shares/calendar", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusNotFound {
t.Fatalf("expected 404 for unowned resource, got %d", rr.Code)
}
}
func TestLogoutClearsSession(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
req := httptest.NewRequest(http.MethodGet, "/logout", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Fatalf("expected redirect on logout, got %d", rr.Code)
}
// Session should no longer be valid.
if _, err := s.dbase.SessionUser(cookie.Value); err == nil {
t.Fatal("expected session to be deleted after logout")
}
}
// emptyStaticFS is a no-op http.FileSystem for tests that don't exercise
// static asset serving.
type emptyStaticFS struct{}
func (emptyStaticFS) Open(name string) (http.File, error) {
return nil, os.ErrNotExist
}