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

+1
View File
@@ -32,6 +32,7 @@ const (
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/pages", requireAgentKind("statuspage"), s.agentPage)
checker := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults)
+84
View File
@@ -31,6 +31,8 @@ func (s *Server) registerConsole(r gin.IRouter) {
r.GET("/monitors/:id/edit", s.orgPage("monitors.edit", authz.MonitorsWrite, s.monitorEditor))
r.GET("/incidents", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentsView))
r.GET("/settings/channels", s.orgPage("channels.title", authz.NotificationsRead, s.channelsView))
r.GET("/statuspages", s.orgPage("pages.title", "", s.statusPagesView))
r.GET("/statuspages/:id", s.orgPage("pages.title", "", s.statusPageEditor))
}
// dashboard is the landing page. Unlike other console pages it renders for
@@ -426,3 +428,85 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
}
return web.ChannelsPage(page, me, v), nil
}
func (s *Server) pageURL(p store.StatusPage) string {
if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
return "https://" + *p.CustomDomain + "/"
}
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
}
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListStatusPages(ctx)
return err
})
if err != nil {
return nil, err
}
v := web.PagesView{CanWrite: p.Grants.Can(authz.StatusPagesWrite)}
for _, r := range rows {
if !p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
continue
}
v.Pages = append(v.Pages, web.PageRow{
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
URL: s.pageURL(r), Domain: deref(r.CustomDomain),
})
}
return web.StatusPagesPage(page, me, v), nil
}
func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
id, err := uuid.Parse(c.Param("id"))
if err != nil || !p.Grants.Can(authz.StatusPagesWrite, pageResource(id)) {
return notFoundPage(c)
}
ctx := c.Request.Context()
var (
row store.StatusPage
listed []store.StatusPageMonitorsRow
monitors []store.Monitor
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if row, err = q.GetStatusPage(ctx, id); err != nil {
return err
}
if listed, err = q.StatusPageMonitors(ctx, id); err != nil {
return err
}
monitors, err = q.ListMonitors(ctx)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
return notFoundPage(c)
}
if err != nil {
return nil, err
}
v := viewStatusPage(row)
e := web.PageEditor{
ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
Published: row.Published, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
}
if v.DomainRecord != nil {
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
}
// Listed monitors keep their order; the rest follow alphabetically.
seen := map[uuid.UUID]bool{}
for _, l := range listed {
seen[l.MonitorID] = true
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: l.MonitorID.String(), Name: l.MonitorName, Included: true, Section: l.Section, Label: l.Label})
}
for _, m := range monitors {
if !seen[m.ID] {
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: m.ID.String(), Name: m.Name})
}
}
return web.StatusPageEditor(page, me, e), nil
}
+4
View File
@@ -0,0 +1,4 @@
package api
// LookupTXT lets tests replace DNS lookups for domain verification.
var LookupTXT = &lookupTXT
+10
View File
@@ -127,6 +127,16 @@ func (s *Server) Mount(r gin.IRouter) {
admin.POST("/agents", s.adminCreateAgent)
admin.DELETE("/agents/:id", s.adminDeleteAgent)
org.GET("/statuspages", s.listStatusPages)
org.POST("/statuspages", can(authz.StatusPagesWrite), s.createStatusPage)
page := org.Group("/statuspages/:id")
page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
+560
View File
@@ -0,0 +1,560 @@
package api
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"net"
"net/http"
"net/url"
"regexp"
"slices"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
const (
historyDays = 90
incidentLookback = 14 * 24 * time.Hour
// verifyPrefix is the label under which customers publish the TXT record
// proving control of a custom domain.
verifyPrefix = "_uptimesebi."
)
var (
slugRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,62}$`)
accentRE = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
domainRE2 = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
)
// buildSnapshot computes what the public sees of page.
func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) {
snap := agentapi.PageSnapshot{
Slug: page.Slug, Title: page.Title, Description: page.Description,
Sections: []agentapi.Section{}, Incidents: []agentapi.PageIncident{}, GeneratedAt: time.Now(),
}
_ = json.Unmarshal(page.Theme, &snap.Theme)
var (
listed []store.StatusPageMonitorsRow
latest []store.LatestResultsRow
open []store.Incident
daily []store.DailyBucketsForMonitorsRow
incidents []store.Incident
)
now := time.Now()
err := s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
var err error
if listed, err = q.StatusPageMonitors(ctx, page.ID); err != nil {
return err
}
ids := make([]uuid.UUID, len(listed))
for i, m := range listed {
ids[i] = m.MonitorID
}
if latest, err = q.LatestResults(ctx, page.OrgID); err != nil {
return err
}
if open, err = q.OpenIncidents(ctx); err != nil {
return err
}
if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
OrgID: page.OrgID, Ids: ids, Bucket: now.AddDate(0, 0, -historyDays),
}); err != nil {
return err
}
incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))})
return err
})
if err != nil {
return snap, err
}
failing := map[uuid.UUID]int{}
reported := map[uuid.UUID]int{}
for _, l := range latest {
reported[l.MonitorID]++
if !l.Ok {
failing[l.MonitorID]++
}
}
down := map[uuid.UUID]bool{}
for _, i := range open {
down[i.MonitorID] = true
}
days := map[uuid.UUID][]web.Bucket{}
for _, d := range daily {
days[d.MonitorID] = append(days[d.MonitorID], web.Bucket{Start: d.Bucket, Total: d.Total, OK: d.OkCount})
}
names := map[uuid.UUID]string{}
worst := agentapi.PageOperational
allUnknown := true
for _, m := range listed {
name := m.Label
if name == "" {
name = m.MonitorName
}
names[m.MonitorID] = name
comp := agentapi.Component{Name: name, Uptime: web.Uptime(days[m.MonitorID]), Days: dayHistory(days[m.MonitorID], now)}
switch {
case down[m.MonitorID]:
comp.Status = agentapi.PageOutage
case !m.Enabled || reported[m.MonitorID] == 0:
comp.Status = agentapi.PageUnknown
case failing[m.MonitorID] > 0:
comp.Status = agentapi.PageDegraded
default:
comp.Status = agentapi.PageOperational
}
if comp.Status != agentapi.PageUnknown {
allUnknown = false
}
worst = worse(worst, comp.Status)
if n := len(snap.Sections); n == 0 || snap.Sections[n-1].Name != m.Section {
snap.Sections = append(snap.Sections, agentapi.Section{Name: m.Section})
}
last := &snap.Sections[len(snap.Sections)-1]
last.Components = append(last.Components, comp)
}
snap.Status = worst
if allUnknown {
snap.Status = agentapi.PageUnknown
}
for _, i := range incidents {
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt})
}
return snap, nil
}
// worse returns the more severe state; unknown components do not make the
// whole page look broken.
func worse(a, b string) string {
rank := map[string]int{agentapi.PageOperational: 0, agentapi.PageUnknown: 0, agentapi.PageDegraded: 1, agentapi.PageOutage: 2}
if rank[b] > rank[a] {
return b
}
return a
}
func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day {
byDay := map[string]web.Bucket{}
for _, b := range buckets {
byDay[b.Start.UTC().Format(time.DateOnly)] = b
}
out := make([]agentapi.Day, historyDays)
start := now.UTC().AddDate(0, 0, -(historyDays - 1))
for i := range out {
d := start.AddDate(0, 0, i).Format(time.DateOnly)
out[i] = agentapi.Day{Date: d, Uptime: -1}
if b, ok := byDay[d]; ok && b.Total > 0 {
out[i].Uptime = float64(b.OK) / float64(b.Total)
}
}
return out
}
// agentPage serves a page snapshot to status page servers. Org-owned
// servers only receive their own org's pages.
func (s *Server) agentPage(c *gin.Context) {
ctx := c.Request.Context()
var host, slug *string
if h := strings.ToLower(strings.TrimSpace(c.Query("host"))); h != "" {
host = &h
} else if sl := strings.ToLower(strings.TrimSpace(c.Query("slug"))); sl != "" {
slug = &sl
} else {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
var page store.StatusPage
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
return err
})
a := agentOf(c)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
snap, err := s.buildSnapshot(ctx, page)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, snap)
}
type statusPageRequest struct {
Slug string `json:"slug" binding:"required,max=63"`
Title string `json:"title" binding:"required,max=200"`
Description string `json:"description" binding:"max=2000"`
Published bool `json:"published"`
Theme agentapi.Theme `json:"theme"`
}
func (r *statusPageRequest) normalize() string {
r.Slug = strings.ToLower(strings.TrimSpace(r.Slug))
r.Title = strings.TrimSpace(r.Title)
r.Description = strings.TrimSpace(r.Description)
t := &r.Theme
t.Accent, t.LogoURL = strings.TrimSpace(t.Accent), strings.TrimSpace(t.LogoURL)
switch {
case !slugRE.MatchString(r.Slug):
return "invalid_slug"
case r.Title == "":
return "invalid_input"
case t.Accent != "" && !accentRE.MatchString(t.Accent):
return "invalid_theme"
case len(t.CSS) > 20000 || strings.Contains(t.CSS, "</"):
// The CSS is embedded in a <style> element; "</" could close it.
return "invalid_theme"
}
if t.LogoURL != "" {
u, err := url.Parse(t.LogoURL)
if err != nil || u.Scheme != "https" || u.Host == "" {
return "invalid_theme"
}
}
return ""
}
type statusPageView struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
Published bool `json:"published"`
Theme agentapi.Theme `json:"theme"`
CustomDomain *string `json:"custom_domain"`
DomainVerified bool `json:"domain_verified"`
// DomainRecord is the TXT record that proves control of CustomDomain.
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
}
type dnsRecord struct {
Name string `json:"name"`
Type string `json:"type"`
Value string `json:"value"`
}
func viewStatusPage(p store.StatusPage) statusPageView {
v := statusPageView{
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description, Published: p.Published,
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
}
_ = json.Unmarshal(p.Theme, &v.Theme)
if p.CustomDomain != nil {
v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken}
}
return v
}
// pageResource is the scope of assignments limited to one status page.
func pageResource(id uuid.UUID) authz.Resource {
return authz.Resource{Type: authz.StatusPage, ID: id}
}
// canPage aborts unless the principal holds perm for the page in :id,
// organization-wide or through an assignment scoped to that page.
func canPage(perm authz.Permission) gin.HandlerFunc {
return func(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil || !current(c).Grants.Can(perm, pageResource(id)) {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Next()
}
}
func (s *Server) listStatusPages(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
var rows []store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListStatusPages(ctx)
return err
})
if err != nil {
internalError(c, err)
return
}
out := []statusPageView{}
for _, r := range rows {
if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
out = append(out, viewStatusPage(r))
}
}
c.JSON(http.StatusOK, gin.H{"pages": out})
}
func (s *Server) createStatusPage(c *gin.Context) {
var req statusPageRequest
if !bind(c, &req) {
return
}
if code := req.normalize(); code != "" {
fail(c, http.StatusUnprocessableEntity, code)
return
}
p := current(c)
ctx := c.Request.Context()
theme, _ := json.Marshal(req.Theme)
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
Published: req.Published, DomainToken: newDomainToken(), Theme: theme,
})
return err
})
if isUniqueViolation(err, "status_pages_slug_key") {
fail(c, http.StatusConflict, "slug_taken")
return
}
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, viewStatusPage(row))
}
func newDomainToken() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return "uptimesebi-verify=" + hex.EncodeToString(b)
}
func (s *Server) updateStatusPage(c *gin.Context) {
var req statusPageRequest
if !bind(c, &req) {
return
}
if code := req.normalize(); code != "" {
fail(c, http.StatusUnprocessableEntity, code)
return
}
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
theme, _ := json.Marshal(req.Theme)
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description, Published: req.Published, Theme: theme,
})
return err
})
switch {
case isUniqueViolation(err, "status_pages_slug_key"):
fail(c, http.StatusConflict, "slug_taken")
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, viewStatusPage(row))
}
}
func (s *Server) deleteStatusPage(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var n int64
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
n, err = q.DeleteStatusPage(ctx, id)
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
type pageMonitor struct {
MonitorID uuid.UUID `json:"monitor_id" binding:"required"`
Section string `json:"section" binding:"max=100"`
Label string `json:"label" binding:"max=200"`
}
type pageMonitorsRequest struct {
Monitors []pageMonitor `json:"monitors" binding:"max=200,dive"`
}
// setPageMonitors replaces the page's components; their order is the
// display order.
func (s *Server) setPageMonitors(c *gin.Context) {
var req pageMonitorsRequest
if !bind(c, &req) {
return
}
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, id); err != nil {
return err
}
if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
return err
}
for i, m := range req.Monitors {
err := q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{
PageID: id, MonitorID: m.MonitorID, OrgID: p.Org.ID,
Section: strings.TrimSpace(m.Section), Label: strings.TrimSpace(m.Label), Position: int32(i),
})
if err != nil {
return err
}
}
return nil
})
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
// Unknown monitors, monitors of other orgs and duplicates.
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
case err != nil:
internalError(c, err)
default:
c.Status(http.StatusNoContent)
}
}
type domainRequest struct {
Domain string `json:"domain" binding:"max=253"`
}
func (s *Server) setPageDomain(c *gin.Context) {
var req domainRequest
if !bind(c, &req) {
return
}
domain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Domain)), ".")
if domain != "" && !domainRE2.MatchString(domain) {
fail(c, http.StatusUnprocessableEntity, "invalid_domain")
return
}
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
return err
})
switch {
case isUniqueViolation(err, "status_pages_custom_domain_key"):
fail(c, http.StatusConflict, "domain_taken")
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, viewStatusPage(row))
}
}
// lookupTXT is replaced in tests.
var lookupTXT = net.DefaultResolver.LookupTXT
// verifyPageDomain checks the TXT record. Only verified domains are served,
// so nobody can claim a domain they do not control.
func (s *Server) verifyPageDomain(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
if !s.limit(c, "verify_domain:"+id.String(), 20, time.Hour) {
return
}
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.GetStatusPage(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
if row.CustomDomain == nil {
fail(c, http.StatusConflict, "no_domain")
return
}
records, err := lookupTXT(ctx, verifyPrefix+*row.CustomDomain)
if err != nil || !slices.Contains(records, row.DomainToken) {
fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
return
}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { return q.MarkDomainVerified(ctx, id) })
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// exportStatusPage returns the page as one self-contained HTML file that
// can be hosted anywhere. It reflects the moment of export.
func (s *Server) exportStatusPage(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.GetStatusPage(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
snap, err := s.buildSnapshot(ctx, row)
if err != nil {
internalError(c, err)
return
}
css, err := web.StylesheetText()
if err != nil {
internalError(c, err)
return
}
c.Header("Content-Disposition", `attachment; filename="`+row.Slug+`.html"`)
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, web.PublicAssets{InlineCSS: css}))
}
+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)
}