ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m10s
ci / test (pull_request) Successful in 12m19s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s
Every console page that shows monitor status (monitors, incidents, monitor details, evidence) went through one loader that read, for all of the organization's monitors: - the newest result per monitor and region, by scanning a day of raw results; - the bars of the selected range, from raw results for ranges up to 24h, though only one page of monitors is shown; - when each monitor first reported, scanning two days of results. With 3000 monitors that took about a second, growing with the number of results. Now: - latest_results keeps the newest result per monitor and region, updated as results are stored (migration 00055 fills it from the last day); - bars are loaded only for the monitors a page shows; - first data is loaded per monitor on its page, and the monitor list asks only for the organization's earliest data, by index; - monitor, region and incident queries name the organization, so their indexes are used instead of row security filtering whole tables. Public status pages also read only their own monitors' latest results and hourly buckets instead of the whole organization's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
929 lines
28 KiB
Go
929 lines
28 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/check"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
|
"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."
|
|
// domainChangesPerDay bounds how often an organization may set a new
|
|
// custom domain.
|
|
domainChangesPerDay = 10
|
|
)
|
|
|
|
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
|
|
statuses customStatuses
|
|
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
|
|
}
|
|
rows, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: page.OrgID, Ids: ids})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
latest = make([]store.LatestResultsRow, len(rows))
|
|
for i, r := range rows {
|
|
latest[i] = store.LatestResultsRow(r)
|
|
}
|
|
if open, err = q.OpenIncidents(ctx, page.OrgID); 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), Ids: ids,
|
|
}); 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 statuses, err = loadCustomStatuses(ctx, q); 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{}
|
|
// A region that has not reported for longer than the evaluator waits
|
|
// is unknown, whatever its last result said.
|
|
staleBefore := map[uuid.UUID]time.Time{}
|
|
for _, m := range listed {
|
|
if !check.Passive(check.Type(m.MonitorType)) {
|
|
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
|
}
|
|
}
|
|
for _, l := range latest {
|
|
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
|
|
continue
|
|
}
|
|
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 {
|
|
st := statuses.info(&u.Status, u.StatusID)
|
|
updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{
|
|
Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Message: u.Message, At: u.CreatedAt,
|
|
})
|
|
}
|
|
for _, i := range incidents {
|
|
st := statuses.of(i)
|
|
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{
|
|
Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt,
|
|
Title: i.Title, Status: st.Key, StatusName: st.Name, StatusColor: st.Color, 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
|
|
}
|
|
page, ok, err := s.agentServes(ctx, agentOf(c), host, slug)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
snap, err := s.buildSnapshot(ctx, page)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
// The server sends the checksum of its copy; an unchanged page is not
|
|
// sent again.
|
|
etag := `"` + snap.Checksum() + `"`
|
|
c.Header("ETag", etag)
|
|
if c.GetHeader("If-None-Match") == etag {
|
|
c.Status(http.StatusNotModified)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, snap)
|
|
}
|
|
|
|
// agentServes finds the published page a status page agent serves at host
|
|
// or slug. The platform's servers leave the pages of organizations that
|
|
// serve them on their own servers to those, which receive only their own
|
|
// organization's pages.
|
|
func (s *Server) agentServes(ctx context.Context, a store.GetAgentByHashRow, host, slug *string) (store.StatusPage, bool, error) {
|
|
var (
|
|
page store.StatusPage
|
|
own bool
|
|
)
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
var err error
|
|
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
|
|
return err
|
|
}
|
|
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
|
|
return err
|
|
})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
return page, false, nil
|
|
case err != nil:
|
|
return page, false, err
|
|
}
|
|
return page, !own && (a.OrgID == nil || *a.OrgID == page.OrgID), nil
|
|
}
|
|
|
|
// agentPageIndex lists the pages the status page server serves.
|
|
func (s *Server) agentPageIndex(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
var rows []store.ServablePagesRow
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ServablePages(ctx, agentOf(c).OrgID)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]agentapi.PageRef, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"pages": out})
|
|
}
|
|
|
|
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"`
|
|
// CNAMERecord points CustomDomain at the platform's status page
|
|
// servers and proves control of it in one, where the platform knows
|
|
// their host.
|
|
CNAMERecord *dnsRecord `json:"cname_record,omitempty"`
|
|
// DomainMissingSince is set when the record of a verified domain has
|
|
// not been found since then; it is switched off a week later.
|
|
DomainMissingSince *time.Time `json:"domain_missing_since,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 (s *Server) 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}
|
|
if target := s.cnameFor(p.DomainToken); target != "" {
|
|
v.CNAMERecord = &dnsRecord{Name: *p.CustomDomain, Type: "CNAME", Value: target}
|
|
}
|
|
v.DomainMissingSince = p.DomainFailingSince
|
|
}
|
|
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, s.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 {
|
|
if err := reserve(ctx, q, p.Org.ID, s.orgLimits(ctx, p.Org).StatusPages, "status_page_limit", q.CountStatusPages); err != nil {
|
|
return err
|
|
}
|
|
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 failLimit(c, err) {
|
|
return
|
|
}
|
|
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, s.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, s.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
|
|
}
|
|
}
|
|
}
|
|
// A page beyond a lowered limit may keep its monitors but not add any.
|
|
if max := s.orgLimits(ctx, p.Org).MonitorsPerPage; max > 0 && len(req.Monitors) > max {
|
|
had, err := q.CountStatusPageMonitors(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if int64(len(req.Monitors)) > had {
|
|
return limitError{"page_monitor_limit", max}
|
|
}
|
|
}
|
|
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 failLimit(c, err):
|
|
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
|
|
limited := false
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
cur, err := q.GetStatusPage(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Every new domain may end in a certificate order; switching domains
|
|
// over and over would use up the CA's limits for everyone.
|
|
if domain != "" && domain != deref(cur.CustomDomain) {
|
|
ok, err := s.limiter.Allow(ctx, "domain_change:"+p.Org.ID.String(), domainChangesPerDay, 24*time.Hour)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok {
|
|
limited = true
|
|
return nil
|
|
}
|
|
}
|
|
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
|
|
return err
|
|
})
|
|
switch {
|
|
case limited:
|
|
fail(c, http.StatusTooManyRequests, "domain_changes_exceeded", "Count", domainChangesPerDay)
|
|
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, s.viewStatusPage(row))
|
|
}
|
|
}
|
|
|
|
// lookupTXT is replaced in tests.
|
|
var lookupTXT = net.DefaultResolver.LookupTXT
|
|
|
|
// verifyPageDomain looks for the CNAME or the TXT record now. 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
|
|
}
|
|
method := s.checkDomain(ctx, *row.CustomDomain, row.DomainToken)
|
|
if method == "" {
|
|
fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
|
|
return
|
|
}
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: id, Now: time.Now(), Method: method})
|
|
})
|
|
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
|
|
}
|