Files
uptimesebi/internal/api/statuspages_test.go
T
Sebastian UnterschützandClaude Opus 5.5 4e9a198b2f
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Canceled after 5m23s
ci / test (pull_request) Canceled after 5m23s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
feat(statuspage): fetch every served page every five minutes
A status page server only knew the pages visitors had asked it for, so
during an API outage a server that had never seen a page could not
serve it. The agent API now lists the pages a server serves
(GET /agent/v1/pages/index), following the same rule as single pages,
and status page servers fetch all of them on start and every five
minutes, also dropping those no longer listed. Pages visited within the
last ten minutes are still refreshed every 30 seconds; the outdated
notice now appears after ten minutes, twice the sync interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:51:46 +01:00

477 lines
19 KiB
Go

package api_test
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// statuspageClient creates a status page agent, platform-wide when org is
// nil, and returns a client for it.
func (e *env) statuspageClient(t *testing.T, org *uuid.UUID) *agentapi.Client {
t.Helper()
ctx := context.Background()
tok, params := api.NewAgentToken(org, "statuspage", "sp-"+uuid.NewString()[:6], nil)
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.CreateAgent(ctx, params)
return err
})
if err != nil {
t.Fatal(err)
}
return agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
}
func TestStatusPages(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) }))
defer down.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("s")+".test", uniq("sp-"))
newMonitor := func(name, target string) string {
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": name, "type": "http", "target": target, "interval_seconds": 60, "confirmations": 1, "regions": []string{region},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
return body["id"].(string)
}
webID, apiID := newMonitor("web", up.URL), newMonitor("api", down.URL)
slug := uniq("acme-")
st, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "theme": map[string]any{"accent": "#1f6feb"}})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
pageID := body["id"].(string)
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{
{"monitor_id": webID, "section": "Frontend", "label": "Website"},
{"monitor_id": apiID, "section": "Backend", "label": "Public API"},
}})
expect(t, "set page monitors", st, body, http.StatusNoContent, "")
platform := e.statuspageClient(t, nil)
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("Page(unpublished) error = %v, want not found", err)
}
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme Status", "published": true, "theme": map[string]any{"accent": "#1f6feb"}})
waitFor(t, 10*time.Second, "incident for the failing monitor", func() bool {
_, body := owner.do("GET", "/api/v1/org/incidents", nil)
return len(body["incidents"].([]any)) == 1
})
snap, err := platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page() failed: %v", err)
}
if snap.Status != agentapi.PageDegraded || len(snap.Sections) != 2 || snap.Sections[1].Components[0].Status != agentapi.PageOutage ||
snap.Sections[1].Components[0].Name != "Public API" {
t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap)
}
raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
if strings.Contains(string(raw), secret) {
t.Errorf("snapshot leaks %q", secret)
}
}
t.Run("rendered by the status page server", func(t *testing.T) {
cat, _ := i18n.Load()
srv, err := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
if err != nil {
t.Fatal(err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
srv.Mount(router)
req := httptest.NewRequest(http.MethodGet, "/"+slug, nil)
req.Host = "status.test"
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Acme Status") || !strings.Contains(w.Body.String(), "--page-accent:#1f6feb") {
t.Errorf("rendered page = %d %.200s", w.Code, w.Body.String())
}
})
t.Run("other org cannot use or see it", func(t *testing.T) {
other := e.browser(t)
other.signup("x@"+uniq("x")+".test", uniq("sp-other-"))
otherOrg := uuid.MustParse(other.orgID())
if _, err := e.statuspageClient(t, &otherOrg).Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("other org's status page server got the page: %v", err)
}
st, body := other.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("o-"), "title": "x"})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
st, body = other.do("PUT", "/api/v1/org/statuspages/"+body["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": webID}}})
expect(t, "list foreign monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
st, body = other.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "hijack"})
expect(t, "edit foreign page", st, body, http.StatusNotFound, "not_found")
})
t.Run("custom domain after verification", func(t *testing.T) {
domain := uniq("status") + ".example.test"
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/domain", map[string]any{"domain": domain})
if st != http.StatusOK {
t.Fatalf("set domain = %d %v", st, body)
}
record := body["domain_record"].(map[string]any)
if _, err := platform.Page(context.Background(), domain, ""); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("Page(unverified domain) error = %v, want not found", err)
}
verifyDomain(t, owner, pageID, record)
if snap, err := platform.Page(context.Background(), domain, ""); err != nil || snap.Title != "Acme Status" {
t.Errorf("Page(verified domain) = %v, %v", snap.Title, err)
}
})
t.Run("export", func(t *testing.T) {
resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
html, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Disposition"), slug+".html") ||
!strings.Contains(string(html), "<style>") || strings.Contains(string(html), `rel="stylesheet"`) {
t.Errorf("export = %d %q, want self-contained HTML", resp.StatusCode, resp.Header.Get("Content-Disposition"))
}
})
t.Run("console pages", func(t *testing.T) {
for path, want := range map[string]string{"/statuspages": "Acme Status", "/statuspages/" + pageID: `data-field="monitor_id"`} {
st, final, html := owner.page(path)
if st != http.StatusOK || final != path || !strings.Contains(html, want) {
t.Errorf("GET %s = %d at %s, contains %q: %t", path, st, final, want, strings.Contains(html, want))
}
}
})
t.Run("permission scoped to one page", func(t *testing.T) {
st, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("second-"), "title": "Second"})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
second := body["id"].(string)
owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Page editor", "permissions": []string{"statuspages.write"}})
editor := e.joinVia(t, owner.invite("pe@"+uniq("pe")+".test", owner.roleID("viewer")))
st, body = owner.do("POST", "/api/v1/org/members/"+owner.userID(editorEmail(editor))+"/roles", map[string]any{
"role_id": owner.roleID("Page editor"), "resource_type": "status_page", "resource_id": pageID,
})
expect(t, "assign scoped role", st, body, http.StatusCreated, "")
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme Status", "published": true})
expect(t, "edit page in scope", st, body, http.StatusOK, "")
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
})
t.Run("own servers replace the platform's", func(t *testing.T) {
org := uuid.MustParse(owner.orgID())
own := e.statuspageClient(t, &org)
lists := func(c *agentapi.Client) bool {
t.Helper()
refs, err := c.Pages(context.Background())
if err != nil {
t.Fatal(err)
}
return slices.ContainsFunc(refs, func(r agentapi.PageRef) bool { return r.Slug == slug && r.Host != "" })
}
if _, err := platform.Page(context.Background(), "", slug); err != nil || !lists(platform) {
t.Fatalf("platform server before the own one connected: %v", err)
}
if _, err := own.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("platform server still gets the page: %v", err)
}
if snap, err := own.Page(context.Background(), "", slug); err != nil || snap.Title != "Acme Status" {
t.Errorf("own server Page() = %v, %v", snap.Title, err)
}
if lists(platform) || !lists(own) {
t.Error("the page lists do not follow who serves the page")
}
if _, _, html := owner.page("/statuspages/" + pageID); !strings.Contains(html, "own status page servers serve its pages") {
t.Error("the editor does not say who serves the pages")
}
})
}
func editorEmail(b *browser) string {
_, me := b.do("GET", "/api/v1/me", nil)
return me["email"].(string)
}
// verifyDomain answers the TXT lookup with record and verifies the domain.
func verifyDomain(t *testing.T, owner *browser, pageID string, record map[string]any) {
t.Helper()
saved := *api.LookupTXT
t.Cleanup(func() { *api.LookupTXT = saved })
*api.LookupTXT = func(_ context.Context, name string) ([]string, error) {
if name == record["name"] {
return []string{"something else", record["value"].(string)}, nil
}
return nil, errors.New("no such record")
}
st, body := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil)
expect(t, "verify domain", st, body, http.StatusNoContent, "")
}
func TestStatusPageGroupsAndDetails(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer down.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("spg")+".test", uniq("spg-"))
// Create monitor groups to test importing the hierarchy later.
st, mgRoot := owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "Core"})
if st != http.StatusCreated {
t.Fatalf("create monitor root group = %d %v, want 201", st, mgRoot)
}
st, mgChild := owner.do("POST", "/api/v1/org/groups", map[string]any{
"name": "Edge",
"parent_id": mgRoot["id"],
})
if st != http.StatusCreated {
t.Fatalf("create monitor child group = %d %v, want 201", st, mgChild)
}
newMonitor := func(name, target string, groupID any) string {
t.Helper()
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": name,
"type": "http",
"target": target,
"interval_seconds": 60,
"confirmations": 1,
"regions": []string{region},
"group_id": groupID,
})
if st != http.StatusCreated {
t.Fatalf("create monitor %q = %d %v, want 201", name, st, body)
}
return body["id"].(string)
}
webID := newMonitor("web", up.URL, mgChild["id"])
apiID := newMonitor("api", down.URL, mgRoot["id"])
// Heartbeat monitors record NULL latency_ms; ensure HourlyBuckets handles them
// cleanly when show_component_details is enabled.
st, hbBody := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "nightly-job",
"type": "heartbeat",
"interval_seconds": 3600,
})
if st != http.StatusCreated {
t.Fatalf("create heartbeat monitor = %d %v, want 201", st, hbBody)
}
hbResp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+hbBody["target"].(string), "text/plain", strings.NewReader(""))
if err != nil {
t.Fatalf("ping heartbeat error = %v", err)
}
_ = hbResp.Body.Close()
slug := uniq("nested-")
st, pageBody := owner.do("POST", "/api/v1/org/statuspages", map[string]any{
"slug": slug,
"title": "Nested Status",
"published": true,
"show_component_details": false,
})
if st != http.StatusCreated {
t.Fatalf("create status page = %d %v, want 201", st, pageBody)
}
pageID := pageBody["id"].(string)
// Nested status page groups CRUD + cycle & depth validation.
st, gParent := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
"name": "Platform",
"position": 0,
})
if st != http.StatusCreated {
t.Fatalf("create page parent group = %d %v, want 201", st, gParent)
}
parentID := gParent["id"].(string)
st, gChild := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
"name": "Public Services",
"parent_id": parentID,
"position": 0,
})
if st != http.StatusCreated {
t.Fatalf("create page child group = %d %v, want 201", st, gChild)
}
childID := gChild["id"].(string)
// Cycle rejection.
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/groups/"+parentID, map[string]any{
"name": "Platform",
"parent_id": childID,
})
expect(t, "group cycle", st, body, http.StatusUnprocessableEntity, "group_cycle")
// Assign monitors into nested groups.
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{
"monitors": []map[string]any{
{"monitor_id": webID, "group_id": childID, "label": "Website"},
{"monitor_id": apiID, "group_id": parentID, "label": "API"},
},
})
expect(t, "assign grouped monitors", st, body, http.StatusNoContent, "")
waitFor(t, 10*time.Second, "incident for failing monitor", func() bool {
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
return len(b["incidents"].([]any)) == 1
})
platform := e.statuspageClient(t, nil)
snap, err := platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page() error = %v", err)
}
if snap.ShowDetails {
t.Fatalf("snap.ShowDetails = true, want false")
}
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Platform" ||
snap.Sections[0].Total != 2 || snap.Sections[0].Status != agentapi.PageDegraded ||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Public Services" ||
snap.Sections[0].Children[0].Status != agentapi.PageOperational {
t.Fatalf("nested sections = %+v, want Platform(degraded,2) -> Public Services(operational,1)", snap.Sections)
}
if snap.Sections[0].Components[0].Details != nil {
t.Errorf("component Details populated when show_component_details=false")
}
// Enable show_component_details and verify snapshot details & privacy.
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{
"slug": slug,
"title": "Nested Status",
"published": true,
"show_component_details": true,
})
if st != http.StatusOK || body["show_component_details"] != true {
t.Fatalf("enable show_component_details = %d %v, want 200 with true", st, body)
}
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(with details) error = %v", err)
}
if !snap.ShowDetails {
t.Fatalf("snap.ShowDetails = false, want true")
}
comp, ok := snap.ComponentByID(apiID)
if !ok || comp.Details == nil {
t.Fatalf("ComponentByID(%s) = (%+v, %t), want component with Details", apiID, comp, ok)
}
if len(comp.Details.Hours) != 24 || len(comp.Details.Regions) != 1 {
t.Errorf("component details hours/regions = %d/%d, want 24/1", len(comp.Details.Hours), len(comp.Details.Regions))
}
raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status", "HTTP 500"} {
if strings.Contains(string(raw), secret) {
t.Errorf("snapshot with details leaks %q", secret)
}
}
// Verify live status page server renders component detail page.
cat, _ := i18n.Load()
spSrv, err := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
if err != nil {
t.Fatalf("statuspage.New() error = %v", err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
spSrv.Mount(router)
req := httptest.NewRequest(http.MethodGet, "/"+slug+"/components/"+apiID, nil)
req.Host = "status.test"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "API") || !strings.Contains(rec.Body.String(), "Last 24 hours") {
t.Errorf("GET detail page = %d, want 200 with component details", rec.Code)
}
// Static export has no broken /components/ links and embeds inline details.
resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export")
if err != nil {
t.Fatalf("export request error = %v", err)
}
exported, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK || strings.Contains(string(exported), "/components/") || !strings.Contains(string(exported), "Show details") {
t.Errorf("export status = %d, want inline details without /components/ links", resp.StatusCode)
}
// Delete child group: monitor moves up to parent group.
st, body = owner.do("DELETE", "/api/v1/org/statuspages/"+pageID+"/groups/"+childID, nil)
expect(t, "delete child group", st, body, http.StatusNoContent, "")
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(after delete) error = %v", err)
}
if len(snap.Sections) != 1 || len(snap.Sections[0].Components) != 2 || len(snap.Sections[0].Children) != 0 {
t.Errorf("after deleting child group, sections = %+v, want 2 monitors under Platform", snap.Sections)
}
// Import monitor groups copies Core -> Edge and re-assigns monitors.
st, imported := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups/import", nil)
if st != http.StatusOK || len(imported["groups"].([]any)) != 2 {
t.Fatalf("import groups = %d %v, want 200 with 2 groups", st, imported)
}
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(after import) error = %v", err)
}
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Core" ||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Edge" {
t.Errorf("imported sections = %+v, want Core -> Edge", snap.Sections)
}
// Console editor shows new controls.
st, _, html := owner.page("/statuspages/" + pageID)
for _, want := range []string{`name="show_component_details"`, `/groups/import`, `data-field="group_id"`} {
if st != http.StatusOK || !strings.Contains(html, want) {
t.Errorf("editor HTML = %d, missing %q", st, want)
}
}
}