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/checker" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) // platformChecker creates a platform region with a checker agent directly // in the database, as "api agent create" would, and returns the agent token // and the region ID. func (e *env) platformChecker(t *testing.T, key string) (string, string) { t.Helper() ctx := context.Background() var ( tok string region store.Region ) err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error if region, err = q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: key}); err != nil { return err } var params store.CreateAgentParams tok, params = api.NewAgentToken(nil, "checker", "test-"+key, ®ion.ID) _, err = q.CreateAgent(ctx, params) return err }) if err != nil { t.Fatalf("creating agent: %v", err) } return tok, region.ID.String() } // 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() euTok, eu := e.platformChecker(t, uniq("eu-")) usTok, us := e.platformChecker(t, uniq("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/org/regions", nil) for _, r := range body["regions"].([]any) { r := r.(map[string]any) if r["id"] == 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.platformChecker(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) } }