Files
uptimesebi/internal/api/moderation_test.go
Sebastian UnterschützandClaude Opus 5.5 d7c5cd711e
ci / image (pull_request) Successful in 3m18s
ci / build (pull_request) Successful in 8m38s
ci / test (pull_request) Successful in 12m6s
ci / lint (pull_request) Successful in 15m0s
feat: page long and truncated lists
Lists that were cut off by a fixed LIMIT, or could grow without bound,
are paged by keyset: the cursor holds the sort key and an ID, so pages
neither skip nor repeat items as others are added. The audit logs had a
timestamp-only cursor that could skip entries with equal times.

The API returns at most 100 items per list (limit takes up to 500) with
next_cursor and prev_cursor, passed back as after and before. The
console shows Newer/Older (or Previous/Next) links and To the start,
without JavaScript.

Paged: incidents (optionally of one monitor), a monitor's results and
evidence, a checker's results, the audit logs, members, maintenance
windows, firing Alertmanager alerts, the monitors API and the admin
lists of status pages and organizations, which move to their own admin
pages. A monitor's page shows its latest incidents and results and links
to all of them. The dashboard caps every group at 50 of its own monitors
with a link to a paged view of the group, and gains a search by name or
target. Lists filtered by permission after reading may show fewer items
on a page.

Closes #116

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:40:25 +01:00

196 lines
8.3 KiB
Go

