package api_test import ( "context" "encoding/json" "errors" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/api" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) // statuspageClient creates a status page agent, platform-wide when org is // nil, and returns a client for it. func (e *env) statuspageClient(t *testing.T, org *uuid.UUID) *agentapi.Client { t.Helper() ctx := context.Background() tok, params := api.NewAgentToken(org, "statuspage", "sp-"+uuid.NewString()[:6], nil) err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error { _, err := q.CreateAgent(ctx, params) return err }) if err != nil { t.Fatal(err) } return agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) } func TestStatusPages(t *testing.T) { e := newEnv(t) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) go e.api.RunScheduler(ctx) up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) defer up.Close() down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer down.Close() tok, region := e.platformChecker(t, uniq("eu-")) e.startChecker(t, tok) owner := e.browser(t) owner.signup("o@"+uniq("s")+".test", uniq("sp-")) newMonitor := func(name, target string) string { st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ "name": name, "type": "http", "target": target, "interval_seconds": 60, "confirmations": 1, "regions": []string{region}, }) if st != http.StatusCreated { t.Fatalf("create monitor = %d %v", st, body) } return body["id"].(string) } webID, apiID := newMonitor("web", up.URL), newMonitor("api", down.URL) slug := uniq("acme-") st, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "theme": map[string]any{"accent": "#1f6feb"}}) if st != http.StatusCreated { t.Fatalf("create page = %d %v", st, body) } pageID := body["id"].(string) st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{ {"monitor_id": webID, "section": "Frontend", "label": "Website"}, {"monitor_id": apiID, "section": "Backend", "label": "Public API"}, }}) expect(t, "set page monitors", st, body, http.StatusNoContent, "") platform := e.statuspageClient(t, nil) if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) { t.Errorf("Page(unpublished) error = %v, want not found", err) } owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme Status", "published": true, "theme": map[string]any{"accent": "#1f6feb"}}) waitFor(t, 10*time.Second, "incident for the failing monitor", func() bool { _, body := owner.do("GET", "/api/v1/org/incidents", nil) return len(body["incidents"].([]any)) == 1 }) snap, err := platform.Page(context.Background(), "", slug) if err != nil { t.Fatalf("Page() failed: %v", err) } if snap.Status != agentapi.PageDegraded || len(snap.Sections) != 2 || snap.Sections[1].Components[0].Status != agentapi.PageOutage || snap.Sections[1].Components[0].Name != "Public API" { t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap) } raw, _ := json.Marshal(snap) for _, secret := range []string{up.URL, down.URL, "unexpected status"} { if strings.Contains(string(raw), secret) { t.Errorf("snapshot leaks %q", secret) } } t.Run("rendered by the status page server", func(t *testing.T) { cat, _ := i18n.Load() srv := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), []string{"status.test"}) gin.SetMode(gin.TestMode) router := gin.New() srv.Mount(router) req := httptest.NewRequest(http.MethodGet, "/"+slug, nil) req.Host = "status.test" w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Acme Status") || !strings.Contains(w.Body.String(), "--page-accent:#1f6feb") { t.Errorf("rendered page = %d %.200s", w.Code, w.Body.String()) } }) t.Run("other org cannot use or see it", func(t *testing.T) { other := e.browser(t) other.signup("x@"+uniq("x")+".test", uniq("sp-other-")) otherOrg := uuid.MustParse(other.orgID()) if _, err := e.statuspageClient(t, &otherOrg).Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) { t.Errorf("other org's status page server got the page: %v", err) } st, body := other.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("o-"), "title": "x"}) if st != http.StatusCreated { t.Fatalf("create page = %d %v", st, body) } st, body = other.do("PUT", "/api/v1/org/statuspages/"+body["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": webID}}}) expect(t, "list foreign monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor") st, body = other.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "hijack"}) expect(t, "edit foreign page", st, body, http.StatusNotFound, "not_found") }) t.Run("custom domain after verification", func(t *testing.T) { domain := uniq("status") + ".example.test" st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/domain", map[string]any{"domain": domain}) if st != http.StatusOK { t.Fatalf("set domain = %d %v", st, body) } record := body["domain_record"].(map[string]any) if _, err := platform.Page(context.Background(), domain, ""); !errors.Is(err, agentapi.ErrNotFound) { t.Errorf("Page(unverified domain) error = %v, want not found", err) } verifyDomain(t, owner, pageID, record) if snap, err := platform.Page(context.Background(), domain, ""); err != nil || snap.Title != "Acme Status" { t.Errorf("Page(verified domain) = %v, %v", snap.Title, err) } }) t.Run("export", func(t *testing.T) { resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export") if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() html, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Disposition"), slug+".html") || !strings.Contains(string(html), "