ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / image (pull_request) Waiting for needed jobs
ci / lint (pull_request) Successful in 11m8s
ci / test (pull_request) Successful in 13m45s
ci / build (pull_request) In progress
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
258 lines
11 KiB
Go
258 lines
11 KiB
Go
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
|
|
}
|
|
|
|
// Subscribers accept the page's privacy policy.
|
|
if st, body := owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{"url": "https://shop.example/privacy"}); st != http.StatusNoContent {
|
|
t.Fatalf("set privacy policy = %d %v", st, body)
|
|
}
|
|
t.Cleanup(func() { owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{}) })
|
|
pages.Sync(ctx)
|
|
code, html, _ := visit("GET", "/"+slug, "")
|
|
if 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 !strings.Contains(html, `name="accept"`) || !strings.Contains(html, `href="https://shop.example/privacy"`) {
|
|
t.Error("the subscription form does not ask to accept the privacy policy")
|
|
}
|
|
if code, html, _ := visit("POST", "/"+slug+"/subscribe", "email=not-an-address&accept=1"); code != http.StatusUnprocessableEntity {
|
|
t.Errorf("subscribing an invalid address = %d %.200s", code, html)
|
|
}
|
|
visitor = "198.51.100.9:1234" // (not to use up the subscription requests of the first)
|
|
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test"); code != http.StatusUnprocessableEntity {
|
|
t.Errorf("subscribing without accepting the privacy policy = %d, want 422", code)
|
|
}
|
|
visitor = "198.51.100.7:1234"
|
|
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=Visitor@Example.test&accept=1"); 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&accept=1")
|
|
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&accept=1"); code != 200 {
|
|
t.Errorf("subscription within the weekly limit = %d", code)
|
|
}
|
|
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=third@example.test&accept=1"); 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&accept=1"); 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&accept=1"); 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")
|
|
}
|
|
}
|