feat(statuspages): email subscriptions, RSS feed and a JSON API
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 9m5s
ci / lint (pull_request) Successful in 10m24s
ci / build (pull_request) Successful in 18m10s
ci / image (pull_request) Successful in 5m16s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 9m5s
ci / lint (pull_request) Successful in 10m24s
ci / build (pull_request) Successful in 18m10s
ci / image (pull_request) Successful in 5m16s
Visitors can subscribe to a page's incidents by email where the organization allows it. They confirm their address first; confirmation and unsubscribe links only show a button, so mail scanners do not act on them, and mails carry RFC 8058 one-click unsubscribe headers. Subscribers get a mail when an incident opens or resolves and for every public update. Every page also has an RSS feed of incidents and planned maintenance and a read-only JSON API (status, summary, components, incidents), both served from the cached snapshot. Abuse protection: status page servers limit feed and API reads, subscription requests and link actions per visitor; the API limits subscription requests per visitor, mailbox and page, and a new limit caps the subscriptions an organization's pages gain in seven days (platform default and per-organization override, 1000 in the cloud). Unconfirmed subscriptions count towards it and are deleted after a week. The fixed cap of 200 monitors per status page is gone; the configurable limit alone decides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
df39b765cb
commit
cca4e80e54
39 files changed
+4332
-1408
No files matched your search
@@ -53,6 +53,9 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||
sp.POST("/storage/lock", s.storageLock)
|
||||
sp.DELETE("/storage/lock", s.storageUnlock)
|
||||
sp.POST("/certificates", s.agentCertificate)
|
||||
sp.POST("/subscriptions", s.agentSubscribe)
|
||||
sp.POST("/subscriptions/confirm", s.agentConfirmSubscription)
|
||||
sp.POST("/subscriptions/unsubscribe", s.agentUnsubscribe)
|
||||
checker := g.Group("", requireAgentKind("checker"))
|
||||
checker.POST("/jobs", s.agentJobs)
|
||||
checker.POST("/results", s.agentResults)
|
||||
|
||||
@@ -99,6 +99,9 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.EnqueueSubscriberNotifications(ctx, store.EnqueueSubscriberNotificationsParams{IncidentID: inc.ID, Event: event}); err != nil {
|
||||
return err
|
||||
}
|
||||
routes, err := q.MonitorAlertRoutes(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -140,6 +143,8 @@ func (s *Server) RunNotifier(ctx context.Context) {
|
||||
case <-tick.C:
|
||||
for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil {
|
||||
}
|
||||
for s.deliverSubscriberBatch(ctx) == subscriberBatch && ctx.Err() == nil {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,6 +188,10 @@ var endpoints = []endpoint{
|
||||
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/subscribers", tag: "Status pages", summary: "List email subscribers", perm: "statuspages.write",
|
||||
description: "Counts of confirmed and pending subscribers and the newest 1000 of them.", resp: subscribersView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id/subscribers/:subscriber", tag: "Status pages", summary: "Remove an email subscriber", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/export", tag: "Status pages", summary: "Export the page as a single HTML file", perm: "statuspages.read",
|
||||
media: "text/html"},
|
||||
|
||||
|
||||
+45
-44
@@ -61,50 +61,51 @@ var auditActions = map[string]string{
|
||||
"POST /api/v1/invitations/:token/accept": "member.join",
|
||||
"POST /api/v1/invitations/:token/signup": "member.join",
|
||||
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"PUT /api/v1/org/monitors/order": "monitor.order",
|
||||
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
|
||||
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
|
||||
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"PUT /api/v1/org/monitors/order": "monitor.order",
|
||||
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
|
||||
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
|
||||
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"DELETE /api/v1/org/statuspages/:id/subscribers/:subscriber": "statuspage.subscriber_delete",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
|
||||
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
|
||||
+13
-1
@@ -1318,6 +1318,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
pageGroups []store.StatusPageGroup
|
||||
orgGroups []store.MonitorGroup
|
||||
monitors []store.Monitor
|
||||
subs subscribersView
|
||||
own bool
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
@@ -1337,6 +1338,9 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if subs, err = s.pageSubscribers(ctx, q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
@@ -1359,7 +1363,15 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
|
||||
}
|
||||
e.DomainChangesPerDay = domainChangesPerDay
|
||||
e.MonitorLimit = s.orgLimits(c.Request.Context(), p.Org).MonitorsPerPage
|
||||
limits := s.orgLimits(c.Request.Context(), p.Org)
|
||||
e.MonitorLimit = limits.MonitorsPerPage
|
||||
e.Subscriptions, e.MailAvailable, e.SubscriberLimit = row.Subscriptions, s.smtp != nil, limits.SubscribersPerWeek
|
||||
e.SubscribersConfirmed, e.SubscribersPending = subs.Confirmed, subs.Pending
|
||||
for _, sub := range subs.Subscribers {
|
||||
e.Subscribers = append(e.Subscribers, web.PageSubscriberRow{
|
||||
ID: sub.ID.String(), Email: sub.Email, Since: sub.CreatedAt.Local().Format("2006-01-02"), Pending: sub.ConfirmedAt == nil,
|
||||
})
|
||||
}
|
||||
if v.CNAMERecord != nil {
|
||||
e.CNAMEValue = v.CNAMERecord.Value
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -335,6 +336,8 @@ type exportStatusPage struct {
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
Groups []pageGroupView `json:"groups"`
|
||||
Monitors []exportPageMember `json:"monitors"`
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Subscribers []subscriberView `json:"subscribers"`
|
||||
}
|
||||
|
||||
type exportPageMember struct {
|
||||
@@ -529,10 +532,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
|
||||
})
|
||||
}
|
||||
subs, err := q.ListPageSubscribers(ctx, store.ListPageSubscribersParams{PageID: pg.ID, MaxRows: math.MaxInt32})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subscribers := []subscriberView{}
|
||||
for _, r := range subs {
|
||||
subscribers = append(subscribers, subscriberView{r.ID, r.Email, r.Locale, r.CreatedAt, r.ConfirmedAt})
|
||||
}
|
||||
x.StatusPages = append(x.StatusPages, exportStatusPage{
|
||||
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
|
||||
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
|
||||
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
|
||||
Subscriptions: pg.Subscriptions, Subscribers: subscribers,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
// tokens and incidents older than the daily aggregate.
|
||||
func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
|
||||
keep := s.cfg.Retention
|
||||
var counts [7]int64
|
||||
var counts [9]int64
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if keep.Housekeeping > 0 {
|
||||
@@ -78,16 +78,24 @@ func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
|
||||
if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
|
||||
return err
|
||||
}
|
||||
if counts[7], err = q.PurgeUnconfirmedSubscribers(ctx, now.Add(-subscriberWindow)); err != nil {
|
||||
return err
|
||||
}
|
||||
if keep.Housekeeping > 0 {
|
||||
if counts[8], err = q.PurgeSubscriberNotifications(ctx, now.Add(-keep.Housekeeping)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if keep.Daily > 0 {
|
||||
before := now.Add(-keep.Daily)
|
||||
counts[3], err = q.PurgeIncidents(ctx, &before)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err == nil && counts != [7]int64{} {
|
||||
if err == nil && counts != [9]int64{} {
|
||||
s.log.InfoContext(ctx, "housekeeping purged rows",
|
||||
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5],
|
||||
"unverified_accounts", counts[6])
|
||||
"unverified_accounts", counts[6], "unconfirmed_subscribers", counts[7], "subscriber_notifications", counts[8])
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -268,6 +268,13 @@ func (s *Server) addIncidentUpdate(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if public {
|
||||
if _, err := q.EnqueueSubscriberNotifications(ctx, store.EnqueueSubscriberNotificationsParams{
|
||||
IncidentID: d.inc.ID, UpdateID: &u.ID, Event: "update",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return q.RefreshIncidentStatus(ctx, d.inc.ID)
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
|
||||
+25
-15
@@ -38,11 +38,14 @@ type Limits struct {
|
||||
OrgsPerAccount int `json:"orgs_per_account"`
|
||||
// MonitorsPerPage limits the monitors one status page shows.
|
||||
MonitorsPerPage int `json:"monitors_per_page"`
|
||||
// SubscribersPerWeek limits the email subscriptions the organization's
|
||||
// status pages gain in seven days.
|
||||
SubscribersPerWeek int `json:"subscribers_per_week"`
|
||||
}
|
||||
|
||||
func (s *Server) defaultLimits() Limits {
|
||||
if s.cloud() {
|
||||
return Limits{OrgsPerAccount: 3}
|
||||
return Limits{OrgsPerAccount: 3, SubscribersPerWeek: 1000}
|
||||
}
|
||||
return Limits{}
|
||||
}
|
||||
@@ -82,6 +85,7 @@ func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
|
||||
override(&l.StatusPages, org.LimitStatusPages)
|
||||
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
|
||||
override(&l.MonitorsPerPage, org.LimitMonitorsPerPage)
|
||||
override(&l.SubscribersPerWeek, org.LimitSubscribersPerWeek)
|
||||
if org.LimitOwnRegionsCount != nil {
|
||||
l.OwnRegionsCount = *org.LimitOwnRegionsCount
|
||||
}
|
||||
@@ -192,7 +196,10 @@ type limitsRequest struct {
|
||||
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
|
||||
MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=200"`
|
||||
MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=1000000"`
|
||||
// SubscribersPerWeek is new email subscriptions per organization and
|
||||
// seven days.
|
||||
SubscribersPerWeek int `json:"subscribers_per_week" binding:"min=0,max=100000000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetLimits(c *gin.Context) {
|
||||
@@ -243,11 +250,12 @@ func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
|
||||
// orgLimitsRequest overrides limits for one organization; null follows the
|
||||
// platform default.
|
||||
type orgLimitsRequest struct {
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page" binding:"omitempty,min=0,max=200"`
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page" binding:"omitempty,min=0,max=1000000"`
|
||||
SubscribersPerWeek *int32 `json:"subscribers_per_week" binding:"omitempty,min=0,max=100000000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
@@ -266,7 +274,7 @@ func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
|
||||
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
|
||||
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
|
||||
MonitorsPerPage: req.MonitorsPerPage,
|
||||
MonitorsPerPage: req.MonitorsPerPage, SubscribersPerWeek: req.SubscribersPerWeek,
|
||||
})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
@@ -318,11 +326,12 @@ type adminOrg struct {
|
||||
}
|
||||
|
||||
type orgLimitsView struct {
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page"`
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page"`
|
||||
SubscribersPerWeek *int32 `json:"subscribers_per_week"`
|
||||
}
|
||||
|
||||
type adminOwner struct {
|
||||
@@ -349,10 +358,10 @@ func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]ad
|
||||
o := &out[i]
|
||||
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
|
||||
o.Created = r.CreatedAt.Format("2006-01-02")
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage}
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage, r.LimitSubscribersPerWeek}
|
||||
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
|
||||
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount,
|
||||
LimitMonitorsPerPage: r.LimitMonitorsPerPage})
|
||||
LimitMonitorsPerPage: r.LimitMonitorsPerPage, LimitSubscribersPerWeek: r.LimitSubscribersPerWeek})
|
||||
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
|
||||
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
|
||||
if r.OwnerID != uuid.Nil {
|
||||
@@ -412,6 +421,7 @@ func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
|
||||
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
|
||||
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
|
||||
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor), PerPageOverride: optInt(o.Overrides.MonitorsPerPage),
|
||||
SubscribersOverride: optInt(o.Overrides.SubscribersPerWeek),
|
||||
}
|
||||
if o.Overrides.OwnRegionsCount != nil {
|
||||
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
|
||||
|
||||
@@ -251,6 +251,8 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
|
||||
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
|
||||
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
|
||||
page.GET("/subscribers", canPage(authz.StatusPagesWrite), s.listPageSubscribers)
|
||||
page.DELETE("/subscribers/:subscriber", canPage(authz.StatusPagesWrite), s.deletePageSubscriber)
|
||||
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
|
||||
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
|
||||
|
||||
|
||||
+17
-10
@@ -53,6 +53,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
Title: page.Title,
|
||||
Description: page.Description,
|
||||
ShowDetails: page.ShowComponentDetails,
|
||||
Subscribe: page.Subscriptions && s.smtp != nil,
|
||||
Sections: []agentapi.Section{},
|
||||
Incidents: []agentapi.PageIncident{},
|
||||
GeneratedAt: time.Now(),
|
||||
@@ -234,7 +235,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
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,
|
||||
ID: i.ID.String(), 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],
|
||||
})
|
||||
}
|
||||
@@ -463,12 +464,14 @@ func (s *Server) agentPageIndex(c *gin.Context) {
|
||||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
// Subscriptions lets visitors subscribe to incidents by email.
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
}
|
||||
|
||||
func (r *statusPageRequest) normalize() string {
|
||||
@@ -504,6 +507,7 @@ type statusPageView struct {
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
DomainVerified bool `json:"domain_verified"`
|
||||
@@ -531,7 +535,7 @@ type dnsRecord struct {
|
||||
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,
|
||||
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails, Subscriptions: p.Subscriptions,
|
||||
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
|
||||
Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason,
|
||||
}
|
||||
@@ -607,7 +611,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
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,
|
||||
DomainToken: newDomainToken(), Theme: theme, Subscriptions: req.Subscriptions,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -650,6 +654,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
|
||||
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,
|
||||
Subscriptions: req.Subscriptions,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -694,7 +699,9 @@ type pageMonitor struct {
|
||||
}
|
||||
|
||||
type pageMonitorsRequest struct {
|
||||
Monitors []pageMonitor `json:"monitors" binding:"max=200,dive"`
|
||||
// The organization's limit decides how many; the binding only bounds
|
||||
// a request.
|
||||
Monitors []pageMonitor `json:"monitors" binding:"max=100000,dive"`
|
||||
}
|
||||
|
||||
// setPageMonitors replaces the page's components; their order is the
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"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/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Visitors subscribe to a status page's incidents by email. A subscription
|
||||
// counts towards the organization's weekly limit as soon as it is asked
|
||||
// for, and nothing but the confirmation is mailed until the address
|
||||
// confirms it, so the form cannot be used to flood strangers' inboxes.
|
||||
|
||||
const (
|
||||
// confirmTTL is how long a confirmation link works.
|
||||
confirmTTL = 48 * time.Hour
|
||||
// subscriberWindow is the window of the weekly limit; unconfirmed
|
||||
// subscriptions are kept as long, so they keep counting.
|
||||
subscriberWindow = 7 * 24 * time.Hour
|
||||
subscriberBatch = 50
|
||||
// maxSubscriberAttempts bounds retries of one mail.
|
||||
maxSubscriberAttempts = 6
|
||||
// maxSubscriberList bounds the subscribers listed in the console.
|
||||
maxSubscriberList = 1000
|
||||
)
|
||||
|
||||
// Rate limits of subscription requests, per visitor address, mailbox and
|
||||
// page, on top of the organization's weekly limit.
|
||||
const (
|
||||
subscribePerIP = 5
|
||||
subscribePerEmail = 3
|
||||
subscribePerPage = 100
|
||||
subscribeIPWindow = time.Hour
|
||||
subscribeMailboxIn = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Token purposes; a token of one is never accepted as the other.
|
||||
const (
|
||||
tokenConfirm = "confirm"
|
||||
tokenUnsubscribe = "unsubscribe"
|
||||
)
|
||||
|
||||
// subscriberToken seals the subscriber's ID and an expiry (zero for none),
|
||||
// so links need no table of their own and an unsubscribe link can be put
|
||||
// into every mail.
|
||||
func (s *Server) subscriberToken(id uuid.UUID, purpose string, expires time.Time) string {
|
||||
b := make([]byte, 24)
|
||||
copy(b, id[:])
|
||||
if !expires.IsZero() {
|
||||
binary.BigEndian.PutUint64(b[16:], uint64(expires.Unix()))
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(s.keys.Seal(b, []byte("subscriber:"+purpose)))
|
||||
}
|
||||
|
||||
func (s *Server) openSubscriberToken(token, purpose string, now time.Time) (uuid.UUID, bool) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(token) > 300 {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
b, err := s.keys.Open(raw, []byte("subscriber:"+purpose))
|
||||
if err != nil || len(b) != 24 {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
if exp := binary.BigEndian.Uint64(b[16:]); exp != 0 && now.Unix() > int64(exp) {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, err := uuid.FromBytes(b[:16])
|
||||
return id, err == nil
|
||||
}
|
||||
|
||||
// subscriberEmail returns the address in normalized form, or false if it
|
||||
// is none.
|
||||
func subscriberEmail(raw string) (string, bool) {
|
||||
e := normalizeEmail(raw)
|
||||
a, err := mail.ParseAddress(e)
|
||||
if err != nil || a.Address != e || len(e) > 254 || !strings.Contains(e[strings.LastIndexByte(e, '@')+1:], ".") {
|
||||
return "", false
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
|
||||
func mailboxKey(email string) string {
|
||||
sum := sha256.Sum256([]byte(email))
|
||||
return hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
// subscriberPageURL is the page address for links in mails, ending in "/":
|
||||
// the platform's own where it knows it, else the one the visitor used.
|
||||
func (s *Server) subscriberPageURL(page store.StatusPage, ownServers bool, given string) string {
|
||||
if known := s.pageURL(page, ownServers); absoluteURL(known) {
|
||||
return strings.TrimSuffix(known, "/") + "/"
|
||||
}
|
||||
if !absoluteURL(given) || len(given) > 500 {
|
||||
return ""
|
||||
}
|
||||
u, _ := url.Parse(given)
|
||||
u.RawQuery, u.Fragment = "", ""
|
||||
return strings.TrimSuffix(u.String(), "/") + "/"
|
||||
}
|
||||
|
||||
func absoluteURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != ""
|
||||
}
|
||||
|
||||
// agentSubscribe asks for a subscription for a visitor of a status page
|
||||
// server and mails the confirmation. It answers the same whether the
|
||||
// address was subscribed already or not.
|
||||
func (s *Server) agentSubscribe(c *gin.Context) {
|
||||
var req agentapi.SubscribeRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
email, ok := subscriberEmail(req.Email)
|
||||
if !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_email")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
a := agentOf(c)
|
||||
var host, slug *string
|
||||
if h := strings.ToLower(strings.TrimSpace(req.Host)); h != "" {
|
||||
host = &h
|
||||
} else if sl := strings.ToLower(strings.TrimSpace(req.Slug)); sl != "" {
|
||||
slug = &sl
|
||||
} else {
|
||||
fail(c, http.StatusBadRequest, "invalid_input")
|
||||
return
|
||||
}
|
||||
page, ok, err := s.agentServes(ctx, a, host, slug)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok || !page.Subscriptions || s.smtp == nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ip := c.ClientIP()
|
||||
if addr, err := netip.ParseAddr(req.IP); err == nil {
|
||||
ip = addr.String()
|
||||
}
|
||||
if !s.limit(c, "subscribe:ip:"+ip, subscribePerIP, subscribeIPWindow) ||
|
||||
!s.limit(c, "subscribe:mailbox:"+mailboxKey(email), subscribePerEmail, subscribeMailboxIn) ||
|
||||
!s.limit(c, "subscribe:page:"+page.ID.String(), subscribePerPage, time.Hour) {
|
||||
return
|
||||
}
|
||||
locale := s.catalog.Match(req.Locale).Lang()
|
||||
pageURL := s.subscriberPageURL(page, a.OrgID != nil, req.PageURL)
|
||||
var (
|
||||
sub store.StatusPageSubscriber
|
||||
send bool
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
org, err := q.GetOrg(ctx, page.OrgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.LockOrgUsage(ctx, page.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
existing, err := q.GetPageSubscriberByEmail(ctx, store.GetPageSubscriberByEmailParams{PageID: page.ID, Email: email})
|
||||
switch {
|
||||
case err == nil && existing.ConfirmedAt != nil:
|
||||
return nil
|
||||
case err == nil:
|
||||
sub, send = existing, true
|
||||
return q.TouchPendingSubscriber(ctx, store.TouchPendingSubscriberParams{ID: existing.ID, Locale: locale, PageUrl: pageURL})
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
if max := s.orgLimits(ctx, org).SubscribersPerWeek; max > 0 {
|
||||
n, err := q.CountRecentSubscribers(ctx, store.CountRecentSubscribersParams{OrgID: page.OrgID, CreatedAt: time.Now().Add(-subscriberWindow)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n >= int64(max) {
|
||||
return limitError{"subscriber_limit", max}
|
||||
}
|
||||
}
|
||||
sub, err = q.CreatePageSubscriber(ctx, store.CreatePageSubscriberParams{
|
||||
OrgID: page.OrgID, PageID: page.ID, Email: email, Locale: locale, PageUrl: pageURL,
|
||||
})
|
||||
send = err == nil
|
||||
return err
|
||||
})
|
||||
var le limitError
|
||||
switch {
|
||||
case errors.As(err, &le):
|
||||
s.log.WarnContext(ctx, "status page subscriptions reached the weekly limit", "org", page.OrgID, "page", page.ID, "max", le.max)
|
||||
c.Header("Retry-After", "3600")
|
||||
fail(c, http.StatusTooManyRequests, le.code)
|
||||
return
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if send {
|
||||
if err := s.sendSubscriberConfirmation(ctx, sub, page.Title, pageURL); err != nil {
|
||||
s.log.WarnContext(ctx, "mailing a subscription confirmation failed", "page", page.ID, "error", err)
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status(http.StatusAccepted)
|
||||
}
|
||||
|
||||
func (s *Server) sendSubscriberConfirmation(ctx context.Context, sub store.StatusPageSubscriber, title, pageURL string) error {
|
||||
if pageURL == "" {
|
||||
return errors.New("api: no address of the status page for the confirmation link")
|
||||
}
|
||||
token := s.subscriberToken(sub.ID, tokenConfirm, time.Now().Add(confirmTTL))
|
||||
l := s.catalog.Match(sub.Locale)
|
||||
data := map[string]any{"Page": title, "Link": pageURL + "subscribe/confirm?token=" + url.QueryEscape(token), "Hours": int(confirmTTL.Hours())}
|
||||
return s.smtp.Send(ctx, notify.Mail{
|
||||
To: []string{sub.Email}, Subject: l.T("email.subscribe.subject", data), Body: l.T("email.subscribe.body", data),
|
||||
})
|
||||
}
|
||||
|
||||
type subscriptionTokenRequest struct {
|
||||
Token string `json:"token" binding:"required,max=300"`
|
||||
}
|
||||
|
||||
// agentConfirmSubscription confirms a subscription from its mailed link.
|
||||
func (s *Server) agentConfirmSubscription(c *gin.Context) {
|
||||
s.subscriptionByToken(c, tokenConfirm, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
|
||||
return q.ConfirmPageSubscriber(ctx, sub.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// agentUnsubscribe ends a subscription from the link in a mail.
|
||||
func (s *Server) agentUnsubscribe(c *gin.Context) {
|
||||
s.subscriptionByToken(c, tokenUnsubscribe, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
|
||||
_, err := q.DeletePageSubscriber(ctx, store.DeletePageSubscriberParams{ID: sub.ID, PageID: sub.PageID})
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) subscriptionByToken(c *gin.Context, purpose string, act func(context.Context, *store.Queries, store.GetPageSubscriberRow) error) {
|
||||
var req subscriptionTokenRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
id, ok := s.openSubscriberToken(req.Token, purpose, time.Now())
|
||||
if !ok {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
a := agentOf(c)
|
||||
var sub store.GetPageSubscriberRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if sub, err = q.GetPageSubscriber(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// An organization's server acts only on its own pages.
|
||||
if a.OrgID != nil && *a.OrgID != sub.OrgID {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return act(ctx, q, sub)
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, agentapi.SubscriptionInfo{PageTitle: sub.PageTitle, Email: sub.Email})
|
||||
}
|
||||
}
|
||||
|
||||
// deliverSubscriberBatch mails queued incident events to subscribers.
|
||||
func (s *Server) deliverSubscriberBatch(ctx context.Context) int {
|
||||
if s.smtp == nil {
|
||||
return 0
|
||||
}
|
||||
var rows []store.SubscriberNotificationDetailsRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
ids, err := q.ClaimSubscriberNotifications(ctx, subscriberBatch)
|
||||
if err != nil || len(ids) == 0 {
|
||||
return err
|
||||
}
|
||||
rows, err = q.SubscriberNotificationDetails(ctx, ids)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "claiming subscriber notifications failed", "error", err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
for _, n := range rows {
|
||||
sendErr := s.smtp.Send(ctx, s.subscriberMail(n))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkSubscriberNotificationSent(ctx, n.ID)
|
||||
}
|
||||
return q.MarkSubscriberNotificationFailed(ctx, store.MarkSubscriberNotificationFailedParams{
|
||||
ID: n.ID, LastError: ptr(truncateValid(sendErr.Error(), 500)), MaxAttempts: maxSubscriberAttempts,
|
||||
RetryInSeconds: int32(retryDelay(int(n.Attempts)).Seconds()),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "recording subscriber notification failed", "notification", n.ID, "error", err)
|
||||
}
|
||||
if sendErr != nil {
|
||||
s.log.WarnContext(ctx, "mailing a subscriber failed", "notification", n.ID, "page", n.PageID, "attempt", n.Attempts+1, "error", sendErr)
|
||||
}
|
||||
}
|
||||
return len(rows)
|
||||
}
|
||||
|
||||
// subscriberMail is the mail announcing n.
|
||||
func (s *Server) subscriberMail(n store.SubscriberNotificationDetailsRow) notify.Mail {
|
||||
page := store.StatusPage{Slug: n.Slug, CustomDomain: n.CustomDomain, DomainVerifiedAt: n.DomainVerifiedAt}
|
||||
base := s.subscriberPageURL(page, n.OwnServers, n.PageUrl)
|
||||
unsubscribe := base + "unsubscribe?token=" + url.QueryEscape(s.subscriberToken(n.SubscriberID, tokenUnsubscribe, time.Time{}))
|
||||
l := s.catalog.Match(n.Locale)
|
||||
title := n.IncidentTitle
|
||||
if title == "" {
|
||||
title = n.Component
|
||||
}
|
||||
at := n.StartedAt
|
||||
if n.Event == notify.Resolved && n.ResolvedAt != nil {
|
||||
at = *n.ResolvedAt
|
||||
}
|
||||
status := n.UpdateStatusName
|
||||
if status == "" && n.UpdateStatus != "" {
|
||||
status = l.T("incident.status."+n.UpdateStatus, nil)
|
||||
}
|
||||
data := map[string]any{
|
||||
"Page": n.PageTitle, "Title": title, "Component": n.Component, "Link": base,
|
||||
"Time": at.UTC().Format("2006-01-02 15:04") + " UTC", "Status": status, "Message": n.UpdateMessage,
|
||||
"Unsubscribe": unsubscribe,
|
||||
}
|
||||
if n.ResolvedAt != nil {
|
||||
data["Duration"] = n.ResolvedAt.Sub(n.StartedAt).Round(time.Minute).String()
|
||||
}
|
||||
return notify.Mail{
|
||||
To: []string{n.Email},
|
||||
Subject: l.T("email.subscriber."+n.Event+".subject", data),
|
||||
Body: l.T("email.subscriber."+n.Event+".body", data) + l.T("email.subscriber.footer", data),
|
||||
// RFC 8058: mail programs offer unsubscribing with one click.
|
||||
Headers: map[string]string{
|
||||
"List-Unsubscribe": "<" + unsubscribe + ">",
|
||||
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// subscriberView is a subscriber in the console.
|
||||
type subscriberView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Locale string `json:"locale"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ConfirmedAt *time.Time `json:"confirmed_at"`
|
||||
}
|
||||
|
||||
type subscribersView struct {
|
||||
Confirmed int `json:"confirmed"`
|
||||
Pending int `json:"pending"`
|
||||
Subscribers []subscriberView `json:"subscribers"`
|
||||
}
|
||||
|
||||
func (s *Server) pageSubscribers(ctx context.Context, q *store.Queries, page uuid.UUID) (subscribersView, error) {
|
||||
v := subscribersView{Subscribers: []subscriberView{}}
|
||||
counts, err := q.CountPageSubscribers(ctx, page)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
v.Confirmed, v.Pending = int(counts.Confirmed), int(counts.Pending)
|
||||
rows, err := q.ListPageSubscribers(ctx, store.ListPageSubscribersParams{PageID: page, MaxRows: maxSubscriberList})
|
||||
for _, r := range rows {
|
||||
v.Subscribers = append(v.Subscribers, subscriberView{r.ID, r.Email, r.Locale, r.CreatedAt, r.ConfirmedAt})
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (s *Server) listPageSubscribers(c *gin.Context) {
|
||||
id := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var v subscribersView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
v, err = s.pageSubscribers(ctx, q, id)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deletePageSubscriber(c *gin.Context) {
|
||||
id := uuid.MustParse(c.Param("id"))
|
||||
sub, err := uuid.Parse(c.Param("subscriber"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
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.DeletePageSubscriber(ctx, store.DeletePageSubscriberParams{ID: sub, PageID: id})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case n == 0:
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
default:
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
|
||||
)
|
||||
|
||||
var tokenRE = regexp.MustCompile(`token=([A-Za-z0-9_%-]+)`)
|
||||
|
||||
func TestStatusPageSubscriptions(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
var healthy atomic.Bool
|
||||
healthy.Store(true)
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
}))
|
||||
defer target.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("sub")+".test", uniq("sub-"))
|
||||
_, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
|
||||
})
|
||||
monitorID := body["id"].(string)
|
||||
slug := uniq("subs-")
|
||||
_, body = owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop Status"})
|
||||
pageID := body["id"].(string)
|
||||
page := map[string]any{"slug": slug, "title": "Shop Status", "published": true, "subscriptions": true}
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
|
||||
if st != http.StatusOK || body["subscriptions"] != true {
|
||||
t.Fatalf("enable subscriptions = %d %v", st, body)
|
||||
}
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}})
|
||||
|
||||
cat, _ := i18n.Load()
|
||||
pages, err := statuspage.New(e.statuspageClient(t, nil), cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
pages.Mount(router)
|
||||
visitor := "198.51.100.7:1234"
|
||||
visit := func(method, path, form string) (int, string, http.Header) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(form))
|
||||
req.Host = "status.test"
|
||||
req.RemoteAddr = visitor
|
||||
if form != "" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
pages.Wait()
|
||||
return w.Code, w.Body.String(), w.Header()
|
||||
}
|
||||
subscribers := func() (int, int) {
|
||||
_, body := owner.do("GET", "/api/v1/org/statuspages/"+pageID+"/subscribers", nil)
|
||||
return int(body["confirmed"].(float64)), int(body["pending"].(float64))
|
||||
}
|
||||
mailsTo := func(addr string) []string {
|
||||
var out []string
|
||||
for _, m := range mail.Messages() {
|
||||
if len(m.To) == 1 && m.To[0] == addr {
|
||||
out = append(out, m.Data)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if code, html, _ := visit("GET", "/"+slug, ""); code != 200 || !strings.Contains(html, `action="/`+slug+`/subscribe"`) || !strings.Contains(html, "feed.rss") {
|
||||
t.Fatalf("page = %d, want the subscription form and the feed link", code)
|
||||
}
|
||||
if code, html, _ := visit("POST", "/"+slug+"/subscribe", "email=not-an-address"); code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("subscribing an invalid address = %d %.200s", code, html)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=Visitor@Example.test"); code != 200 {
|
||||
t.Fatalf("subscribe = %d", code)
|
||||
}
|
||||
if c, p := subscribers(); c != 0 || p != 1 {
|
||||
t.Errorf("subscribers after subscribing = %d confirmed, %d pending; want 0, 1", c, p)
|
||||
}
|
||||
sent := mailsTo("visitor@example.test")
|
||||
if len(sent) != 1 || !strings.Contains(sent[0], "Shop Status") {
|
||||
t.Fatalf("confirmation mails = %d", len(sent))
|
||||
}
|
||||
m := tokenRE.FindStringSubmatch(sent[0])
|
||||
if m == nil {
|
||||
t.Fatal("no token in the confirmation mail")
|
||||
}
|
||||
confirm, _ := url.QueryUnescape(m[1])
|
||||
|
||||
// Opening the link only shows a button.
|
||||
if code, html, _ := visit("GET", "/"+slug+"/subscribe/confirm?token="+url.QueryEscape(confirm), ""); code != 200 || !strings.Contains(html, `name="token"`) {
|
||||
t.Errorf("confirmation link = %d", code)
|
||||
}
|
||||
if c, _ := subscribers(); c != 0 {
|
||||
t.Error("opening the confirmation link confirmed the subscription")
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/unsubscribe", "token="+url.QueryEscape(confirm)); code != http.StatusNotFound {
|
||||
t.Errorf("unsubscribing with the confirmation token = %d, want 404", code)
|
||||
}
|
||||
if code, html, _ := visit("POST", "/"+slug+"/subscribe/confirm", "token="+url.QueryEscape(confirm)); code != 200 || !strings.Contains(html, "visitor@example.test") {
|
||||
t.Fatalf("confirm = %d %.300s", code, html)
|
||||
}
|
||||
if c, p := subscribers(); c != 1 || p != 0 {
|
||||
t.Errorf("subscribers after confirming = %d, %d; want 1, 0", c, p)
|
||||
}
|
||||
// Asking again for a confirmed address mails nothing.
|
||||
visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test")
|
||||
if n := len(mailsTo("visitor@example.test")); n != 1 {
|
||||
t.Errorf("mails after subscribing a confirmed address again = %d, want 1", n)
|
||||
}
|
||||
|
||||
healthy.Store(false)
|
||||
waitFor(t, 30*time.Second, "outage mail to the subscriber", func() bool { return len(mailsTo("visitor@example.test")) == 2 })
|
||||
outage := mailsTo("visitor@example.test")[1]
|
||||
if !strings.Contains(outage, "Shop") || !strings.Contains(outage, "List-Unsubscribe: <http") || !strings.Contains(outage, "List-Unsubscribe-Post: List-Unsubscribe=One-Click") {
|
||||
t.Errorf("outage mail = %.600s", outage)
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
incidentID := body["incidents"].([]any)[0].(map[string]any)["id"].(string)
|
||||
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "Payment provider down", "public": false})
|
||||
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "We found the cause", "public": true})
|
||||
waitFor(t, 10*time.Second, "update mail", func() bool { return len(mailsTo("visitor@example.test")) == 3 })
|
||||
if upd := mailsTo("visitor@example.test")[2]; !strings.Contains(upd, "We found the cause") {
|
||||
t.Errorf("update mail = %.400s", upd)
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
for _, m := range mailsTo("visitor@example.test") {
|
||||
if strings.Contains(m, "Payment provider down") {
|
||||
t.Error("a private update was mailed to a subscriber")
|
||||
}
|
||||
}
|
||||
|
||||
// Feed and API come from the snapshot.
|
||||
pages.Sync(ctx)
|
||||
code, feed, hdr := visit("GET", "/"+slug+"/feed.rss", "")
|
||||
if code != 200 || !strings.HasPrefix(hdr.Get("Content-Type"), "application/rss+xml") || !strings.Contains(feed, "<rss") ||
|
||||
!strings.Contains(feed, "incident-"+incidentID) || !strings.Contains(feed, "We found the cause") {
|
||||
t.Errorf("feed = %d %.600s", code, feed)
|
||||
}
|
||||
code, raw, hdr := visit("GET", "/"+slug+"/api/v1/summary", "")
|
||||
var summary struct {
|
||||
Page struct{ Title, Status string }
|
||||
Components []struct{ Name, Status string }
|
||||
Incidents []struct{ ID string }
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &summary); code != 200 || err != nil || hdr.Get("Access-Control-Allow-Origin") != "*" ||
|
||||
summary.Page.Title != "Shop Status" || len(summary.Components) != 1 || len(summary.Incidents) != 1 || summary.Incidents[0].ID != incidentID {
|
||||
t.Errorf("summary = %d %v %s", code, err, raw)
|
||||
}
|
||||
if code, _, _ := visit("GET", "/"+slug+"/api/v1/nope", ""); code != 404 {
|
||||
t.Errorf("unknown API resource = %d", code)
|
||||
}
|
||||
|
||||
// The unsubscribe link of mails works with one click, as mail
|
||||
// programs post it.
|
||||
m = tokenRE.FindStringSubmatch(outage)
|
||||
unsub, _ := url.QueryUnescape(m[1])
|
||||
if code, html, _ := visit("POST", "/"+slug+"/unsubscribe?token="+url.QueryEscape(unsub), "List-Unsubscribe=One-Click"); code != 200 {
|
||||
t.Errorf("one-click unsubscribe = %d %.300s", code, html)
|
||||
}
|
||||
if c, p := subscribers(); c != 0 || p != 0 {
|
||||
t.Errorf("subscribers after unsubscribing = %d, %d", c, p)
|
||||
}
|
||||
|
||||
// The weekly limit counts every subscription asked for.
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE orgs SET limit_subscribers_per_week = 1 WHERE id = $1`, owner.orgID())
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=second@example.test"); code != 200 {
|
||||
t.Errorf("subscription within the weekly limit = %d", code)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=third@example.test"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("subscription beyond the weekly limit = %d, want 429", code)
|
||||
}
|
||||
if n := len(mailsTo("third@example.test")); n != 0 {
|
||||
t.Errorf("mails beyond the weekly limit = %d", n)
|
||||
}
|
||||
|
||||
// Pages without subscriptions take none. (Another visitor: this one
|
||||
// used up its subscription requests.)
|
||||
visitor = "198.51.100.8:1234"
|
||||
page["subscriptions"] = false
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
|
||||
pages.Sync(ctx)
|
||||
if code, html, _ := visit("GET", "/"+slug, ""); code != 200 || strings.Contains(html, "/subscribe\"") {
|
||||
t.Errorf("page without subscriptions = %d, still offers the form", code)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fourth@example.test"); code != http.StatusNotFound {
|
||||
t.Errorf("subscribing where it is off = %d, want 404", code)
|
||||
}
|
||||
|
||||
// This visitor used up its subscription requests on the server.
|
||||
visitor = "198.51.100.7:1234"
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fifth@example.test"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("sixth subscription request of a visitor = %d, want 429", code)
|
||||
}
|
||||
|
||||
// Polling the API is rate limited per visitor.
|
||||
limited := false
|
||||
for range 70 {
|
||||
if code, _, _ := visit("GET", "/"+slug+"/api/v1/status", ""); code == http.StatusTooManyRequests {
|
||||
limited = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !limited {
|
||||
t.Error("70 API requests within a minute were all answered")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user