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 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 } 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 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{} 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{} var states []string 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 } states = append(states, 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 = 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 } 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"` 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; "