Files
uptimesebi/internal/api/regions_test.go
T
Sebastian UnterschützandClaude Opus 5.5 22f0740056 feat(api): organization-owned regions, checkers and status page servers
Organizations create regions and agents for themselves under Regions &
checkers; an org checker only receives its org's monitors. Platform admins
manage shared regions and agents in the admin panel or with the CLI,
which gains 'api admin grant|revoke'. The first user of a self-hosted
installation becomes a platform admin. Region lists show the org's own
regions first.

Closes #52
Refs #29

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

156 lines
5.5 KiB
Go

package api_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func (b *browser) createRegion(key string) string {
b.t.Helper()
st, body := b.do("POST", "/api/v1/org/regions", map[string]any{"key": key, "name": "Office " + key})
if st != http.StatusCreated {
b.t.Fatalf("create region %s = %d %v", key, st, body)
}
return body["id"].(string)
}
func (b *browser) regionIDs() []string {
b.t.Helper()
_, body := b.do("GET", "/api/v1/org/regions", nil)
var ids []string
for _, r := range body["regions"].([]any) {
ids = append(ids, r.(map[string]any)["id"].(string))
}
return ids
}
func TestOrgRegionsAndAgents(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
_, platformRegion := e.platformChecker(t, uniq("shared-"))
a := e.browser(t)
a.signup("a@"+uniq("a")+".test", uniq("org-a-"))
b := e.browser(t)
b.signup("b@"+uniq("b")+".test", uniq("org-b-"))
aOffice := a.createRegion("office")
bOffice := b.createRegion("office") // same key in another org is fine
t.Run("own regions first, then platform", func(t *testing.T) {
ids := a.regionIDs()
if len(ids) < 2 || ids[0] != aOffice {
t.Errorf("org A regions = %v, want %s first", ids, aOffice)
}
for _, id := range ids {
if id == bOffice {
t.Errorf("org A sees org B's region")
}
}
found := false
for _, id := range ids {
found = found || id == platformRegion
}
if !found {
t.Errorf("org A regions = %v, want platform region %s", ids, platformRegion)
}
})
t.Run("foreign regions are unusable", func(t *testing.T) {
st, body := b.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "x", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{aOffice},
})
expect(t, "monitor in foreign region", st, body, http.StatusUnprocessableEntity, "invalid_region")
st, body = a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "x", "region_id": bOffice})
expect(t, "agent in foreign region", st, body, http.StatusUnprocessableEntity, "invalid_region")
st, body = a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "x", "region_id": platformRegion})
expect(t, "org agent in platform region", st, body, http.StatusUnprocessableEntity, "invalid_region")
st, body = a.do("DELETE", "/api/v1/org/regions/"+platformRegion, nil)
expect(t, "org deletes platform region", st, body, http.StatusNotFound, "not_found")
})
t.Run("org checker runs only its org's monitors", func(t *testing.T) {
st, body := a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": aOffice})
if st != http.StatusCreated {
t.Fatalf("create org agent = %d %v", st, body)
}
checker, _ := e.startChecker(t, body["token"].(string))
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer target.Close()
st, body = a.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "intranet", "type": "http", "target": target.URL, "interval_seconds": 60, "regions": []string{aOffice},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
waitFor(t, 10*time.Second, "org checker reports", func() bool {
var n int
_ = e.dbPool.QueryRow(context.Background(), `SELECT count(*) FROM check_results WHERE checker_id = $1 AND region = $2`, checker, aOffice).Scan(&n)
return n > 0
})
st, body = a.do("DELETE", "/api/v1/org/regions/"+aOffice, nil)
expect(t, "delete region in use", st, body, http.StatusConflict, "region_in_use")
_, agents := a.do("GET", "/api/v1/org/agents", nil)
if n := len(agents["agents"].([]any)); n != 1 {
t.Errorf("org A agents = %d, want 1", n)
}
_, agents = b.do("GET", "/api/v1/org/agents", nil)
if n := len(agents["agents"].([]any)); n != 0 {
t.Errorf("org B agents = %d, want 0", n)
}
})
t.Run("platform regions are admin only", func(t *testing.T) {
st, body := a.do("POST", "/api/v1/admin/regions", map[string]any{"key": "global"})
expect(t, "non-admin creates platform region", st, body, http.StatusForbidden, "forbidden")
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), a.userIDSelf())
})
if err != nil {
t.Fatal(err)
}
key := uniq("glob-")
st, body = a.do("POST", "/api/v1/admin/regions", map[string]any{"key": key, "name": "Global"})
if st != http.StatusCreated || body["own"] != false {
t.Fatalf("admin creates platform region = %d %v", st, body)
}
global := body["id"].(string)
st, body = a.do("POST", "/api/v1/admin/agents", map[string]any{"kind": "checker", "name": "g1", "region_id": global})
expect(t, "admin creates platform agent", st, body, http.StatusCreated, "")
found := false
for _, id := range b.regionIDs() {
found = found || id == global
}
if !found {
t.Errorf("org B does not see the new platform region")
}
for _, path := range []string{"/admin", "/settings/regions"} {
if got := a.visit(path); got.Path != path {
t.Errorf("admin GET %s ended at %s", path, got.Path)
}
}
if got := b.visit("/admin"); got.Path != "/" {
t.Errorf("non-admin GET /admin ended at %s, want /", got.Path)
}
})
}
func (b *browser) userIDSelf() uuid.UUID {
b.t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
return uuid.MustParse(me["id"].(string))
}