Files
uptimesebi/internal/api/regions_test.go
T
Sebastian UnterschützandClaude Opus 5.5 e281bcd604
ci / build (pull_request) Successful in 11m14s
ci / lint (pull_request) Successful in 14m23s
ci / image (pull_request) Successful in 3m58s
ci / test (pull_request) Successful in 18m0s
feat(console): install instructions for new agents, outdated agents
Creating a checker or status page server now shows how to install it
next to the one-time token: the one-liner of the platform's install
script and the Compose files with .env, with the token and kind filled
in, and a switch between the self-updating and the plain image. Agents
behind the platform's release are marked outdated in the organization's
and the admin's agent lists, which also show each agent's release and
the platform's.

Closes #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 19:14:20 +01:00

203 lines
7.4 KiB
Go

package api_test
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"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))
}
func TestAgentInstallConsole(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.PublicURL = "https://uptime.example.com" })
owner := e.browser(t)
owner.signup("o@"+uniq("inst")+".test", uniq("inst-"))
st, body := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "statuspage", "name": "pages"})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, body)
}
tok := body["token"].(string)
old := buildinfo.Version
buildinfo.Version = "v1.4.2"
t.Cleanup(func() { buildinfo.Version = old })
_, _, html := owner.page("/settings/regions")
for _, want := range []string{
"curl -fsSL https://uptime.example.com/install.sh | sudo sh -s -- {kind} --token {token}{manual}",
`data-channel="latest"`, "Update automatically", "}-statuspage:${UPTIME_AGENT_TAG",
"The platform runs v1.4.2.",
} {
if !strings.Contains(html, want) {
t.Errorf("the page lacks %q", want)
}
}
if strings.Contains(html, ">· outdated<") {
t.Error("an agent that never reported is marked outdated")
}
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "v1.4.1").WithHTTPClient(e.srv.Client())
if _, err := client.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, _, html := owner.page("/settings/regions"); !strings.Contains(html, "v1.4.1") || !strings.Contains(html, "outdated") {
t.Error("an agent behind the platform is not marked outdated")
}
current := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "v1.4.2").WithHTTPClient(e.srv.Client())
if _, err := current.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, _, html := owner.page("/settings/regions"); strings.Contains(html, "· outdated") {
t.Error("an agent on the platform's release is marked outdated")
}
}