package api_test
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const testPassword = "correct horse battery"
func TestModeration(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("admin@"+uniq("mod")+".test", uniq("mod-admin-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
ownerEmail := "owner@" + uniq("mod") + ".test"
owner := e.browser(t)
owner.signup(ownerEmail, uniq("mod-org-"))
slug := uniq("acme-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "published": true})
_, draft := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("draft-"), "title": "Draft", "published": false})
_, hb := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600})
_, region := e.platformChecker(t, uniq("eu-"))
_, web := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Web", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
scheduled := func() bool {
var rows []store.ListEnabledMonitorsForScheduleRow
_ = tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
return err
})
for _, r := range rows {
if r.ID.String() == web["id"] {
return true
}
}
return false
}
_, tok := owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
api := &browser{t: t, base: owner.base, hc: e.srv.Client(), bearer: tok["token"].(string)}
sp := e.statuspageClient(t, nil)
served := func() bool {
_, err := sp.Page(ctx, "", slug)
if err != nil && !errors.Is(err, agentapi.ErrNotFound) {
t.Fatal(err)
}
return err == nil
}
// Pings of paused monitors are answered, so cron jobs do not fail, but
// not recorded.
recorded := func() bool {
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+hb["target"].(string), "text/plain", nil)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return resp.StatusCode == http.StatusOK && !strings.Contains(string(b), "paused")
}
// Only admins see the list; it holds published pages with their
// organization and owner, and search narrows it.
if st, _ := owner.do("GET", "/api/v1/admin/status-pages", nil); st != http.StatusForbidden {
t.Errorf("non-admin listing = %d", st)
}
_, list := admin.do("GET", "/api/v1/admin/status-pages?q="+slug, nil)
raw := mustJSON(list)
if !strings.Contains(raw, slug) || !strings.Contains(raw, ownerEmail) || strings.Contains(raw, draft["slug"].(string)) {
t.Fatalf("list = %s", raw)
}
pg := list["status_pages"].([]any)[0].(map[string]any)
orgID := pg["org"].(map[string]any)["id"].(string)
userID := pg["owner"].(map[string]any)["id"].(string)
if _, other := admin.do("GET", "/api/v1/admin/status-pages?q=no-such-page-"+slug, nil); len(other["status_pages"].([]any)) != 0 {
t.Error("search does not narrow the list")
}
if !served() {
t.Fatal("the page is not served before suspension")
}
// A suspended page goes offline and its organization learns why.
suspend := func(path string, on bool, reason string) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/"+path+"/suspension", map[string]any{"suspended": on, "reason": reason}); st != http.StatusNoContent {
t.Fatalf("suspend %s = %d %v", path, st, body)
}
}
suspend("status-pages/"+page["id"].(string), true, "phishing")
if served() {
t.Error("a suspended page is served")
}
_, pages := owner.do("GET", "/api/v1/org/statuspages", nil)
if raw := mustJSON(pages); !strings.Contains(raw, `"suspended":true`) || !strings.Contains(raw, `"suspended_reason":"phishing"`) {
t.Errorf("the organization does not see the suspension: %s", raw)
}
if _, _, html := owner.page("/statuspages"); !strings.Contains(html, "suspended by the operator") {
t.Error("the page list does not mark the suspension")
}
suspend("status-pages/"+page["id"].(string), false, "")
if !served() {
t.Error("a reinstated page is not served")
}
// A suspended organization is locked out, checks and pages stop.
suspend("orgs/"+orgID, true, "unpaid")
st, body := owner.do("GET", "/api/v1/org/monitors", nil)
expect(t, "member of a suspended org", st, body, http.StatusForbidden, "org_suspended")
st, body = api.do("GET", "/api/v1/org/monitors", nil)
expect(t, "token of a suspended org", st, body, http.StatusForbidden, "org_suspended")
if served() {
t.Error("a suspended organization's page is served")
}
if recorded() {
t.Error("a heartbeat of a suspended org is recorded")
}
if scheduled() {
t.Error("monitors of a suspended org are scheduled")
}
if _, _, html := owner.page("/"); !strings.Contains(html, "The operator suspended this organization") || !strings.Contains(html, "unpaid") {
t.Error("the console does not explain the suspension")
}
suspend("orgs/"+orgID, false, "")
if st, _ := owner.do("GET", "/api/v1/org/monitors", nil); st != http.StatusOK || !scheduled() {
t.Errorf("member of a reinstated org = %d, scheduled = %v", st, scheduled())
}
if !recorded() {
t.Error("a heartbeat after reinstatement is not recorded")
}
// A suspended account is signed out and kept out, tokens included.
suspend("users/"+userID, true, "")
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("session of a suspended account = %d", st)
}
if st, _ := api.do("GET", "/api/v1/org/monitors", nil); st != http.StatusUnauthorized {
t.Errorf("token of a suspended account = %d", st)
}
fresh := e.browser(t)
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword})
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": "wrong password"}); st != http.StatusUnauthorized {
t.Error("a wrong password reveals the suspension")
}
suspend("users/"+userID, false, "")
if st, _ := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
t.Errorf("sign-in after reinstatement = %d", st)
}
// Admins are out of reach, also for themselves.
st, body = admin.do("PUT", "/api/v1/admin/users/"+admin.userIDSelf().String()+"/suspension", map[string]any{"suspended": true})
expect(t, "suspend an admin", st, body, http.StatusConflict, "target_is_admin")
st, body = admin.do("DELETE", "/api/v1/admin/users/"+admin.userIDSelf().String(), nil)
expect(t, "delete an admin", st, body, http.StatusConflict, "target_is_admin")
// An owner of a shared organization cannot be deleted before it.
fresh.do("POST", "/api/v1/me/org", map[string]any{"org_id": orgID})
e.joinVia(t, fresh.invite("m@"+uniq("mod")+".test", fresh.roleID("viewer")))
st, body = admin.do("DELETE", "/api/v1/admin/users/"+userID, nil)
expect(t, "delete the owner of a shared org", st, body, http.StatusConflict, "owns_shared_orgs")
// Deleting: page, organization, account.
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
t.Errorf("delete page = %d", st)
}
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNoContent {
t.Errorf("delete org = %d", st)
}
if st, body := admin.do("DELETE", "/api/v1/admin/users/"+userID, nil); st != http.StatusNoContent {
t.Errorf("delete account = %d %v", st, body)
}
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusUnauthorized {
t.Error("the deleted account can still sign in")
}
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNotFound {
t.Error("deleting a deleted org is not 404")
}
// The admin page shows the list.
if _, _, html := admin.page("/admin/status-pages"); !strings.Contains(html, `id="moderation"`) {
t.Error("the admin page lacks the status page list")
}
}