package api_test import ( "context" "net/http" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "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 TestHousekeepingPurgesOnlyOldRows(t *testing.T) { e := newEnvWith(t, func(c *config.API) { c.Retention = config.Retention{Daily: 365 * 24 * time.Hour, Housekeeping: 30 * 24 * time.Hour} }) _, region := e.platformChecker(t, uniq("eu-")) owner := e.browser(t) owner.signup("o@"+uniq("hk")+".test", uniq("hk-")) st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ "name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region}, }) if st != http.StatusCreated { t.Fatal(body) } monitor := uuid.MustParse(body["id"].(string)) org := uuid.MustParse(owner.orgID()) user := owner.userIDSelf() role := uuid.MustParse(owner.roleID("viewer")) ctx := context.Background() now := time.Now() old, fresh := now.Add(-40*24*time.Hour), now.Add(-time.Hour) ancient := now.Add(-400 * 24 * time.Hour) var oldInc, freshInc, ancientInc uuid.UUID err := e.asSystem(t, func(tx pgx.Tx) error { var channel uuid.UUID if err := tx.QueryRow(ctx, `INSERT INTO notification_channels (org_id, name, type, config) VALUES ($1, 'c', 'webhook', '{}') RETURNING id`, org).Scan(&channel); err != nil { return err } for _, inc := range []struct { id *uuid.UUID started time.Time }{{&ancientInc, ancient}, {&oldInc, old}, {&freshInc, fresh}} { if err := tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at) VALUES ($1, $2, $3::timestamptz, $3::timestamptz + interval '5 minutes') RETURNING id`, org, monitor, inc.started).Scan(inc.id); err != nil { return err } } for _, n := range []struct { inc uuid.UUID status string created time.Time }{{oldInc, "sent", old}, {freshInc, "sent", fresh}} { if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'opened', $4, $5)`, org, channel, n.inc, n.status, n.created); err != nil { return err } } if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'resolved', 'pending', $4)`, org, channel, oldInc, old); err != nil { return err } for i, exp := range []time.Time{old, now.Add(24 * time.Hour)} { if _, err := tx.Exec(ctx, `INSERT INTO invitations (org_id, email, role_id, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)`, org, uniq("i")+"@x.test", role, []byte(uniq("h")), exp); err != nil { return err } if _, err := tx.Exec(ctx, `INSERT INTO api_tokens (org_id, user_id, name, token_hash, prefix, permissions, expires_at) VALUES ($1, $2, $3, $4, 'usk_x', '{}', $5)`, org, user, "t"+string(rune('a'+i)), []byte(uniq("t")), exp); err != nil { return err } } return nil }) if err != nil { t.Fatal(err) } if err := e.api.Housekeep(ctx, now); err != nil { t.Fatalf("Housekeep() = %v", err) } count := func(query string) int { var n int _ = e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(ctx, query, org).Scan(&n) }) return n } for query, want := range map[string]int{ `SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'sent'`: 1, `SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'pending'`: 1, `SELECT count(*) FROM invitations WHERE org_id = $1`: 1, `SELECT count(*) FROM api_tokens WHERE org_id = $1 AND expires_at IS NOT NULL`: 1, `SELECT count(*) FROM incidents WHERE org_id = $1`: 2, } { if got := count(query); got != want { t.Errorf("%s = %d, want %d", query, got, want) } } } func TestAdminSeesStorage(t *testing.T) { e := newEnv(t) a := e.browser(t) a.signup("a@"+uniq("st")+".test", uniq("st-")) 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) } st, _, html := a.page("/admin") if st != http.StatusOK { t.Fatalf("GET /admin = %d", st) } for _, want := range []string{"Data storage", "Raw results", "Daily aggregate", "Background jobs", "Compression"} { if !strings.Contains(html, want) { t.Errorf("admin page lacks %q", want) } } } // asSystem runs fn in a transaction that bypasses tenant isolation. func (e *env) asSystem(t *testing.T, fn func(pgx.Tx) error) error { t.Helper() ctx := context.Background() return pgx.BeginFunc(ctx, e.dbPool, func(tx pgx.Tx) error { if _, err := tx.Exec(ctx, `SELECT set_config('app.scope', 'system', true)`); err != nil { return err } return fn(tx) }) }