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: