Files
LektorenPlan/web/web/server_test.go
T

428 lines
13 KiB
Go

package web
import (
"context"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"lektorenplan/domain"
"lektorenplan/store"
)
// newTestServer seeds an in-memory database and returns a running server.
func newTestServer(t *testing.T) (*httptest.Server, *store.Store) {
t.Helper()
st, err := store.Open(":memory:")
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { st.Close() })
if err := st.SeedDemo(context.Background()); err != nil {
t.Fatalf("seed demo: %v", err)
}
srv, err := New(st, Options{Version: "test", DemoMode: true})
if err != nil {
t.Fatalf("new server: %v", err)
}
ts := httptest.NewServer(srv.Handler())
t.Cleanup(ts.Close)
return ts, st
}
func newClient(t *testing.T) *http.Client {
t.Helper()
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("cookie jar: %v", err)
}
return &http.Client{
Jar: jar,
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
func login(t *testing.T, client *http.Client, base, username, password string) {
t.Helper()
resp, err := client.PostForm(base+"/login", url.Values{
"username": {username}, "password": {password},
})
if err != nil {
t.Fatalf("login: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("login status = %d, want 303", resp.StatusCode)
}
location := resp.Header.Get("Location")
if location == "/password" {
// Every seeded account starts with a forced password change.
page := get(t, client, base+"/password", http.StatusOK)
csrf := extractCSRF(t, page)
change, err := client.PostForm(base+"/password", url.Values{
"csrf": {csrf},
"current_password": {password},
"new_password": {password + "1"},
"confirm_password": {password + "1"},
})
if err != nil {
t.Fatalf("change initial password: %v", err)
}
defer change.Body.Close()
if change.StatusCode != http.StatusSeeOther {
t.Fatalf("change password status = %d, want 303", change.StatusCode)
}
location = change.Header.Get("Location")
}
if !strings.HasPrefix(location, "/plan") {
t.Fatalf("login redirect = %q, want /plan", location)
}
}
func get(t *testing.T, client *http.Client, url string, want int) string {
t.Helper()
resp, err := client.Get(url)
if err != nil {
t.Fatalf("GET %s: %v", url, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != want {
t.Fatalf("GET %s = %d, want %d\n%s", url, resp.StatusCode, want, firstBytes(body, 400))
}
if want == http.StatusOK {
text := string(body)
if strings.Contains(text, "Die Seite konnte nicht erstellt werden.") {
t.Fatalf("GET %s rendered a template error", url)
}
}
return string(body)
}
func firstBytes(data []byte, n int) string {
if len(data) > n {
data = data[:n]
}
return string(data)
}
func TestFormatFloatUsesGermanComma(t *testing.T) {
fn, ok := templateFunctions()["formatFloat"].(func(float64) string)
if !ok {
t.Fatal("formatFloat template function missing")
}
for value, want := range map[float64]string{5: "5,0", 12.36: "12,4", 0.25: "0,3"} {
if got := fn(value); got != want {
t.Fatalf("formatFloat(%v) = %q, want %q", value, got, want)
}
}
}
func TestAuthenticatedPagesRender(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "admin", "admin123")
ctx := context.Background()
tenants, err := st.Tenants(ctx)
if err != nil || len(tenants) == 0 {
t.Fatalf("tenants: %v", err)
}
tenantID := tenants[0].ID
churches, _ := st.Churches(ctx, tenantID)
people, _ := st.People(ctx, tenantID)
templates, _ := st.Templates(ctx, tenantID)
exceptions, _ := st.Exceptions(ctx, tenantID)
services, _ := st.Services(ctx, tenantID, domain.YearRange(2025))
specials, _ := st.SpecialServices(ctx, tenantID)
if len(churches) == 0 || len(people) == 0 || len(templates) == 0 || len(services) == 0 || len(specials) == 0 {
t.Fatalf("demo data incomplete: churches=%d people=%d templates=%d services=%d specials=%d",
len(churches), len(people), len(templates), len(services), len(specials))
}
pages := []string{
"/plan",
"/plan?start=2025-01-01&end=2025-01-31",
"/services",
"/services?edit=" + templates[0].ID,
"/services?edit_special=" + specials[0].ID,
"/services/" + services[0].ID,
"/team",
"/team/person/" + people[0].ID,
"/statistics",
"/statistics?start=2025-01-01&end=2025-12-31",
"/exchange",
"/exchange/export",
"/settings",
"/liturgy?year=2025",
"/admin/tenants",
"/admin/tenants?edit=" + tenantID,
"/admin/users",
"/admin/churches",
"/admin/churches?edit=" + churches[0].ID,
"/pdf?variant=plan&start=2025-01-01&end=2025-01-31",
"/pdf?variant=compact&start=2025-01-01&end=2025-01-31",
}
if len(exceptions) > 0 {
pages = append(pages, "/services?edit_exception="+exceptions[0].ID)
}
for _, page := range pages {
get(t, client, ts.URL+page, http.StatusOK)
}
}
func TestRoleAndTenantGuards(t *testing.T) {
ts, _ := newTestServer(t)
reader := newClient(t)
login(t, reader, ts.URL, "reader", "reader123")
get(t, reader, ts.URL+"/plan", http.StatusOK)
get(t, reader, ts.URL+"/admin/users", http.StatusForbidden)
editor := newClient(t)
login(t, editor, ts.URL, "editor", "editor123")
get(t, editor, ts.URL+"/settings", http.StatusOK)
get(t, editor, ts.URL+"/admin/tenants", http.StatusForbidden)
anonymous := newClient(t)
get(t, anonymous, ts.URL+"/plan", http.StatusSeeOther)
}
func TestWritesAndCSRF(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "admin", "admin123")
body := get(t, client, ts.URL+"/plan", http.StatusOK)
csrf := extractCSRF(t, body)
// The login cookie session and CSRF token are valid for follow-up writes.
post := func(path string, form url.Values, want int) {
t.Helper()
form.Set("csrf", csrf)
resp, err := client.PostForm(ts.URL+path, form)
if err != nil {
t.Fatalf("POST %s: %v", path, err)
}
defer resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("POST %s = %d, want %d", path, resp.StatusCode, want)
}
}
post("/plan/generate", url.Values{"start": {"2026-12-01"}, "end": {"2026-12-31"}}, http.StatusSeeOther)
post("/plan/auto", url.Values{"start": {"2026-12-01"}, "end": {"2026-12-31"}}, http.StatusSeeOther)
get(t, client, ts.URL+"/plan?start=2026-12-01&end=2026-12-31", http.StatusOK)
// A missing CSRF token must be rejected before any mutation.
resp, err := client.PostForm(ts.URL+"/settings/save", url.Values{"auto_sync": {"1"}})
if err != nil {
t.Fatalf("POST without csrf: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("POST without csrf = %d, want 403", resp.StatusCode)
}
// The write above must not have reached the store.
if err := st.Healthy(context.Background()); err != nil {
t.Fatalf("store unhealthy: %v", err)
}
}
func TestLinkedReaderSelfService(t *testing.T) {
ts, st := newTestServer(t)
ctx := context.Background()
reader, err := st.UserByUsername(ctx, "reader")
if err != nil {
t.Fatalf("reader: %v", err)
}
tenants, err := st.Tenants(ctx)
if err != nil || len(tenants) == 0 {
t.Fatalf("tenants: %v", err)
}
var tenantID string
for _, tenant := range tenants {
if tenant.Slug == "bad-godesberg" {
tenantID = tenant.ID
break
}
}
if tenantID == "" {
t.Fatal("demo tenant not found")
}
people, err := st.People(ctx, tenantID)
if err != nil || len(people) < 2 {
t.Fatalf("people: %v", err)
}
if err := st.SetUserPersonLink(ctx, reader.ID, tenantID, people[0].ID); err != nil {
t.Fatalf("link reader: %v", err)
}
client := newClient(t)
login(t, client, ts.URL, "reader", "reader123")
body := get(t, client, ts.URL+"/team", http.StatusOK)
if !strings.Contains(body, people[0].FullName()) {
t.Fatalf("linked person missing from team page")
}
get(t, client, ts.URL+"/team/person/"+people[0].ID, http.StatusOK)
get(t, client, ts.URL+"/team/person/"+people[1].ID, http.StatusForbidden)
personBody := get(t, client, ts.URL+"/team/person/"+people[0].ID, http.StatusOK)
csrf := extractCSRF(t, personBody)
resp, err := client.PostForm(ts.URL+"/team/person/"+people[0].ID+"/save", url.Values{
"csrf": {csrf},
"first_name": {"Selbst"},
"last_name": {"Gepflegt"},
"email": {"selbst@example.org"},
})
if err != nil {
t.Fatalf("save own person: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("save own person = %d, want 303", resp.StatusCode)
}
updated, err := st.Person(ctx, tenantID, people[0].ID)
if err != nil || updated.FirstName != "Selbst" {
t.Fatalf("own person not updated: %#v, %v", updated, err)
}
if len(updated.Roles) != len(people[0].Roles) {
t.Fatalf("reader changed protected roles: %v", updated.Roles)
}
resp, err = client.PostForm(ts.URL+"/team/person/"+people[1].ID+"/save", url.Values{
"csrf": {csrf}, "first_name": {"Fremd"}, "last_name": {"Person"},
})
if err != nil {
t.Fatalf("save foreign person: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("save foreign person = %d, want 403", resp.StatusCode)
}
}
func TestReaderWithoutLinkCannotSeeTeam(t *testing.T) {
ts, _ := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "reader", "reader123")
get(t, client, ts.URL+"/team", http.StatusForbidden)
}
func TestAdminPasswordResetAndLoginQuote(t *testing.T) {
ts, st := newTestServer(t)
admin := newClient(t)
login(t, admin, ts.URL, "admin", "admin123")
body := get(t, admin, ts.URL+"/settings", http.StatusOK)
if !strings.Contains(body, "Spruch unter dem Logo") {
t.Fatal("admin settings do not expose the login quote")
}
csrf := extractCSRF(t, body)
resp, err := admin.PostForm(ts.URL+"/settings/save", url.Values{
"csrf": {csrf}, "login_quote": {"Neuer Spruch für die Anmeldung"},
"login_quote_source": {"Testgemeinde"},
})
if err != nil {
t.Fatalf("save settings: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("save settings = %d, want 303", resp.StatusCode)
}
anonymous := newClient(t)
loginPage := get(t, anonymous, ts.URL+"/login", http.StatusOK)
if !strings.Contains(loginPage, "Neuer Spruch für die Anmeldung") {
t.Fatal("configured login quote not rendered")
}
reader, err := st.UserByUsername(context.Background(), "reader")
if err != nil {
t.Fatalf("reader: %v", err)
}
usersPage := get(t, admin, ts.URL+"/admin/users?edit="+reader.ID, http.StatusOK)
csrf = extractCSRF(t, usersPage)
resp, err = admin.PostForm(ts.URL+"/admin/users/reset-password", url.Values{
"csrf": {csrf}, "id": {reader.ID},
})
if err != nil {
t.Fatalf("reset password: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("reset password = %d, want 303", resp.StatusCode)
}
reloaded, err := st.UserByUsername(context.Background(), "reader")
if err != nil {
t.Fatalf("reload reader: %v", err)
}
if !reloaded.MustChangePassword {
t.Fatal("password reset did not force a password change")
}
if _, err := st.Authenticate(context.Background(), "reader", "reader123"); err == nil {
t.Fatal("old reader password still valid after reset")
}
editor := newClient(t)
login(t, editor, ts.URL, "editor", "editor123")
editorSettings := get(t, editor, ts.URL+"/settings", http.StatusOK)
if strings.Contains(editorSettings, "Spruch unter dem Logo") {
t.Fatal("non-admin sees website-wide settings")
}
}
func TestPlanTimelinePresetsAndReadingLinks(t *testing.T) {
ts, st := newTestServer(t)
client := newClient(t)
login(t, client, ts.URL, "admin", "admin123")
tenants, err := st.Tenants(context.Background())
if err != nil || len(tenants) == 0 {
t.Fatalf("tenants: %v", err)
}
people, err := st.People(context.Background(), tenants[0].ID)
if err != nil || len(people) == 0 {
t.Fatalf("people: %v", err)
}
body := get(t, client, ts.URL+"/plan?start=2025-01-01&end=2025-12-31&person="+people[0].ID, http.StatusOK)
for _, marker := range []string{"Zeitstrahl", "Zeitraum-Presets", "Weihnachtszeit", "Osterzeit", "Ostern", "1. Advent"} {
if !strings.Contains(body, marker) {
t.Fatalf("plan page misses %q", marker)
}
}
if !strings.Contains(body, "Allgemeine Personen") && !strings.Contains(body, "Alle Personen") {
t.Fatal("plan page misses the person filter")
}
if !strings.Contains(body, "schott.erzabtei-beuron.de") {
t.Fatal("plan page misses the Schott reading link")
}
for _, marker := range []string{"plan-table-desktop", "plan-mobile-list", "plan-day-summary", "data-plan-mobile-empty"} {
if !strings.Contains(body, marker) {
t.Fatalf("plan page misses mobile markup %q", marker)
}
}
}
func extractCSRF(t *testing.T, body string) string {
t.Helper()
const marker = `name="csrf" value="`
index := strings.Index(body, marker)
if index < 0 {
t.Fatal("csrf token not found")
}
rest := body[index+len(marker):]
end := strings.Index(rest, `"`)
if end < 0 {
t.Fatal("malformed csrf token")
}
return rest[:end]
}