Files
landwelle/content_analytics_test.go
T
OpenGenesis (MPL 2.0) 1831e499c8 fix: improve portal stability, proxy security and frontend consistency v1.5.73
* security: add verified central client IP resolution with regression tests

* security: add verified central client IP resolution with regression tests

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix(stability): standardize request identity, readiness and predictable build

* fix: remove unused network imports after centralized IP handling

* fix: remove unused network imports after centralized IP handling

* fix: buffer public templates before responding and return HTTP 500 on render failures

* fix: cancel now-playing polling on graceful shutdown

* fix: join now-playing background worker before shutdown

* fix(deploy): ensure rollback on failed restart or wrong version

* fix(frontend): update public pages to app-v18 player and consent script (part 1)

* fix(frontend): update public pages to app-v18 player and consent script (part 2)

* fix(frontend): update public pages to app-v18 player and consent script (part 3)

* test: verify atomic public templates and consistent player JavaScript

* test: require Landwelle v1.5.73

* ci: validate frontend scripts and deployment shell syntax

* docs: document v1.5.73 changes, proxy setup and remaining architecture work

* docs: record Landwelle v1.5.73 quality release

* fix(charts): remove obsolete strings import after IP resolver refactor

* test(frontend): assert consent-aware analytics uses current app-v18.js
2026-10-21 13:36:18 +02:00

320 lines
11 KiB
Go

