Files
uptimesebi/internal/statuspage/public.go
T
Sebastian UnterschützandClaude Opus 5.5 2d4bd10c9b
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m8s
ci / test (pull_request) Successful in 13m45s
ci / build (pull_request) Successful in 19m0s
ci / image (pull_request) Successful in 6m5s
feat(notify): name regions and link the console in alerts; consent to subscribe
Alert mails and chat messages named regions by id. They now show the
region's name and mails link the monitor in the console.

Visitors of a status page accept the platform's terms and the page's
privacy policy, where set, before they can subscribe to it; the status
page server and the API both check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 20:16:28 +01:00

419 lines
14 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package statuspage
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"errors"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Besides the page itself, every page has an RSS feed, a small read-only
// JSON API and, where the organization allows it, email subscriptions.
// Feed and API are served from the cached snapshot like the page;
// subscriptions are passed on to the API.
type routeKind int
const (
routePage routeKind = iota
routeLegal
routeComponent
routeFeed
routeAPI
routeSubscribe
routeConfirm
routeUnsubscribe
)
// posts reports whether the route takes form posts.
func (k routeKind) posts() bool {
return k == routeSubscribe || k == routeConfirm || k == routeUnsubscribe
}
type route struct {
kind routeKind
// arg is the legal document, component or API resource.
arg string
}
// apiResources are the resources of the page API, below api/v1/.
var apiResources = map[string]bool{"status": true, "summary": true, "components": true, "incidents": true}
// routeOf matches the path below a page's base.
func routeOf(parts []string) (route, bool) {
switch {
case len(parts) == 0:
return route{kind: routePage}, true
case len(parts) == 1 && parts[0] == "feed.rss":
return route{kind: routeFeed}, true
case len(parts) == 1 && parts[0] == "subscribe":
return route{kind: routeSubscribe}, true
case len(parts) == 2 && parts[0] == "subscribe" && parts[1] == "confirm":
return route{kind: routeConfirm}, true
case len(parts) == 1 && parts[0] == "unsubscribe":
return route{kind: routeUnsubscribe}, true
case len(parts) == 3 && parts[0] == "api" && parts[1] == "v1" && apiResources[parts[2]]:
return route{kind: routeAPI, arg: parts[2]}, true
case len(parts) == 1 && parts[0] != "" && parts[0] != "api":
return route{kind: routeLegal, arg: parts[0]}, true
case len(parts) == 2 && parts[0] == "components" && parts[1] != "":
return route{kind: routeComponent, arg: parts[1]}, true
}
return route{}, false
}
// Requests per visitor address and window, beyond which the server
// answers 429: feed and API are cheap but invite polling loops, and every
// subscription request costs the API a mail.
const (
readsPerMinute = 60
subscribesPer10Min = 5
tokenActionsPer10Min = 20
// maxTracked bounds the addresses a limiter remembers per window.
maxTracked = 100_000
)
// windowLimiter counts requests per key in fixed windows.
type windowLimiter struct {
max int
window time.Duration
mu sync.Mutex
start time.Time
counts map[string]int
}
func newWindowLimiter(max int, window time.Duration) *windowLimiter {
return &windowLimiter{max: max, window: window, counts: map[string]int{}}
}
func (l *windowLimiter) allow(key string, now time.Time) bool {
l.mu.Lock()
defer l.mu.Unlock()
if now.Sub(l.start) >= l.window {
clear(l.counts)
l.start = now
}
n, seen := l.counts[key]
if !seen && len(l.counts) >= maxTracked {
// Memory stays bounded during a flood from many addresses; the
// API's own limits still apply to subscriptions.
return true
}
l.counts[key] = n + 1
return n < l.max
}
// limiters holds the server's rate limits per kind of route.
type limiters struct {
reads, subscribes, tokens *windowLimiter
}
func newLimiters() limiters {
return limiters{
reads: newWindowLimiter(readsPerMinute, time.Minute),
subscribes: newWindowLimiter(subscribesPer10Min, 10*time.Minute),
tokens: newWindowLimiter(tokenActionsPer10Min, 10*time.Minute),
}
}
func (s *Server) limiterFor(k routeKind) *windowLimiter {
switch k {
case routeFeed, routeAPI:
return s.limits.reads
case routeSubscribe:
return s.limits.subscribes
case routeConfirm, routeUnsubscribe:
return s.limits.tokens
}
return nil
}
// pageURL is the absolute address of the page, as the visitor reached it.
func pageURL(c *gin.Context, base string) string {
scheme := "http"
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
scheme = "https"
}
return scheme + "://" + c.Request.Host + base
}
// RSS 2.0, with the feed's own address as Atom link as validators ask.
type rssFeed struct {
XMLName xml.Name `xml:"rss"`
Version string `xml:"version,attr"`
Atom string `xml:"xmlns:atom,attr"`
Channel rssChannel `xml:"channel"`
}
type rssChannel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language,omitempty"`
LastBuildDate string `xml:"lastBuildDate"`
Self atomLink `xml:"atom:link"`
Items []rssItem `xml:"item"`
}
type atomLink struct {
Href string `xml:"href,attr"`
Rel string `xml:"rel,attr"`
Type string `xml:"type,attr"`
}
type rssItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
GUID rssGUID `xml:"guid"`
PubDate string `xml:"pubDate"`
}
type rssGUID struct {
Value string `xml:",chardata"`
IsPermaLink bool `xml:"isPermaLink,attr"`
}
// serveFeed renders the page's incidents and planned maintenance as RSS.
func (s *Server) serveFeed(c *gin.Context, e entry, base string) {
s.localizeRequest(c)
ctx := c.Request.Context()
snap := e.Snap.WithMaintenance(s.now())
link := pageURL(c, base)
feed := rssFeed{Version: "2.0", Atom: "http://www.w3.org/2005/Atom", Channel: rssChannel{
Title: snap.Title, Link: link, Language: i18n.Lang(ctx),
Description: i18n.T(ctx, "page.feed.description", "Page", snap.Title),
LastBuildDate: snap.GeneratedAt.UTC().Format(time.RFC1123Z),
Self: atomLink{Href: link + "feed.rss", Rel: "self", Type: "application/rss+xml"},
}}
for _, inc := range snap.Incidents {
title := inc.Title
if title == "" {
title = inc.Component
}
at, status := inc.StartedAt, i18n.T(ctx, "incidents.ongoing")
if inc.ResolvedAt != nil {
at, status = *inc.ResolvedAt, i18n.T(ctx, "incidents.resolved")
}
var desc []string
if len(inc.Updates) > 0 {
u := inc.Updates[0]
if u.At.After(at) {
at = u.At
}
status = u.StatusName
if status == "" {
status = i18n.T(ctx, "incident.status."+u.Status)
}
}
for _, u := range inc.Updates {
name := u.StatusName
if name == "" {
name = i18n.T(ctx, "incident.status."+u.Status)
}
desc = append(desc, u.At.UTC().Format("2006-01-02 15:04")+" UTC · "+name+": "+u.Message)
}
if title != inc.Component {
desc = append([]string{inc.Component}, desc...)
}
id := inc.ID
if id == "" {
id = digest(inc.Component, inc.StartedAt.String())
}
feed.Channel.Items = append(feed.Channel.Items, rssItem{
Title: title + " – " + status, Link: link, Description: strings.Join(desc, "\n\n"),
GUID: rssGUID{Value: "incident-" + id}, PubDate: at.UTC().Format(time.RFC1123Z),
})
}
for _, m := range snap.Maintenance {
feed.Channel.Items = append(feed.Channel.Items, rssItem{
Title: i18n.T(ctx, "page.feed.maintenance", "Title", m.Title), Link: link,
Description: m.Start.UTC().Format("2006-01-02 15:04") + " – " + m.End.UTC().Format("2006-01-02 15:04") + " UTC · " +
strings.Join(m.Components, ", ") + "\n\n" + m.Description,
GUID: rssGUID{Value: "maintenance-" + digest(m.Title, m.Start.String())},
PubDate: m.Start.UTC().Format(time.RFC1123Z),
})
}
out, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Header("Cache-Control", "public, max-age=60")
c.Data(http.StatusOK, "application/rss+xml; charset=utf-8", append([]byte(xml.Header), out...))
}
func digest(parts ...string) string {
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
return hex.EncodeToString(sum[:8])
}
// apiPage describes the page in API answers.
type apiPage struct {
Title string `json:"title"`
URL string `json:"url"`
Status string `json:"status"`
UpdatedAt time.Time `json:"updated_at"`
// Stale is set while the page cannot reach its source and shows an
// older state.
Stale bool `json:"stale,omitempty"`
}
// apiComponent is a component in API answers.
type apiComponent struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Group string `json:"group,omitempty"`
Status string `json:"status"`
// Uptime90d is the share of successful checks over 90 days, -1
// without data.
Uptime90d float64 `json:"uptime_90d"`
}
func apiComponents(sections []agentapi.Section, group string) []apiComponent {
out := []apiComponent{}
for _, sec := range sections {
g := group
if sec.Name != "" {
g = strings.TrimPrefix(group+" / "+sec.Name, " / ")
}
for _, comp := range sec.Components {
out = append(out, apiComponent{ID: comp.ID, Name: comp.Name, Group: g, Status: comp.Status, Uptime90d: comp.Uptime})
}
out = append(out, apiComponents(sec.Children, g)...)
}
return out
}
// serveAPI answers the page's read-only JSON API.
func (s *Server) serveAPI(c *gin.Context, e entry, resource, base string) {
now := s.now()
snap := e.Snap.WithMaintenance(now)
page := apiPage{
Title: snap.Title, URL: pageURL(c, base), Status: snap.Status, UpdatedAt: snap.GeneratedAt,
Stale: now.Sub(e.Fetched) > staleNoticeAfter,
}
incidents := snap.Incidents
if incidents == nil {
incidents = []agentapi.PageIncident{}
}
maintenance := append(snap.Ongoing(now), snap.Upcoming(now)...)
if maintenance == nil {
maintenance = []agentapi.PageMaintenance{}
}
var body any
switch resource {
case "status":
body = gin.H{"page": page}
case "components":
body = gin.H{"page": page, "components": apiComponents(snap.Sections, "")}
case "incidents":
body = gin.H{"page": page, "incidents": incidents}
default:
open := []agentapi.PageIncident{}
for _, inc := range incidents {
if inc.ResolvedAt == nil {
open = append(open, inc)
}
}
body = gin.H{"page": page, "components": apiComponents(snap.Sections, ""), "incidents": open, "maintenance": maintenance}
}
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Cache-Control", "public, max-age=30")
c.JSON(http.StatusOK, body)
}
// Subscriptions passes subscription requests on; *agentapi.Client
// implements it. Without it the server offers no subscriptions.
type Subscriptions interface {
Subscribe(ctx context.Context, r agentapi.SubscribeRequest) error
ConfirmSubscription(ctx context.Context, token string) (agentapi.SubscriptionInfo, error)
Unsubscribe(ctx context.Context, token string) (agentapi.SubscriptionInfo, error)
}
// serveSubscription handles the subscription form and the links mailed to
// subscribers. Links only show a button; acting on them takes a post, so
// mail scanners opening links neither confirm nor end subscriptions.
func (s *Server) serveSubscription(c *gin.Context, e entry, kind routeKind, host, slug, base string, a web.PublicAssets) {
subs, ok := s.src.(Subscriptions)
if !ok || (kind == routeSubscribe && !e.Snap.Subscribe) {
c.Status(http.StatusNotFound)
return
}
s.localizeRequest(c)
ctx := c.Request.Context()
c.Header("Cache-Control", "no-store")
a.NoRefresh = true
snap := e.Snap
notice := func(status int, title, msg string, form *web.NoticeForm) {
web.Render(c, status, web.PublicNoticePage(snap, a, title, msg, form))
}
token := c.PostForm("token")
if token == "" {
token = c.Query("token")
}
switch {
case kind == routeSubscribe && c.Request.Method != http.MethodPost:
c.Redirect(http.StatusSeeOther, base+"#subscribe")
case kind == routeSubscribe && c.PostForm("accept") == "" && len(web.SubscribeConsent(snap, base)) > 0:
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.accept_required"), nil)
case kind == routeSubscribe:
err := subs.Subscribe(ctx, agentapi.SubscribeRequest{
Host: host, Slug: slug, Email: c.PostForm("email"), IP: c.ClientIP(),
Locale: c.GetHeader("Accept-Language"), PageURL: pageURL(c, base), Accepted: true,
})
switch {
case err == nil:
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.sent_title"), i18n.T(ctx, "page.subscribe.sent"), nil)
case errors.Is(err, agentapi.ErrInvalidInput):
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.invalid"), nil)
case errors.Is(err, agentapi.ErrRateLimited):
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
default:
if !errors.Is(err, agentapi.ErrNotFound) {
s.log.WarnContext(ctx, "passing on a subscription failed", "error", err)
}
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
}
case token == "":
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
case kind == routeConfirm && c.Request.Method != http.MethodPost:
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.confirm_title"), i18n.T(ctx, "page.subscribe.confirm_intro", "Page", snap.Title),
&web.NoticeForm{Action: base + "subscribe/confirm", Token: token, Button: i18n.T(ctx, "page.subscribe.confirm_button")})
case kind == routeUnsubscribe && c.Request.Method != http.MethodPost:
notice(http.StatusOK, i18n.T(ctx, "page.unsubscribe.title"), i18n.T(ctx, "page.unsubscribe.intro", "Page", snap.Title),
&web.NoticeForm{Action: base + "unsubscribe", Token: token, Button: i18n.T(ctx, "page.unsubscribe.button")})
default:
act, title, done := subs.ConfirmSubscription, "page.subscribe.confirmed_title", "page.subscribe.confirmed"
if kind == routeUnsubscribe {
// Also the one-click unsubscribe of mail programs (RFC 8058),
// which posts to the link itself.
act, title, done = subs.Unsubscribe, "page.unsubscribe.done_title", "page.unsubscribe.done"
}
info, err := act(ctx, token)
switch {
case err == nil:
notice(http.StatusOK, i18n.T(ctx, title), i18n.T(ctx, done, "Email", info.Email, "Page", info.PageTitle), nil)
case errors.Is(err, agentapi.ErrNotFound):
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
case errors.Is(err, agentapi.ErrRateLimited):
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
default:
s.log.WarnContext(ctx, "passing on a subscription link failed", "error", err)
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
}
}
}