package api import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "math" "net" "net/http" "net/url" "regexp" "slices" "strings" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "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, ShowDetails: page.ShowComponentDetails, Sections: []agentapi.Section{}, Incidents: []agentapi.PageIncident{}, GeneratedAt: time.Now(), } _ = json.Unmarshal(page.Theme, &snap.Theme) var ( listed []store.StatusPageMonitorsRow pageGroups []store.StatusPageGroup latest []store.LatestResultsRow open []store.Incident daily []store.DailyBucketsForMonitorsRow hourly []store.HourlyBucketsRow regions []store.Region incidents []store.Incident updates []store.PublicIncidentUpdatesRow planned map[uuid.UUID][]store.MaintenanceWindow ) 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 } if pageGroups, err = q.ListStatusPageGroups(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 } if page.ShowComponentDetails { if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{ OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), }); err != nil { return err } if regions, err = q.ListVisibleRegions(ctx); err != nil { return err } } if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil { return err } incidentIDs := make([]uuid.UUID, len(incidents)) for i, inc := range incidents { incidentIDs[i] = inc.ID } if updates, err = q.PublicIncidentUpdates(ctx, incidentIDs); err != nil { return err } if planned, err = maintenanceFor(ctx, q, ids); err != nil { return err } docs, err := q.LegalDocuments(ctx, &page.OrgID) // Visitors of status pages accept no terms. snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" }) return err }) if err != nil { return snap, err } failing := map[uuid.UUID]int{} reported := map[uuid.UUID]int{} latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{} for _, l := range latest { reported[l.MonitorID]++ if !l.Ok { failing[l.MonitorID]++ } latestByMonitor[l.MonitorID] = append(latestByMonitor[l.MonitorID], l) } 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}) } hourlyByMonitor := map[uuid.UUID][]web.Bucket{} for _, h := range hourly { hourlyByMonitor[h.MonitorID] = append(hourlyByMonitor[h.MonitorID], web.Bucket{ Start: h.Bucket, Total: h.Total, OK: h.OkCount, Latency: h.AvgLatencyMs, }) } regionNames := make(map[string]string, len(regions)) for _, r := range regions { regionNames[r.ID.String()] = r.Name } names := map[uuid.UUID]string{} var states []string var ungrouped []agentapi.Component byGroup := map[uuid.UUID][]agentapi.Component{} for _, m := range listed { name := m.Label if name == "" { name = m.MonitorName } names[m.MonitorID] = name uptime90 := web.Uptime(days[m.MonitorID]) comp := agentapi.Component{ ID: m.MonitorID.String(), Name: name, Uptime: uptime90, 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 page.ShowComponentDetails { comp.Details = buildComponentDetails( days[m.MonitorID], hourlyByMonitor[m.MonitorID], latestByMonitor[m.MonitorID], regionNames, uptime90, now, ) } states = append(states, comp.Status) if m.GroupID != nil { byGroup[*m.GroupID] = append(byGroup[*m.GroupID], comp) } else { ungrouped = append(ungrouped, comp) } } if len(ungrouped) > 0 { snap.Sections = append(snap.Sections, agentapi.Section{Name: "", Components: ungrouped}) } snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...) snap.Status = agentapi.Summarize(states) snap.Maintenance = pageMaintenance(planned, names, now) updatesOf := map[uuid.UUID][]agentapi.PageIncidentUpdate{} for _, u := range updates { updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{Status: u.Status, Message: u.Message, At: u.CreatedAt}) } for _, i := range incidents { snap.Incidents = append(snap.Incidents, agentapi.PageIncident{ Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Title: i.Title, Status: incidentStatus(i), Updates: updatesOf[i.ID], }) } return snap, nil } // buildPageSections turns a status page's group tree and grouped components // into recursive public sections, omitting subtrees with no components. func buildPageSections(tree pageGroupTree, byGroup map[uuid.UUID][]agentapi.Component) []agentapi.Section { var build func(id uuid.UUID) (agentapi.Section, []string) build = func(id uuid.UUID) (agentapi.Section, []string) { g := tree.byID[id] sec := agentapi.Section{Name: g.Name, Components: byGroup[id]} var states []string for _, c := range sec.Components { states = append(states, c.Status) } sec.Total = len(sec.Components) for _, childID := range tree.children[id] { childSec, childStates := build(childID) if childSec.Total == 0 { continue } sec.Children = append(sec.Children, childSec) sec.Total += childSec.Total states = append(states, childStates...) } if sec.Total > 0 { sec.Status = agentapi.Summarize(states) } return sec, states } var out []agentapi.Section for _, rootID := range tree.roots { sec, _ := build(rootID) if sec.Total > 0 { out = append(out, sec) } } return out } func buildComponentDetails( daily []web.Bucket, hourly []web.Bucket, latest []store.LatestResultsRow, regionNames map[string]string, uptime90 float64, now time.Time, ) *agentapi.ComponentDetails { since7d := now.UTC().AddDate(0, 0, -7) since30d := now.UTC().AddDate(0, 0, -30) var d7, d30 []web.Bucket for _, b := range daily { if !b.Start.Before(since30d) { d30 = append(d30, b) } if !b.Start.Before(since7d) { d7 = append(d7, b) } } byHour := make(map[int64]web.Bucket, len(hourly)) for _, b := range hourly { byHour[web.AlignBucket(b.Start.UTC(), time.Hour).Unix()] = b } endHour := web.AlignBucket(now.UTC(), time.Hour) hours := make([]agentapi.HourBucket, 24) for i := range hours { ts := endHour.Add(-time.Duration(23-i) * time.Hour) hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1} if b, ok := byHour[ts.Unix()]; ok && b.Total > 0 { hours[i].Uptime = float64(b.OK) / float64(b.Total) hours[i].AvgLatencyMS = int(math.Round(float64(b.Latency))) } } regs := make([]agentapi.ComponentRegion, 0, len(latest)) for _, l := range latest { name := regionNames[l.Region] if name == "" { name = l.Region } status := agentapi.PageOperational if !l.Ok { status = agentapi.PageOutage } var latency int if l.LatencyMs != nil && *l.LatencyMs > 0 { latency = int(*l.LatencyMs) } regs = append(regs, agentapi.ComponentRegion{Name: name, Status: status, LatencyMS: latency}) } slices.SortFunc(regs, func(a, b agentapi.ComponentRegion) int { return strings.Compare(a.Name, b.Name) }) return &agentapi.ComponentDetails{ SLA24h: web.Uptime(hourly), SLA7d: web.Uptime(d7), SLA30d: web.Uptime(d30), SLA90d: uptime90, Hours: hours, Regions: regs, } } 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=10000"` Published bool `json:"published"` ShowComponentDetails bool `json:"show_component_details"` 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, " element; "= nextPos { nextPos = g.Position + 1 } } } if err := q.ClearStatusPageMonitors(ctx, id); err != nil { return err } for i, m := range req.Monitors { groupID, section, err := resolvePageMonitorGroup(ctx, q, id, p.Org.ID, m, groupsByID, topByName, &nextPos) if err != nil { return err } err = q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{ PageID: id, MonitorID: m.MonitorID, OrgID: p.Org.ID, Section: section, GroupID: groupID, Label: strings.TrimSpace(m.Label), Position: int32(i), }) if err != nil { return err } } return nil }) var pgErr *pgconn.PgError switch { case errors.Is(err, pgx.ErrNoRows): fail(c, http.StatusNotFound, "not_found") case errors.As(err, &pgErr) && pgErr.Code == "23503" && strings.Contains(pgErr.ConstraintName, "group_id"): fail(c, http.StatusUnprocessableEntity, "invalid_group") 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.WithMaintenance(time.Now()), web.PublicAssets{InlineCSS: css, Now: time.Now()})) } // pageMaintenance lists the occurrences affecting the page's components // from an hour ago, so a snapshot cached just before still knows about // maintenance in progress, to two weeks ahead. func pageMaintenance(planned map[uuid.UUID][]store.MaintenanceWindow, names map[uuid.UUID]string, now time.Time) []agentapi.PageMaintenance { // Occurrences are matched by instant: time.Time values of the same // instant differ as map keys when their locations were loaded apart. type key struct { window uuid.UUID start int64 } byKey := map[key]*agentapi.PageMaintenance{} var order []key for monitor, ws := range planned { name, listed := names[monitor] if !listed { continue } for _, w := range ws { for _, occ := range ruleOf(w).Occurrences(now.Add(-time.Hour), now.Add(upcomingHorizon)) { k := key{w.ID, occ.Start.UnixNano()} m, ok := byKey[k] if !ok { m = &agentapi.PageMaintenance{Title: w.Title, Description: w.Description, Start: occ.Start, End: occ.End} byKey[k] = m order = append(order, k) } if !slices.Contains(m.Components, name) { m.Components = append(m.Components, name) } } } } out := make([]agentapi.PageMaintenance, 0, len(order)) for _, k := range order { m := *byKey[k] slices.Sort(m.Components) out = append(out, m) } slices.SortFunc(out, func(a, b agentapi.PageMaintenance) int { if c := a.Start.Compare(b.Start); c != 0 { return c } return strings.Compare(a.Title, b.Title) }) return out }