package main
import (
"bytes"
"html/template"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func TestPublicContentMigrationContract(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("migrations", "0033_public_content_mediathek_analytics.sql"))
if err != nil {
t.Fatal(err)
}
migration := string(raw)
for _, want := range []string{
"landwelle.public_pages",
"landwelle.contact_messages",
"landwelle.mediathek_entries",
"landwelle.web_analytics_events",
"visitor_hash",
"session_hash",
"source_key",
"mediathek_entries_source_key_uidx",
} {
if !strings.Contains(migration, want) {
t.Fatalf("migration 0033 is missing %q", want)
}
}
for _, forbidden := range []string{"ip_address", "user_agent", "\nBEGIN;", "\nCOMMIT;"} {
if strings.Contains(strings.ToLower(migration), strings.ToLower(forbidden)) {
t.Fatalf("migration 0033 contains forbidden analytics or transaction detail %q", forbidden)
}
}
}
func TestChartPresentationFixes(t *testing.T) {
cssRaw, err := os.ReadFile(filepath.Join("web", "assets", "charts-v8.css"))
if err != nil {
t.Fatal(err)
}
css := string(cssRaw)
for _, want := range []string{
"aspect-ratio:16/10;max-height:255px",
".chart-vote-countdown[hidden]{display:none!important}",
"background:#203422",
} {
if !strings.Contains(css, want) {
t.Fatalf("chart stylesheet is missing %q", want)
}
}
templateRaw, err := os.ReadFile(filepath.Join("web", "charts-listener.html"))
if err != nil {
t.Fatal(err)
}
page := string(templateRaw)
for _, want := range []string{"Aktuelle Punkte", "Letzte Woche", "Dabei seit", "Tendenz"} {
if !strings.Contains(page, want) {
t.Fatalf("chart wording is missing %q", want)
}
}
for _, forbidden := range []string{"VOTING-STAND", "EINSTIEG"} {
if strings.Contains(page, forbidden) {
t.Fatalf("chart template still contains technical label %q", forbidden)
}
}
}
func TestAnalyticsPrivacyFilters(t *testing.T) {
cases := map[string]string{
"/charts/zuhoerer?utm_source=test": "/charts/zuhoerer",
"/presse#kontakt": "/presse",
"/admin/statistik": "",
"/api/v1/news": "",
"/media/audio.mp3": "",
"/assets/app-v16.js": "",
}
for input, want := range cases {
if got := normalizeAnalyticsPath(input); got != want {
t.Fatalf("normalizeAnalyticsPath(%q) = %q, want %q", input, got, want)
}
}
if !analyticsBot("Mozilla/5.0 compatible; ExampleBot/1.0") {
t.Fatal("known bot user agent was not excluded")
}
if analyticsBot("Mozilla/5.0 Firefox/140.0") {
t.Fatal("normal browser was classified as bot")
}
if got := analyticsHash("visitor", "abc-123456789"); len(got) != 64 || strings.Contains(got, "abc") {
t.Fatalf("visitor identifier is not pseudonymized correctly: %q", got)
}
}
func TestPublicAndAdminContentAssets(t *testing.T) {
for _, name := range []string{
"web/managed-page.html",
"web/faq.html",
"web/contact.html",
"web/mediathek.html",
"web/admin/site-content.html",
"web/admin/mediathek.html",
"web/admin/analytics.html",
"web/assets/site-content-v2.css",
"web/assets/admin-site-content-v2.css",
"web/assets/mediathek-v1.js",
"web/assets/mediathek-v4.css",
"web/assets/mediathek-hero-landwelle-v1.webp",
"web/assets/admin-analytics-v1.js",
"web/assets/admin-forum-v2.css",
} {
if _, err := webFS.ReadFile(name); err != nil {
t.Fatalf("missing embedded content asset %s: %v", name, err)
}
}
partials, err := webFS.ReadFile("web/partials.html")
if err != nil {
t.Fatal(err)
}
footer := string(partials)
if !strings.Contains(footer, `href="/presse"`) {
t.Fatal("public footer has no press link")
}
if strings.Contains(strings.ToLower(footer), "fotos & video") || strings.Contains(footer, "/fotos-videos") {
t.Fatal("removed photo/video navigation is still present")
}
adminMediathek, err := webFS.ReadFile("web/admin/mediathek.html")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"Direkt aus ElevenLabs", "Als Entwurf übernehmen"} {
if !strings.Contains(string(adminMediathek), want) {
t.Fatalf("admin mediathek is missing generated-audio action %q", want)
}
}
publicMediathek, err := webFS.ReadFile("web/mediathek.html")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"/assets/mediathek-hero-landwelle-v1.webp", "/assets/mediathek-v4.css", "fetchpriority=\"high\"", "mediathek-hero-shade"} {
if !strings.Contains(string(publicMediathek), want) {
t.Fatalf("public mediathek hero is missing %q", want)
}
}
heroAsset, err := webFS.ReadFile("web/assets/mediathek-hero-landwelle-v1.webp")
if err != nil {
t.Fatal(err)
}
if len(heroAsset) < 12 || string(heroAsset[:4]) != "RIFF" || string(heroAsset[8:12]) != "WEBP" {
t.Fatal("mediathek hero is not a valid embedded WebP container")
}
for _, name := range []string{"web/managed-page.html", "web/faq.html", "web/contact.html", "web/mediathek.html"} {
raw, err := webFS.ReadFile(name)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), "/assets/app-v18.js") {
t.Fatalf("public template %s does not load consent-aware analytics", name)
}
}
}
func TestContentTemplatesParse(t *testing.T) {
publicFuncs := template.FuncMap{
"year": func() int { return 2026 },
"seoHead": seoHead,
"playlistURL": playlistPageURL,
"paragraphs": managedParagraphs,
"publicNavigation": func() template.HTML { return navigationHTML(defaultNavigationItems()) },
"seq": func(a, b int) []int {
out := make([]int, 0, b-a+1)
for i := a; i <= b; i++ {
out = append(out, i)
}
return out
},
}
if _, err := template.New("public-content").Funcs(publicFuncs).ParseFS(webFS,
"web/partials.html", "web/managed-page.html", "web/faq.html", "web/contact.html", "web/mediathek.html"); err != nil {
t.Fatalf("new public templates do not parse: %v", err)
}
for _, file := range []string{"web/admin/site-content.html", "web/admin/mediathek.html", "web/admin/analytics.html", "web/admin/forum.html", "web/admin/management.html"} {
if _, err := parseAdminTemplate(file); err != nil {
t.Fatalf("admin template %s does not parse: %v", file, err)
}
}
}
func TestHomeHasHonestVorOrtEmptyState(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("web", "index.html"))
if err != nil {
t.Fatal(err)
}
page := string(raw)
for _, want := range []string{"Aktuell liegen uns keine neuen Geschichten aus der Region vor.", "home-stories-empty"} {
if !strings.Contains(page, want) {
t.Fatalf("home page is missing honest empty state %q", want)
}
}
}
func TestAnalyticsRequestValidation(t *testing.T) {
valid := "abcDEF0123456789-identifier_42"
if !validAnalyticsIdentifier(valid) {
t.Fatalf("valid analytics identifier rejected: %q", valid)
}
for _, invalid := range []string{"short", strings.Repeat("a", 81), "abcdefghijklmnopqrst!", "abcdefghijklmnopqrstä"} {
if validAnalyticsIdentifier(invalid) {
t.Fatalf("invalid analytics identifier accepted: %q", invalid)
}
}
req := httptest.NewRequest(http.MethodPost, "https://landwelle.de/api/site-analytics/pageview", nil)
req.Host = "landwelle.de"
req.Header.Set("Origin", "https://landwelle.de")
req.Header.Set("Sec-Fetch-Site", "same-origin")
if !analyticsSameOriginRequest(req) {
t.Fatal("same-origin analytics request was rejected")
}
req.Header.Set("Origin", "https://example.org")
if analyticsSameOriginRequest(req) {
t.Fatal("cross-origin analytics request was accepted")
}
req.Header.Set("Origin", "https://landwelle.de")
req.Header.Set("Sec-Fetch-Site", "cross-site")
if analyticsSameOriginRequest(req) {
t.Fatal("cross-site Sec-Fetch-Site request was accepted")
}
consent := `{"version":1,"necessary":true,"analytics":true,"externalMedia":false,"expiresAt":"2099-01-01T00:00:00Z"}`
req.AddCookie(&http.Cookie{Name: "landwelle_consent", Value: url.QueryEscape(consent)})
if !analyticsConsentCookieValid(req) {
t.Fatal("valid analytics consent cookie was rejected")
}
expired := `{"version":1,"necessary":true,"analytics":true,"expiresAt":"2020-01-01T00:00:00Z"}`
req = httptest.NewRequest(http.MethodPost, "https://landwelle.de/api/site-analytics/pageview", nil)
req.AddCookie(&http.Cookie{Name: "landwelle_consent", Value: url.QueryEscape(expired)})
if analyticsConsentCookieValid(req) {
t.Fatal("expired analytics consent cookie was accepted")
}
}
func TestVisibleManagedPageFiltersInactiveBlocks(t *testing.T) {
page := ManagedPublicPage{Blocks: []PublicPageBlock{
{ID: 1, Title: "Sichtbar", Active: true},
{ID: 2, Title: "Entwurf", Active: false},
}}
got := visibleManagedPage(page)
if len(got.Blocks) != 1 || got.Blocks[0].ID != 1 {
t.Fatalf("inactive public content leaked into public page: %#v", got.Blocks)
}
if len(page.Blocks) != 2 {
t.Fatal("visibleManagedPage unexpectedly modified the source page")
}
}
func TestMediathekAudioValidation(t *testing.T) {
store := &mediaStore{dir: t.TempDir()}
cases := []struct {
name string
data []byte
}{
{name: "test.mp3", data: append([]byte("ID3\x04\x00\x00\x00\x00\x00\x15"), bytes.Repeat([]byte{0}, 64)...)},
{name: "test.ogg", data: append([]byte("OggS\x00\x02"), bytes.Repeat([]byte{0}, 64)...)},
{name: "test.wav", data: append([]byte("RIFF\x24\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00"), bytes.Repeat([]byte{0}, 64)...)},
{name: "test.m4a", data: append([]byte("\x00\x00\x00\x18ftypM4A \x00\x00\x00\x00M4A "), bytes.Repeat([]byte{0}, 64)...)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
url, err := store.saveAudio(bytes.NewReader(tc.data), int64(len(tc.data)), tc.name)
if err != nil {
t.Fatalf("valid audio was rejected: %v", err)
}
if !strings.HasPrefix(url, "/media/audio-") {
t.Fatalf("unexpected audio URL %q", url)
}
})
}
fake := []byte("This is not an audio file")
if _, err := store.saveAudio(bytes.NewReader(fake), int64(len(fake)), "fake.mp3"); err == nil {
t.Fatal("fake MP3 was accepted")
}
}
func TestContactAndScheduledMediathekGuards(t *testing.T) {
raw, err := os.ReadFile("site_content.go")
if err != nil {
t.Fatal(err)
}
source := string(raw)
for _, want := range []string{
`WHERE me.active=true AND me.published_at<=now()`,
`limiter := newWishRateLimiter()`,
`Bitte warte einen kurzen Moment`,
} {
if !strings.Contains(source, want) {
t.Fatalf("site content guard is missing %q", want)
}
}
limiter := newWishRateLimiter()
req := httptest.NewRequest(http.MethodPost, "https://landwelle.de/kontakt", nil)
req.RemoteAddr = "192.0.2.5:12345"
if !limiter.Allow(req) {
t.Fatal("first contact request was rate-limited")
}
if limiter.Allow(req) {
t.Fatal("immediate duplicate contact request was not rate-limited")
}
}