feat(api): manage status pages with themes, custom domains and export

Organizations build pages from their monitors, grouped into sections
with public names, choose an accent color, logo and CSS, verify custom
domains with a TXT record and export a page as one self-contained HTML
file. Assignments scoped to a single status page are honored.

Closes #21
Closes #23
Closes #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 08:39:00 +01:00
1 parent 2b72715a9d
commit a6126b353e
15 files changed
+2382 -228

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
package api_test
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"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.PageOutage || len(snap.Sections) != 2 || snap.Sections[1].Components[0].Name != "Public API" {
t.Errorf("snapshot = %+v, want outage with Frontend and Backend sections", 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 := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), []string{"status.test"})
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)
}
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, "")
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")
})
}
func editorEmail(b *browser) string {
_, me := b.do("GET", "/api/v1/me", nil)
return me["email"].(string)
}