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 } if !req.Accepted { fail(c, http.StatusUnprocessableEntity, "consent_required") 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) } }