Files
uptimesebi/internal/statuspage/statuspage_test.go
T
Sebastian UnterschützandClaude Opus 5.5 538c43b563
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m29s
ci / test (pull_request) Successful in 12m55s
ci / build (pull_request) Successful in 16m45s
ci / image (pull_request) Successful in 5m41s
feat(agents): talk to the API over a WebSocket and push page changes
Checkers and status page servers keep one WebSocket open to the API at
/agent/v1/stream and send their requests over it. The API answers them
through the agent API as if they had come over HTTP, each authenticated
again, so the protocol stays the same and a revoked token ends the
stream. While the stream is down agents fall back to plain HTTP, and an
API without it is asked again every five minutes.

Over the stream the API tells status page servers which of their pages
changed, so they fetch them at once instead of on their next refresh:
when a region of a monitor changes between up and down, an incident
opens or resolves, or anything of the organization is edited. Changes
are announced through Redis to every API instance and sent at most every
five seconds per stream. A page that changes while it is fetched is
fetched once more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 17:21:30 +01:00

590 lines
21 KiB
Go

package statuspage
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
type fakeSource struct {
mu sync.Mutex
calls int
// unchanged counts the answers that the page had not changed.
unchanged int
err error
delay time.Duration
pages map[string]agentapi.PageSnapshot
}
// PageIfChanged counts calls and answers like the API, sending pages
// only when their checksum changed.
func (f *fakeSource) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) {
p, err := f.page(ctx, host, slug)
if err == nil && checksum != "" && p.Checksum() == checksum {
f.mu.Lock()
f.unchanged++
f.mu.Unlock()
return agentapi.PageSnapshot{}, agentapi.ErrNotModified
}
return p, err
}
func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
f.mu.Lock()
f.calls++
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
if _, exists := f.pages[host+"|"+slug]; exists {
ok = true
}
f.mu.Unlock()
if delay > 0 {
select {
case <-time.After(delay):
case <-ctx.Done():
return p, ctx.Err()
}
}
if err != nil {
return agentapi.PageSnapshot{}, err
}
if !ok {
return p, agentapi.ErrNotFound
}
return p, nil
}
// Pages lists the fake's pages by their keys: "host|" or "|slug".
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.err != nil {
return nil, f.err
}
var out []agentapi.PageRef
for k := range f.pages {
host, slug, _ := strings.Cut(k, "|")
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
}
return out, nil
}
func (f *fakeSource) set(fn func(*fakeSource)) {
f.mu.Lock()
defer f.mu.Unlock()
fn(f)
}
type harness struct {
srv *Server
src *fakeSource
r *gin.Engine
now *time.Time
}
func newHarness(t *testing.T, src *fakeSource, dir string, now *time.Time) harness {
t.Helper()
cat, err := i18n.Load()
if err != nil {
t.Fatal(err)
}
s, err := New(src, cat, slog.New(slog.DiscardHandler), Options{Hosts: []string{"status.example.test"}, CacheDir: dir})
if err != nil {
t.Fatal(err)
}
s.now = func() time.Time { return *now }
// Runs before the cleanup of a TempDir created earlier, so no refresh
// writes into a directory being removed.
t.Cleanup(s.Wait)
gin.SetMode(gin.TestMode)
r := gin.New()
s.Mount(r)
return harness{srv: s, src: src, r: r, now: now}
}
func newSource() *fakeSource {
return &fakeSource{pages: map[string]agentapi.PageSnapshot{
"|acme": {Title: "Acme status", Status: agentapi.PageOperational},
"status.acme.test|": {Title: "Acme on own domain", Status: agentapi.PageOutage},
}}
}
func (h harness) get(host, path string) (int, string) {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Host = host
req.Header.Set("Accept-Language", "de")
w := httptest.NewRecorder()
h.r.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
func TestRouting(t *testing.T) {
now := time.Now()
h := newHarness(t, newSource(), t.TempDir(), &now)
tests := []struct {
host, path string
want int
contains string
}{
{"status.example.test", "/acme", 200, "Acme status"},
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
{"status.example.test", "/missing", 404, ""},
{"status.example.test", "/", 404, ""},
{"status.acme.test", "/", 200, "Acme on own domain"},
{"status.acme.test", "/acme", 404, ""},
{"other.test", "/", 404, ""},
}
for _, tt := range tests {
code, body := h.get(tt.host, tt.path)
if code != tt.want || !strings.Contains(body, tt.contains) {
t.Errorf("GET %s%s = %d (contains %q: %t), want %d", tt.host, tt.path, code, tt.contains, strings.Contains(body, tt.contains), tt.want)
}
}
}
// TestSurvivesAPIOutageAndRestart is the reason this package keeps state:
// the page must stay up while the API is down, also across restarts.
func TestSurvivesAPIOutageAndRestart(t *testing.T) {
dir := t.TempDir()
now := time.Now()
h := newHarness(t, newSource(), dir, &now)
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
t.Fatalf("first GET = %d", code)
}
down := &fakeSource{err: errors.New("connection refused")}
now = now.Add(time.Minute)
restarted := newHarness(t, down, dir, &now)
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET after restart with API down = %d, want cached page without stale notice", code)
}
if err := restarted.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err != nil {
t.Errorf("Ready() with cached pages and API down = %v, want ready", err)
}
now = now.Add(72 * time.Hour)
code, body := restarted.get("status.example.test", "/acme")
if code != 200 || !strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET three days into the outage = %d, want cached page with stale notice", code)
}
}
func TestReadyWithoutCacheNeedsAPI(t *testing.T) {
now := time.Now()
h := newHarness(t, newSource(), t.TempDir(), &now)
if err := h.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err == nil {
t.Error("Ready() with empty cache and API down = nil, want error")
}
}
func TestCachedPagesDoNotWaitForAPI(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) { f.delay = 5 * time.Second })
now = now.Add(time.Minute)
start := time.Now()
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
t.Fatalf("GET = %d", code)
}
if took := time.Since(start); took > time.Second {
t.Errorf("GET with a hanging API took %v, want an immediate cached answer", took)
}
}
func TestBackgroundRefresh(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
})
now = now.Add(time.Minute)
h.get("status.example.test", "/acme") // served from cache, triggers refresh
deadline := time.Now().Add(2 * time.Second)
for {
_, body := h.get("status.example.test", "/acme")
if strings.Contains(body, "Renamed") {
break
}
if time.Now().After(deadline) {
t.Fatal("cached page was not refreshed in the background")
}
time.Sleep(20 * time.Millisecond)
}
}
func TestDeletedPageDisappears(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
now = now.Add(time.Minute)
h.srv.refresh(context.Background(), "slug:acme", "", "acme")
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after the API reported the page gone = %d, want 404", code)
}
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
if code, _ := restarted.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after restart = %d, want 404 (removed from disk too)", code)
}
}
func TestLegalDocuments(t *testing.T) {
now := time.Now()
src := newSource()
legal := []agentapi.LegalDoc{
{Kind: "imprint", Markdown: "# Impressum\n\nAcme GmbH <script>alert(1)</script> [x](javascript:alert(1))"},
{Kind: "privacy", URL: "https://acme.example/privacy"},
}
src.pages["|acme"] = agentapi.PageSnapshot{Title: "Acme status", Status: agentapi.PageOperational, Legal: legal}
src.pages["status.acme.test|"] = agentapi.PageSnapshot{Title: "Acme on own domain", Status: agentapi.PageOperational, Legal: legal}
h := newHarness(t, src, t.TempDir(), &now)
_, page := h.get("status.example.test", "/acme")
if !strings.Contains(page, `href="/acme/imprint"`) || !strings.Contains(page, `href="https://acme.example/privacy"`) {
t.Error("status page does not link its legal documents")
}
if _, page := h.get("status.acme.test", "/"); !strings.Contains(page, `href="/imprint"`) {
t.Error("custom domain page does not link /imprint")
}
// The API goes away; the documents stay reachable from the cache.
src.mu.Lock()
src.err = errors.New("connection refused")
src.mu.Unlock()
now = now.Add(time.Hour)
for _, tc := range []struct{ host, path string }{{"status.example.test", "/acme/imprint"}, {"status.acme.test", "/imprint"}} {
code, body := h.get(tc.host, tc.path)
if code != http.StatusOK || !strings.Contains(body, "<h1>Impressum</h1>") || !strings.Contains(body, "Acme GmbH") {
t.Errorf("GET %s%s = %d, lacks the rendered imprint", tc.host, tc.path, code)
}
if strings.Contains(body, "<script>alert") || strings.Contains(body, "javascript:") {
t.Errorf("GET %s%s renders unsafe markup", tc.host, tc.path)
}
}
req := httptest.NewRequest(http.MethodGet, "/acme/privacy", nil)
req.Host = "status.example.test"
w := httptest.NewRecorder()
h.r.ServeHTTP(w, req)
if w.Code != http.StatusFound || w.Header().Get("Location") != "https://acme.example/privacy" {
t.Errorf("privacy link = %d %s, want redirect", w.Code, w.Header().Get("Location"))
}
if code, _ := h.get("status.example.test", "/acme/other"); code != http.StatusNotFound {
t.Errorf("unknown document = %d, want 404", code)
}
}
// Maintenance in a cached snapshot starts on time even without the API.
func TestMaintenanceStartsWhileAPIIsDown(t *testing.T) {
now := time.Now()
src := newSource()
src.pages["|acme"] = agentapi.PageSnapshot{
Title: "Acme status", Status: agentapi.PageOperational, Description: "Run by **Acme**",
Sections: []agentapi.Section{{Components: []agentapi.Component{{Name: "Database", Status: agentapi.PageOperational}, {Name: "Web", Status: agentapi.PageOperational}}}},
Maintenance: []agentapi.PageMaintenance{{
Title: "DB upgrade", Description: "Expect <b>short</b> _gaps_.", Components: []string{"Database"},
Start: now.Add(30 * time.Minute), End: now.Add(90 * time.Minute),
}},
}
h := newHarness(t, src, t.TempDir(), &now)
_, page := h.get("status.example.test", "/acme")
if !strings.Contains(page, "Geplante Wartung") || strings.Contains(page, "Laufende Wartung") {
t.Error("upcoming maintenance is not announced as planned")
}
if !strings.Contains(page, "<strong>Acme</strong>") || !strings.Contains(page, "<em>gaps</em>") || strings.Contains(page, "<b>short</b>") {
t.Error("descriptions are not rendered as safe Markdown")
}
src.mu.Lock()
src.err = errors.New("connection refused")
src.mu.Unlock()
now = now.Add(45 * time.Minute)
_, page = h.get("status.example.test", "/acme")
if !strings.Contains(page, "Laufende Wartung") || !strings.Contains(page, "Geplante Wartung läuft") {
t.Error("maintenance in progress is not shown from the cache")
}
now = now.Add(time.Hour)
if _, page = h.get("status.example.test", "/acme"); strings.Contains(page, "Wartung") {
t.Error("ended maintenance is still shown")
}
}
func TestNestedGroupsAndComponentDetails(t *testing.T) {
now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)
hours := make([]agentapi.HourBucket, 24)
for i := range hours {
hours[i] = agentapi.HourBucket{
Time: now.Add(-time.Duration(23-i) * time.Hour),
Uptime: 1,
AvgLatencyMS: 35 + i,
}
}
snap := agentapi.PageSnapshot{
Slug: "acme",
Title: "Acme status",
Status: agentapi.PageDegraded,
ShowDetails: true,
GeneratedAt: now,
Sections: []agentapi.Section{
{
Name: "Platform",
Status: agentapi.PageDegraded,
Total: 2,
Children: []agentapi.Section{
{
Name: "API",
Status: agentapi.PageOutage,
Total: 1,
Components: []agentapi.Component{
{
ID: "comp-api",
Name: "Public API",
Status: agentapi.PageOutage,
Uptime: 0.995,
Days: []agentapi.Day{{Date: "2026-11-22", Uptime: 0.995}},
Details: &agentapi.ComponentDetails{
SLA24h: 0.99,
SLA7d: 0.995,
SLA30d: 0.998,
SLA90d: 0.995,
Hours: hours,
Regions: []agentapi.ComponentRegion{
{Name: "Frankfurt", Status: agentapi.PageOperational, LatencyMS: 42},
},
},
},
},
},
},
Components: []agentapi.Component{
{
ID: "comp-web",
Name: "Website",
Status: agentapi.PageOperational,
Uptime: 1,
Days: []agentapi.Day{{Date: "2026-11-22", Uptime: 1}},
},
},
},
},
Incidents: []agentapi.PageIncident{
{Component: "Public API", StartedAt: now.Add(-10 * time.Minute)},
{
Component: "Website", StartedAt: now.Add(-time.Hour), Title: "Anmeldung langsam", Status: "monitoring",
Updates: []agentapi.PageIncidentUpdate{
{Status: "monitoring", Message: "Fix ist **ausgerollt**.", At: now.Add(-5 * time.Minute)},
{Status: "investigating", Message: "Wir schauen.\n\n<script>alert(1)</script>", At: now.Add(-50 * time.Minute)},
},
},
{Component: "Website", StartedAt: now.Add(-2 * time.Hour), Title: "Zahlungen", Status: "custom", StatusName: "Warten auf Anbieter", StatusColor: "#7c3aed"},
},
Maintenance: []agentapi.PageMaintenance{
{Title: "Datenbank-Upgrade", Start: now.Add(24 * time.Hour), End: now.Add(25 * time.Hour), Components: []string{"Website"}},
},
}
src := &fakeSource{pages: map[string]agentapi.PageSnapshot{
"|acme": snap,
"status.acme.test|": snap,
}}
h := newHarness(t, src, t.TempDir(), &now)
t.Run("incidents show their title, status and updates", func(t *testing.T) {
_, body := h.get("status.example.test", "/acme")
for _, want := range []string{"Anmeldung langsam", "Beobachtung", "Untersuchung läuft", "<strong>ausgerollt</strong>", "Wir schauen."} {
if !strings.Contains(body, want) {
t.Errorf("GET /acme missing %q", want)
}
}
if strings.Contains(body, "<script>alert") {
t.Error("an update's HTML reached the page")
}
if !strings.Contains(body, "Warten auf Anbieter") || !strings.Contains(body, "background-color:#7c3aed") {
t.Error("the own status lacks its name or color")
}
// The component list names the status of the newest open incident.
if i, j := strings.Index(body, "Beobachtung"), strings.Index(body, "Letzte Vorfälle"); i < 0 || i > j {
t.Error("the component list lacks the status of the open incident")
}
// Recent incidents come before planned maintenance.
if i, j := strings.Index(body, "Letzte Vorfälle"), strings.Index(body, "Geplante Wartung"); i < 0 || j < 0 || i > j {
t.Errorf("incidents at %d, planned maintenance at %d: want incidents first", i, j)
}
})
t.Run("main page renders nested groups and clickable links", func(t *testing.T) {
code, body := h.get("status.example.test", "/acme")
if code != http.StatusOK {
t.Fatalf("GET /acme = %d, want 200", code)
}
for _, want := range []string{"<details open", "Platform", "API", `href="/acme/components/comp-api"`, `href="/acme/components/comp-web"`} {
if !strings.Contains(body, want) {
t.Errorf("GET /acme missing %q", want)
}
}
})
t.Run("component detail page on slug and custom domain", func(t *testing.T) {
cases := []struct {
name string
host string
path string
back string
}{
{name: "slug", host: "status.example.test", path: "/acme/components/comp-api", back: `href="/acme"`},
{name: "custom domain", host: "status.acme.test", path: "/components/comp-api", back: `href="/"`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
code, body := h.get(tc.host, tc.path)
if code != http.StatusOK {
t.Fatalf("GET %s%s = %d, want 200", tc.host, tc.path, code)
}
for _, want := range []string{tc.back, "Public API", "Frankfurt", "42 ms", "<polyline", "Letzte 24 Stunden"} {
if !strings.Contains(body, want) {
t.Errorf("GET %s%s missing %q", tc.host, tc.path, want)
}
}
})
}
})
t.Run("unknown component returns 404", func(t *testing.T) {
if code, _ := h.get("status.example.test", "/acme/components/missing"); code != http.StatusNotFound {
t.Errorf("GET /acme/components/missing = %d, want 404", code)
}
})
t.Run("detail page stays available from cache during API outage", func(t *testing.T) {
src.set(func(f *fakeSource) { f.err = errors.New("connection refused") })
code, body := h.get("status.example.test", "/acme/components/comp-api")
if code != http.StatusOK || !strings.Contains(body, "Frankfurt") {
t.Errorf("GET cached detail during API outage = %d, want 200 with region data", code)
}
})
t.Run("detail page returns 404 when ShowDetails is disabled", func(t *testing.T) {
disabled := snap
disabled.ShowDetails = false
h2 := newHarness(t, &fakeSource{pages: map[string]agentapi.PageSnapshot{"|acme": disabled}}, t.TempDir(), &now)
code, body := h2.get("status.example.test", "/acme")
if code != http.StatusOK || strings.Contains(body, "/components/") {
t.Errorf("main page with ShowDetails=false = %d, unexpectedly links to /components/", code)
}
if code, _ := h2.get("status.example.test", "/acme/components/comp-api"); code != http.StatusNotFound {
t.Errorf("detail page with ShowDetails=false = %d, want 404", code)
}
})
}
func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.srv.Sync(context.Background())
// Nobody visited them, yet both survive an outage and a restart.
now = now.Add(syncInterval)
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET of a synced page with the API down = %d, want it without stale notice", code)
}
if code, body := restarted.get("status.acme.test", "/"); code != 200 || !strings.Contains(body, "Acme on own domain") {
t.Errorf("GET of a synced custom domain with the API down = %d", code)
}
restarted.srv.Sync(context.Background())
if code, _ := restarted.get("status.example.test", "/acme"); code != 200 {
t.Errorf("a failed sync dropped the cache: %d", code)
}
// A page the API no longer lists is dropped by the next sync.
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
h.srv.Sync(context.Background())
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after the page left the list = %d, want 404", code)
}
}
func TestRefreshSkipsUnchangedPages(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.srv.Sync(context.Background())
now = now.Add(syncInterval)
h.srv.Sync(context.Background())
src.mu.Lock()
unchanged := src.unchanged
src.mu.Unlock()
if unchanged != 2 {
t.Errorf("unchanged answers on the second sync = %d, want 2", unchanged)
}
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Error("an unchanged page is not served as current")
}
// A changed page is sent again, and the checksum survives a restart.
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
})
restarted := newHarness(t, src, dir, &now)
restarted.srv.Sync(context.Background())
src.mu.Lock()
unchanged = src.unchanged
src.mu.Unlock()
if _, body := restarted.get("status.example.test", "/acme"); !strings.Contains(body, "Renamed") || unchanged != 3 {
t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged)
}
}
// Pages the API says changed are fetched at once, and once more when they
// change during that fetch.
func TestEventsRefreshPagesAtOnce(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
if code, body := h.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") {
t.Fatalf("first GET = %d", code)
}
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Acme renamed", Status: agentapi.PageOperational}
f.delay = 200 * time.Millisecond
f.calls = 0
})
event := []byte(`{"pages":[{"slug":"acme"}]}`)
h.srv.OnEvent(agentapi.EventPages, event)
time.Sleep(50 * time.Millisecond)
// Arrives while the first fetch runs.
h.srv.OnEvent(agentapi.EventPages, event)
h.srv.OnEvent("unknown", nil)
h.srv.Wait()
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme renamed") {
t.Error("page not refreshed after the event")
}
src.mu.Lock()
calls := src.calls
src.mu.Unlock()
if calls != 2 {
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
}
}