package server_test import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "errors" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "git.breakpilot.com/platform/tenant-registry/internal/gitea" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/secretbox" "git.breakpilot.com/platform/tenant-registry/internal/server" "git.breakpilot.com/platform/tenant-registry/internal/store" ) const sentinelToken = "SENTINELxSENTINELxSENTINEL" // test value, low entropy on purpose (gitleaks) var berlin = func() *time.Location { l, err := time.LoadLocation("Europe/Berlin") if err != nil { return time.UTC } return l }() func testSecrets(t *testing.T) *secretbox.Box { t.Helper() key := make([]byte, 32) _, _ = rand.Read(key) box, err := secretbox.New(base64.StdEncoding.EncodeToString(key)) if err != nil { t.Fatal(err) } return box } // fakeGitea serves //api/v1/admin/users: "ok" and "second" list // users (two per page, then an empty page), "fail" answers 500 with the // token in the body. Every request must carry the token as a header. func fakeGitea(t *testing.T) *httptest.Server { t.Helper() never := "1970-01-01T01:00:00+01:00" signed := "2026-11-10T09:00:00+01:00" users := map[string][]map[string]any{ "ok": { {"login": "ada", "login_name": "kc-ada", "last_login": signed}, // member, signed in {"login": "bob", "login_name": "kc-bob", "last_login": never}, // member, never signed in {"login": "cy", "login_name": "kc-cy", "last_login": signed}, // member, signed in {"login": "ops-bp", "login_name": "staff-sub", "last_login": signed}, // staff: company realm {"login": "breakpilot-ci", "login_name": "", "last_login": signed}, // local CI bot {"login": "gone", "login_name": "kc-gone", "last_login": signed}, // removed from the workspace {"login": "dee", "login_name": "kc-dee"}, // member, no last_login at all }, "second": { {"login": "ada", "login_name": "kc-ada", "last_login": signed}, // the same person counts once {"login": "eve", "login_name": "kc-eve", "last_login": signed}, }, } return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "token "+sentinelToken || strings.Contains(r.URL.RawQuery, sentinelToken) { w.WriteHeader(http.StatusUnauthorized) return } instance, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") if rest != "api/v1/admin/users" { http.NotFound(w, r) return } if instance == "fail" { w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte("boom " + sentinelToken)) return } list := users[instance] page, err := strconv.Atoi(r.URL.Query().Get("page")) if err != nil || page < 1 { page = 1 } lo, hi := min((page-1)*2, len(list)), min(page*2, len(list)) _ = json.NewEncoder(w).Encode(list[lo:hi]) })) } func TestModuleUsers_adminToken(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { var bodies []string do := func(method, path string, body any) (*http.Response, []byte) { resp, raw := h.do(method, path, body) bodies = append(bodies, string(raw)) return resp, raw } git := createService(t, h, h.tenant.ID, map[string]any{"kind": "git", "name": "Git", "url": "https://git.k-00001.example", "sku": "INF-GIT-CLD-STD"}) runner := createService(t, h, h.tenant.ID, map[string]any{"kind": "ci-runner", "name": "Runner", "url": "https://git.k-00001.example", "sku": "INF-CI-CLD-STD"}) path := "/v1/admin/tenants/" + h.tenant.ID + "/managed-services/" + git.ID + "/admin-token" // Without SECRETS_ENCRYPTION_KEY nothing is stored. if resp, raw := do("PUT", path, map[string]any{"token": sentinelToken}); resp.StatusCode != 503 || !strings.Contains(string(raw), "secrets_disabled") { t.Fatalf("secrets off: %d %s", resp.StatusCode, raw) } h.app.Secrets = testSecrets(t) for _, c := range []struct { name string path string body any code int err string }{ {"no token field", path, map[string]any{}, 400, "invalid_token"}, {"inner space", path, map[string]any{"token": "a b"}, 400, "invalid_token"}, {"too long", path, map[string]any{"token": strings.Repeat("a", 513)}, 400, "invalid_token"}, {"runner", "/v1/admin/tenants/" + h.tenant.ID + "/managed-services/" + runner.ID + "/admin-token", map[string]any{"token": sentinelToken}, 400, "invalid_kind"}, {"unknown service", "/v1/admin/tenants/" + h.tenant.ID + "/managed-services/11111111-1111-1111-1111-111111111111/admin-token", map[string]any{"token": sentinelToken}, 404, ""}, {"other tenant", "/v1/admin/tenants/11111111-1111-1111-1111-111111111111/managed-services/" + git.ID + "/admin-token", map[string]any{"token": sentinelToken}, 404, ""}, } { if resp, raw := do("PUT", c.path, c.body); resp.StatusCode != c.code || !strings.Contains(string(raw), c.err) { t.Fatalf("%s: %d %s", c.name, resp.StatusCode, raw) } } resp, raw := do("PUT", path, map[string]any{"token": " " + sentinelToken + " "}) if resp.StatusCode != 200 || !strings.Contains(string(raw), `"admin_token_set":true`) { t.Fatalf("set: %d %s", resp.StatusCode, raw) } ms, err := h.store.GetManagedService(context.Background(), git.ID) if err != nil || len(ms.AdminTokenSealed) == 0 || strings.Contains(string(ms.AdminTokenSealed), sentinelToken) { t.Fatalf("stored sealed: %v %+v", err, ms) } if plain, err := h.app.Secrets.Open(ms.AdminTokenSealed, []byte(git.ID)); err != nil || string(plain) != sentinelToken { t.Fatalf("opened: %v %q", err, plain) } // The admin list says it is set; the tenant view says nothing. if _, raw := do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/managed-services", nil); !strings.Contains(string(raw), `"admin_token_set":true`) { t.Fatalf("admin list: %s", raw) } if _, raw := do("GET", "/v1/tenants/"+h.tenant.ID+"/managed-services", nil); strings.Contains(string(raw), "admin_token") { t.Fatalf("tenant view: %s", raw) } // A PATCH keeps the token. if resp, raw := do("PATCH", "/v1/admin/tenants/"+h.tenant.ID+"/managed-services/"+git.ID, map[string]any{"status": "active"}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"admin_token_set":true`) { t.Fatalf("patch: %d %s", resp.StatusCode, raw) } // "" clears (works without the key as well). h.app.Secrets = nil if resp, raw := do("PUT", path, map[string]any{"token": ""}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"admin_token_set":false`) { t.Fatalf("clear: %d %s", resp.StatusCode, raw) } if ms, _ := h.store.GetManagedService(context.Background(), git.ID); len(ms.AdminTokenSealed) != 0 { t.Fatalf("not cleared: %+v", ms) } for _, action := range []string{"managed_service.admin_token_set", "managed_service.admin_token_cleared"} { evs, _, _ := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: h.tenant.ID, Action: action}) if len(evs) != 1 || evs[0].TargetID != git.ID { t.Fatalf("%s: %+v", action, evs) } b, _ := json.Marshal(evs[0]) bodies = append(bodies, string(b)) } if _, raw := do("GET", "/v1/audit?tenant_id="+h.tenant.ID, nil); len(raw) == 0 { t.Fatal("audit list empty") } for _, b := range bodies { if strings.Contains(b, sentinelToken) { t.Fatalf("token in a response: %s", b) } } }) } // setToken stores the sentinel token for a service straight in the store. func setToken(t *testing.T, h *testHarness, id string) { t.Helper() sealed, err := h.app.Secrets.Seal([]byte(sentinelToken), []byte(id)) if err != nil { t.Fatal(err) } if err := h.store.SetManagedServiceAdminToken(context.Background(), id, sealed); err != nil { t.Fatal(err) } } func activeGit(t *testing.T, h *testHarness, tenantID, url string) store.ManagedService { t.Helper() return createService(t, h, tenantID, map[string]any{"kind": "git", "name": "Git", "url": url, "sku": "INF-GIT-CLD-STD", "status": "active"}) } func TestModuleUsers_count(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { ctx := context.Background() gt := fakeGitea(t) defer gt.Close() h.app.Secrets = testSecrets(t) h.app.Gitea = &gitea.Client{HTTP: gt.Client()} // 23:30 UTC on 30.11. is already 01.12. in Berlin. now := time.Date(2026, 11, 30, 23, 30, 0, 0, time.UTC) h.app.Now = func() time.Time { return now } member := func(id string) keycloak.OrgMember { return keycloak.OrgMember{UserID: id, Enabled: true} } h.kcMock.Members["acme"] = []keycloak.OrgMember{member("kc-ada"), member("kc-bob"), member("kc-cy"), member("kc-dee"), member("kc-eve")} // acme: two active instances (union), plus a halted one and a runner // that are not read. a1 := activeGit(t, h, h.tenant.ID, gt.URL+"/ok") a2 := activeGit(t, h, h.tenant.ID, gt.URL+"/second") setToken(t, h, a1.ID) setToken(t, h, a2.ID) halted := createService(t, h, h.tenant.ID, map[string]any{"kind": "git", "name": "Old", "url": gt.URL + "/fail", "sku": "INF-GIT-CLD-STD", "status": "halted"}) setToken(t, h, halted.ID) // beta: one instance fails; nothing is written for beta. beta, err := h.store.CreateTenant(ctx, store.TenantCreate{Slug: "beta", Name: "Beta", Plan: "professional"}) if err != nil { t.Fatal(err) } h.kcMock.Members["beta"] = []keycloak.OrgMember{member("kc-ada")} b1 := activeGit(t, h, beta.ID, gt.URL+"/ok") b2 := activeGit(t, h, beta.ID, gt.URL+"/fail") setToken(t, h, b1.ID) setToken(t, h, b2.ID) // gamma: no token set. gamma, err := h.store.CreateTenant(ctx, store.TenantCreate{Slug: "gamma", Name: "Gamma", Plan: "professional"}) if err != nil { t.Fatal(err) } g1 := activeGit(t, h, gamma.ID, gt.URL+"/ok") // delta: no organization in Keycloak → a real 0. delta, err := h.store.CreateTenant(ctx, store.TenantCreate{Slug: "delta", Name: "Delta", Plan: "professional"}) if err != nil { t.Fatal(err) } d1 := activeGit(t, h, delta.ID, gt.URL+"/ok") setToken(t, h, d1.ID) resp, raw := h.do("POST", "/v1/internal/module-users/count", nil) if resp.StatusCode != 200 { t.Fatalf("count: %d %s", resp.StatusCode, raw) } if strings.Contains(string(raw), sentinelToken) || strings.Contains(string(raw), "boom") || strings.Contains(string(raw), "127.0.0.1") { t.Fatalf("report leaks: %s", raw) } var rep server.ModuleUserReport _ = json.Unmarshal(raw, &rep) if rep.Day != "2026-12-01" || rep.Tenants != 4 || rep.GitCounted != 2 { t.Fatalf("report: %s", raw) } joined := strings.Join(rep.Errors, "\n") if len(rep.Errors) != 2 || !strings.Contains(joined, beta.ID+": git "+b2.ID+": page 1: gitea: status 500") || !strings.Contains(joined, gamma.ID+": git "+g1.ID+": no admin token set") { t.Fatalf("errors: %q", rep.Errors) } counts := func(tenantID, month string) []store.ModuleUserCount { t.Helper() c, err := h.store.ModuleUserCounts(ctx, tenantID, month) if err != nil { t.Fatal(err) } return c } // ada, cy (ok) + eve (second); bob and dee never signed in, staff, // the bot and the removed member don't count. if c := counts(h.tenant.ID, "2026-12"); len(c) != 1 || c[0] != (store.ModuleUserCount{Module: "managed-git", Count: 3, PeakDay: "2026-12-01"}) { t.Fatalf("acme: %+v", c) } if c := counts(beta.ID, "2026-12"); len(c) != 0 { t.Fatalf("beta written despite a failing instance: %+v", c) } if c := counts(gamma.ID, "2026-12"); len(c) != 0 { t.Fatalf("gamma: %+v", c) } if c := counts(delta.ID, "2026-12"); len(c) != 1 || c[0].Count != 0 { t.Fatalf("delta: %+v", c) } // A re-run after a member left overwrites the day. h.kcMock.Members["acme"] = []keycloak.OrgMember{member("kc-ada")} h.app.CountModuleUsers(ctx) if c := counts(h.tenant.ID, "2026-12"); c[0].Count != 1 { t.Fatalf("rerun: %+v", c) } // Keycloak down: reported, day untouched. h.kcMock.FailNext = errors.New("keycloak down") rep = h.app.CountModuleUsers(ctx) if !strings.Contains(strings.Join(rep.Errors, "\n"), h.tenant.ID+": members: keycloak down") || counts(h.tenant.ID, "2026-12")[0].Count != 1 { t.Fatalf("keycloak down: %q", rep.Errors) } }) } func TestModuleUsers_licences(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { ctx := context.Background() now := time.Now().UTC() h.app.Now = func() time.Time { return now } local := now.In(berlin) thisMonth := local.Format("2006-01") firstOfMonth := time.Date(local.Year(), local.Month(), 1, 12, 0, 0, 0, berlin) lastMonth := firstOfMonth.AddDate(0, 0, -1) // noon on the previous month's last day longAgo := time.Date(local.Year(), local.Month()-2, 15, 12, 0, 0, 0, berlin) // two months back lic := func(product, subject, device string, seen *time.Time) { t.Helper() l, err := h.store.CreateLicence(ctx, store.Licence{Kid: "k", TenantID: h.tenant.ID, Product: product, Subject: subject, Device: device, ExpiresAt: now.Add(time.Hour)}) if err != nil { t.Fatal(err) } if seen != nil { if err := h.store.TouchLicence(ctx, l.ID, *seen); err != nil { t.Fatal(err) } } } lic("werkpilot", "kc-ada", "laptop", &now) lic("werkpilot", "kc-ada", "desktop", nil) // the same person twice lic("werkpilot", "kc-bob", "laptop", &lastMonth) lic("werkpilot", "kc-old", "laptop", &longAgo) lic("werkpilot", "apikey:k1", "ci:runner-1", &now) // CI licence lic("werkpilot", "kc-cy", "ci:runner-2", &now) // CI device lic("werkpilot", "service:"+h.tenant.ID, "", &now) // issued by a service client lic("firmwerk", "kc-ada", "laptop", &now) lic("pruefwerk", "kc-zed", "", &now) // not a licence module rep := h.app.CountModuleUsers(ctx) if len(rep.Errors) != 0 { t.Fatalf("errors: %q", rep.Errors) } // This month (created_at is now): ada, bob, old for Werkpilot; ada for Firmwerk. got, _ := h.store.ModuleUserCounts(ctx, h.tenant.ID, thisMonth) want := []store.ModuleUserCount{{Module: "firmwerk", Count: 1}, {Module: "werkpilot", Count: 3}} if len(got) != 2 || got[0] != want[0] || got[1] != want[1] { t.Fatalf("this month: %+v", got) } // The previous month: bob, seen there last. if got, _ := h.store.ModuleUserCounts(ctx, h.tenant.ID, lastMonth.Format("2006-01")); len(got) != 1 || got[0] != (store.ModuleUserCount{Module: "werkpilot", Count: 1}) { t.Fatalf("last month: %+v", got) } // Two months back is outside the sweep. if got, _ := h.store.ModuleUserCounts(ctx, h.tenant.ID, longAgo.Format("2006-01")); len(got) != 0 { t.Fatalf("long ago: %+v", got) } // Idempotent: nothing new on a re-run. if rep := h.app.CountModuleUsers(ctx); rep.LicenceUsersAdded != 0 { t.Fatalf("rerun added %d", rep.LicenceUsersAdded) } }) } func TestModuleUsers_reads(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { ctx := context.Background() h.app.Now = func() time.Time { return time.Date(2026, 11, 17, 10, 0, 0, 0, time.UTC) } for _, d := range []store.ModuleUserDay{ {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-11-03", Count: 4}, {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-11-09", Count: 6}, {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-11-12", Count: 6}, // tie: the earlier day is the peak {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-11-15", Count: 5}, {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-10-31", Count: 9}, // another month {TenantID: h.tenant.ID, Module: "managed-git", Day: "2026-12-01", Count: 9}, } { if err := h.store.PutModuleUserDay(ctx, d); err != nil { t.Fatal(err) } } if n, err := h.store.AddModuleUsersSeen(ctx, h.tenant.ID, "werkpilot", "2026-11", []string{"a", "b", "a", ""}); err != nil || n != 2 { t.Fatalf("add seen: %d %v", n, err) } if n, _ := h.store.AddModuleUsersSeen(ctx, h.tenant.ID, "werkpilot", "2026-11", []string{"b", "c"}); n != 1 { t.Fatalf("add seen again: %d", n) } _, _ = h.store.AddModuleUsersSeen(ctx, h.tenant.ID, "werkpilot", "2026-10", []string{"z"}) if err := h.store.PutModuleUserDay(ctx, store.ModuleUserDay{TenantID: "11111111-1111-1111-1111-111111111111", Module: "managed-git", Day: "2026-11-01", Count: 1}); !errors.Is(err, store.ErrNotFound) { t.Fatalf("unknown tenant: %v", err) } if _, err := h.store.AddModuleUsersSeen(ctx, h.tenant.ID, "werkpilot", "2026-13", []string{"x"}); !errors.Is(err, store.ErrInvalidInput) { t.Fatalf("bad month: %v", err) } want := `{"tenant_id":"` + h.tenant.ID + `","month":"2026-11","items":[{"module":"managed-git","count":6,"peak_day":"2026-11-09"},{"module":"werkpilot","count":3}]}` for _, path := range []string{ "/v1/admin/tenants/" + h.tenant.ID + "/module-users?month=2026-11", "/v1/admin/tenants/" + h.tenant.ID + "/module-users", // default: the current Berlin month "/v1/tenants/" + h.tenant.ID + "/module-users?month=2026-11", } { resp, raw := h.do("GET", path, nil) if resp.StatusCode != 200 || strings.TrimSpace(string(raw)) != want { t.Fatalf("%s: %d %s", path, resp.StatusCode, raw) } } if _, raw := h.do("GET", "/v1/tenants/"+h.tenant.ID+"/module-users?month=2026-09", nil); !strings.Contains(string(raw), `"items":[]`) { t.Fatalf("empty month: %s", raw) } for _, m := range []string{"2026-1", "2026-13", "nov", "2026-11-01"} { if resp, raw := h.do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/module-users?month="+m, nil); resp.StatusCode != 400 || !strings.Contains(string(raw), "invalid_month") { t.Fatalf("month %q: %d %s", m, resp.StatusCode, raw) } } if resp, _ := h.do("GET", "/v1/admin/tenants/11111111-1111-1111-1111-111111111111/module-users", nil); resp.StatusCode != 404 { t.Fatalf("unknown tenant: %d", resp.StatusCode) } }) }