New internal/web package mounted at /ui/, separate from DAV Basic Auth: - Cookie-based sessions (opaque random tokens in a new web_sessions SQLite table, internal/db/sessions.go), checked against the same cfg.Users/bcrypt credentials as DAV Basic Auth. - Dashboard listing the logged-in user's own calendars/address books, who they're shared with, and what's shared with them. - Share/unshare directly from the dashboard, updated in place via htmx partial swaps (POST to create/update, DELETE to revoke). Always verifies the resource actually belongs to the logged-in user before granting a share. - Templates written in templ (internal/web/templates/*.templ, generated *_templ.go committed), styled with Tailwind CSS v4 (web/input.css, compiled to web/static/app.css), with htmx vendored as a static file for the dynamic bits. Both are embedded into the binary at build time (web/staticassets.go) so the compiled server has no Node.js/web/ runtime dependency. - Wired into cmd/server/main.go at /ui/ alongside the existing /cal/, /card/, /files/ routes; welcome page links to it. - Tests: internal/web/server_test.go covers login success/failure, the login-required redirect, dashboard rendering, share/unshare including the htmx-v2-sends-DELETE-params-as-query-string quirk, and rejecting shares of resources the user doesn't own. - Docs: README (new 'Web UI' section, updated sharing section, project layout, dependencies) and copilot-instructions updated accordingly. Makefile: new templ-generate/web-deps/web-css targets. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
222 lines
6.8 KiB
Go
222 lines
6.8 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"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
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() })
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.MinCost)
|
|
if err != nil {
|
|
t.Fatalf("GenerateFromPassword: %v", err)
|
|
}
|
|
|
|
cfg := &config.Config{
|
|
Users: map[string]config.UserConfig{
|
|
"alice": {Password: string(hash), Calendars: []string{"work"}, AddressBooks: []string{"contacts"}},
|
|
"bob": {Password: string(hash), Calendars: []string{"personal"}},
|
|
},
|
|
}
|
|
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, "/ui/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, "/ui/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, "/ui/", 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 != "/ui/login" {
|
|
t.Fatalf("expected redirect to /ui/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, "/ui/", 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, "/ui/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, "/ui/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, "/ui/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, "/ui/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
|
|
}
|