Files
uptimesebi/internal/api/checker_test.go
T
Sebastian UnterschützandClaude Opus 5.5 d9891bb050 feat!: let checkers and status page servers reach data only through the api
Only cmd/api connects to Postgres and Redis. Agents authenticate with
tokens created by 'api agent create' and use /agent/v1: checkers long
poll for jobs, which doubles as heartbeat, and report results in
batches. Organizations manage monitors through /api/v1/org/monitors.

BREAKING CHANGE: cmd/checker and cmd/statuspage no longer read
UPTIME_DATABASE_URL or UPTIME_REDIS_*; they need UPTIME_API_URL and
UPTIME_AGENT_TOKEN. UPTIME_CHECKER_REGION is replaced by the region bound
to the agent token.

Closes #10
Closes #11
Closes #12
Closes #13
Closes #49

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

206 lines
6.0 KiB
Go

package api_test
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
"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/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// agentToken creates a checker agent for region directly in the database,
// as "api agent create" would.
func (e *env) agentToken(t *testing.T, region string) string {
t.Helper()
tok := api.AgentTokenPrefix + auth.RandomToken()
ctx := context.Background()
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: region}); err != nil {
return err
}
_, err := q.CreateAgent(ctx, store.CreateAgentParams{
Kind: "checker", Name: "test-" + region, Region: &region, TokenHash: api.HashToken(tok), Prefix: tok[:10],
})
return err
})
if err != nil {
t.Fatalf("creating agent: %v", err)
}
return tok
}
// startChecker runs a checker instance until the returned stop is called.
func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) {
t.Helper()
id := uuid.New()
client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client())
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = checker.New(client, 8, slog.New(slog.DiscardHandler)).Run(ctx, 5*time.Second)
}()
var once bool
stop := func() {
if once {
return
}
once = true
cancel()
<-done
}
t.Cleanup(stop)
return id, stop
}
func TestCheckersPerRegion(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/down" {
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer target.Close()
eu, us := uniq("eu-"), uniq("us-")
euTok, usTok := e.agentToken(t, eu), e.agentToken(t, us)
euA, stopA := e.startChecker(t, euTok)
euB, _ := e.startChecker(t, euTok)
usC, _ := e.startChecker(t, usTok)
owner := e.browser(t)
owner.signup("o@"+uniq("c")+".test", uniq("chk-"))
org := owner.orgID()
// Instances register on their first poll.
waitFor(t, 5*time.Second, "both eu instances registered", func() bool {
_, body := owner.do("GET", "/api/v1/regions", nil)
for _, r := range body["regions"].([]any) {
r := r.(map[string]any)
if r["key"] == eu && r["instances"] == float64(2) {
return true
}
}
return false
})
const n = 30
for i := range n {
path := "/up"
if i == 0 {
path = "/down"
}
regions := []string{eu}
if i < 3 {
regions = append(regions, us)
}
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "http", "target": target.URL + path, "interval_seconds": 3600, "regions": regions,
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
}
count := func(checker uuid.UUID) (total, failed int) {
_ = e.dbPool.QueryRow(context.Background(),
`SELECT count(*), count(*) FILTER (WHERE NOT ok) FROM check_results WHERE org_id = $1 AND checker_id = $2`,
org, checker).Scan(&total, &failed)
return total, failed
}
waitFor(t, 15*time.Second, "all first runs reported", func() bool {
a, _ := count(euA)
b, _ := count(euB)
c, _ := count(usC)
return a+b == n && c == 3
})
a, aFailed := count(euA)
b, bFailed := count(euB)
if a < 5 || b < 5 {
t.Errorf("eu instances ran %d and %d checks, want both to get a random share of %d", a, b, n)
}
if aFailed+bFailed != 1 {
t.Errorf("failed eu checks = %d, want 1 (the /down monitor)", aFailed+bFailed)
}
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
withLatest := 0
for _, m := range body["monitors"].([]any) {
if len(m.(map[string]any)["latest"].([]any)) > 0 {
withLatest++
}
}
if withLatest != n {
t.Errorf("monitors with latest results = %d, want %d", withLatest, n)
}
// Stopping one eu instance leaves the other to take every eu check.
stopA()
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "after", "type": "tcp", "target": target.Listener.Addr().String(), "interval_seconds": 3600, "regions": []string{eu},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
before, _ := count(euB)
waitFor(t, 10*time.Second, "remaining eu instance runs the new monitor", func() bool {
now, _ := count(euB)
return now == before+1
})
if after, _ := count(euA); after != a {
t.Errorf("stopped instance ran %d more checks", after-a)
}
}
func TestAgentAuth(t *testing.T) {
e := newEnv(t)
tok := e.agentToken(t, uniq("x-"))
ctx := context.Background()
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized)
}
h, err := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx)
if err != nil || h.Kind != "checker" {
t.Errorf("Hello() = %+v, %v; want checker", h, err)
}
// User API tokens and sessions do not open the agent API.
owner := e.browser(t)
owner.signup("a@"+uniq("a")+".test", uniq("auth-"))
st, _ := owner.do("GET", "/agent/v1/hello", nil)
if st == http.StatusOK {
t.Error("session opened the agent API")
}
}
func (b *browser) orgID() string {
b.t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
return me["active_org"].(string)
}
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(d)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for: %s", what)
}
time.Sleep(100 * time.Millisecond)
}
}