Files
uptimesebi/internal/api/limits_test.go
T
Sebastian UnterschützandClaude Opus 5.5 3a7bed5a3e
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m31s
ci / test (pull_request) Successful in 13m28s
ci / build (pull_request) Successful in 10m23s
ci / image (pull_request) Successful in 5m51s
fix(monitors): stop selecting more regions than the limit allows
The monitor form let users tick any number of regions and only the save
failed with the region limit. The form now knows the organization's
regions-per-monitor limit: it says how many regions a monitor may use,
counts the ticked ones, and once the limit is reached locks the other
regions that count towards it, in the list and on the map, until one is
unticked. Own regions stay free unless they count. The server still
enforces the limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 12:17:08 +01:00

239 lines
9.7 KiB
Go

package api_test
import (
"context"
"net/http"
"strings"
"sync"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestLimits(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
return err
})
}
reset()
t.Cleanup(reset)
admin := e.browser(t)
admin.signup("admin@"+uniq("lim")+".test", uniq("lim-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)
}
setDefaults := func(l map[string]any) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/limits", l); st != http.StatusNoContent {
t.Fatalf("set defaults = %d %v", st, body)
}
}
setDefaults(map[string]any{"monitors": 2, "status_pages": 1, "regions_per_monitor": 1, "own_regions_count": false, "orgs_per_account": 3})
_, p1 := e.platformChecker(t, uniq("eu-"))
_, p2 := e.platformChecker(t, uniq("us-"))
owner := e.browser(t)
orgSlug := uniq("lim-org-")
owner.signup("o@"+uniq("lim")+".test", orgSlug)
_, own := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
o1 := own["id"].(string)
monitor := func(regions ...string) (int, map[string]any) {
return owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": regions,
})
}
// The monitor form locks regions beyond the limit; own ones do not count.
_, _, html := owner.page("/monitors/new")
if !strings.Contains(html, `data-region-limit="1"`) {
t.Error("monitor form lacks the region limit")
}
for id, counted := range map[string]bool{p1: true, o1: false} {
i := strings.Index(html, `value="`+id+`"`)
if i < 0 {
t.Fatalf("monitor form lacks region %s", id)
}
tag := html[i : i+strings.Index(html[i:], ">")]
if strings.Contains(tag, "data-counted") != counted {
t.Errorf("region %s counted = %v, want %v", id, !counted, counted)
}
}
// Monitors, passive ones included.
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
t.Fatalf("heartbeat = %d %v", st, body)
}
if st, body := monitor(p1); st != http.StatusCreated {
t.Fatalf("second monitor = %d %v", st, body)
}
st, body := monitor(p1)
expect(t, "third monitor", st, body, http.StatusUnprocessableEntity, "monitor_limit")
if !strings.Contains(body["message"].(string), "2") {
t.Errorf("message lacks the limit: %v", body["message"])
}
_, usage := owner.do("GET", "/api/v1/org/limits", nil)
if raw := mustJSON(usage); !strings.Contains(raw, `"monitors":2`) || !strings.Contains(raw, `"usage":{"monitors":2,"status_pages":0}`) {
t.Errorf("org limits = %s", raw)
}
// An override lifts the monitor limit; own regions do not count.
_, orgs := admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
org := orgs["orgs"].([]any)[0].(map[string]any)
orgID := org["id"].(string)
setOrg := func(l map[string]any) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+orgID+"/limits", l); st != http.StatusNoContent {
t.Fatalf("set org limits = %d %v", st, body)
}
}
setOrg(map[string]any{"monitors": 10, "status_pages": nil, "regions_per_monitor": nil, "own_regions_count": nil})
st, body = monitor(p1, p2)
expect(t, "two platform regions", st, body, http.StatusUnprocessableEntity, "platform_region_limit")
st, mixed := monitor(p1, o1)
expect(t, "platform and own region", st, mixed, http.StatusCreated, "")
// Once own regions count, the existing monitor keeps both but may not
// grow, and new ones are refused.
setOrg(map[string]any{"monitors": 10, "own_regions_count": "true"})
st, body = monitor(p1, o1)
expect(t, "own region counted", st, body, http.StatusUnprocessableEntity, "region_limit")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, o1},
})
expect(t, "edit a monitor beyond a lowered limit", st, body, http.StatusOK, "")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, p2, o1},
})
expect(t, "grow a monitor beyond the limit", st, body, http.StatusUnprocessableEntity, "region_limit")
// Status pages; concurrent creations cannot overshoot.
var wg sync.WaitGroup
var mu sync.Mutex
created := 0
for range 5 {
wg.Add(1)
go func() {
defer wg.Done()
st, _ := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("p-"), "title": "x"})
mu.Lock()
defer mu.Unlock()
if st == http.StatusCreated {
created++
}
}()
}
wg.Wait()
if created != 1 {
t.Errorf("%d status pages created under a limit of 1", created)
}
// Defaults change for every organization without an override, at once.
other := e.browser(t)
other.signup("x@"+uniq("lim")+".test", uniq("lim-x-"))
setDefaults(map[string]any{"monitors": 1})
if st, _ := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
t.Fatalf("first monitor = %d", st)
}
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
expect(t, "default lowered", st, body, http.StatusUnprocessableEntity, "monitor_limit")
setDefaults(map[string]any{"monitors": 0})
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
expect(t, "default unlimited", st, body, http.StatusCreated, "")
// Account limits and the admin list.
ownerID := org["owner"].(map[string]any)["id"].(string)
if st, body := admin.do("PUT", "/api/v1/admin/users/"+ownerID+"/limits", map[string]any{"orgs": 5}); st != http.StatusNoContent {
t.Fatalf("set user limit = %d %v", st, body)
}
_, orgs = admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
raw := mustJSON(orgs)
for _, want := range []string{`"org_limit":5`, `"orgs":1`, `"monitors":10`, `"own_regions_count":true`, `"usage":{"monitors":3,"status_pages":1}`} {
if !strings.Contains(raw, want) {
t.Errorf("admin org list lacks %s: %s", want, raw)
}
}
if st, _ := owner.do("GET", "/api/v1/admin/orgs", nil); st != http.StatusForbidden {
t.Errorf("non-admin org list = %d", st)
}
if _, _, html := admin.page("/admin/orgs?q=" + orgSlug); !strings.Contains(html, `id="orgs"`) || !strings.Contains(html, orgSlug) {
t.Error("the admin page lacks the organization list")
}
if _, _, html := owner.page("/settings/org"); !strings.Contains(html, "3 / 10") {
t.Error("the organization settings lack the usage")
}
}
func TestMonitorsPerStatusPageLimit(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
return err
})
}
reset()
t.Cleanup(reset)
admin := e.browser(t)
admin.signup("admin@"+uniq("mpp")+".test", uniq("mpp-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)
}
if st, body := admin.do("PUT", "/api/v1/admin/limits", map[string]any{"monitors_per_page": 2}); st != http.StatusNoContent {
t.Fatalf("set defaults = %d %v", st, body)
}
owner := e.browser(t)
owner.signup("o@"+uniq("mpp")+".test", uniq("mpp-"))
var ids []map[string]any
for range 3 {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600})
ids = append(ids, map[string]any{"monitor_id": m["id"]})
}
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("mpp-"), "title": "Status"})
set := func(n int) (int, map[string]any) {
return owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": ids[:n]})
}
if st, body := set(2); st != http.StatusNoContent {
t.Fatalf("two monitors = %d %v", st, body)
}
st, body := set(3)
expect(t, "three monitors", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
if _, _, html := owner.page("/statuspages/" + page["id"].(string)); !strings.Contains(html, "at most 2 monitors") {
t.Error("the editor does not name the limit")
}
// An override for the organization raises it; lowered again, the page
// keeps its monitors but cannot grow.
org := owner.orgID()
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 3}); st != http.StatusNoContent {
t.Fatalf("override = %d %v", st, body)
}
if st, body := set(3); st != http.StatusNoContent {
t.Fatalf("three monitors with the override = %d %v", st, body)
}
admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 1})
if st, body := set(3); st != http.StatusNoContent {
t.Errorf("saving a page beyond a lowered limit = %d %v", st, body)
}
if st, body := set(2); st != http.StatusNoContent {
t.Errorf("shrinking a page beyond a lowered limit = %d %v", st, body)
}
st, body = set(3)
expect(t, "growing again beyond the lowered limit", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
if _, _, html := admin.page("/admin"); !strings.Contains(html, "Monitors per status page") {
t.Error("the admin page does not offer the limit")
}
}