The admin panel lists every published status page, and every suspended page, organization or account, with the organization and owner behind it, searchable by title, address, organization or email. Each can be suspended with a reason, reinstated, or deleted. A suspended page is not served; status page servers drop it when they next ask. A suspended organization's monitors leave the schedule, its pages go offline, heartbeat pings and Alertmanager webhooks are no longer recorded, and its members and API tokens get 403 org_suspended; the console explains why. Reinstating restarts heartbeat waits so they do not fire at once. A suspended account is signed out everywhere and can neither sign in nor use its tokens; only someone who knows the password learns of the suspension. Platform admins cannot be suspended or deleted. Account deletion shares its logic with the GDPR erasure, including the refusal while the account owns shared organizations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
788 lines
23 KiB
Go
788 lines
23 KiB
Go
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
|
|
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
|
|
}
|
|
if planned, err = maintenanceFor(ctx, q, ids); err != nil {
|
|
return err
|
|
}
|
|
docs, err := q.LegalDocuments(ctx, &page.OrgID)
|
|
snap.Legal = mergeLegal(docs)
|
|
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)
|
|
for _, i := range incidents {
|
|
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt})
|
|
}
|
|
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, "</"):
|
|
// 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"`
|
|
ShowComponentDetails bool `json:"show_component_details"`
|
|
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"`
|
|
// Suspended is set when platform admins took the page offline; it is
|
|
// not served whatever Published says.
|
|
Suspended bool `json:"suspended,omitempty"`
|
|
SuspendedReason string `json:"suspended_reason,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, ShowComponentDetails: p.ShowComponentDetails,
|
|
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
|
|
Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason,
|
|
}
|
|
_ = 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, ShowComponentDetails: req.ShowComponentDetails,
|
|
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, ShowComponentDetails: req.ShowComponentDetails, 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"`
|
|
GroupID *uuid.UUID `json:"group_id"`
|
|
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
|
|
}
|
|
existingGroups, err := q.ListStatusPageGroups(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
groupsByID := make(map[uuid.UUID]store.StatusPageGroup, len(existingGroups))
|
|
topByName := map[string]store.StatusPageGroup{}
|
|
var nextPos int32
|
|
for _, g := range existingGroups {
|
|
groupsByID[g.ID] = g
|
|
if g.ParentID == nil {
|
|
topByName[g.Name] = g
|
|
if g.Position >= 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
|
|
}
|