feat(metering): count module users per tenant and month
Daily Europe/Berlin job: Managed Git = members signed in to the tenant's active instances; Werkpilot/Firmwerk = people with their own licence in use in the month. Staff PUT for the Gitea admin token, staff and tenant reads of the month's counts, POST /v1/internal/module-users/count on demand (route group module-users). No invoicing yet (t72). Refs: t81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f9ada789ea
commit
692a9dd378
10 files changed
+1072
-2
No files matched your search
@@ -102,6 +102,10 @@ Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary:
|
||||
| POST | `/v1/licences/{id}/revoke` | Revoke |
|
||||
| POST | `/v1/licences/heartbeat` | CLI phone-home (licence JWT is the credential; renews past half-life) |
|
||||
| GET | `/.well-known/licence-keys.json` | JWKS (Ed25519) for offline licence verification |
|
||||
| PUT | `/v1/admin/tenants/{id}/managed-services/{sid}/admin-token` | Set or clear a Git instance's `read:admin` token (staff; sealed, write-only) |
|
||||
| GET | `/v1/admin/tenants/{id}/module-users?month=` | Module users per month (staff) |
|
||||
| GET | `/v1/tenants/{id}/module-users?month=` | Module users per month (tenant; `portal:billing.view`) |
|
||||
| POST | `/v1/internal/module-users/count` | Run the daily module-user count now (group `module-users`) |
|
||||
|
||||
State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec.
|
||||
|
||||
@@ -181,6 +185,42 @@ LiteLLM virtual key** (`POST /key/generate` on `LITELLM_BASE_URL` with
|
||||
records `llm_key_deleted`. Firmwerk licences get no key.
|
||||
- `GET /v1/internal/erp/status` reports `llm_keys_enabled`.
|
||||
|
||||
## Module users (t81)
|
||||
|
||||
The registry counts the users of each module per tenant and Europe/Berlin
|
||||
month (migration `0031`). Counting only: invoicing, usage events and the
|
||||
included amounts come later with t72.
|
||||
|
||||
| Module | Who counts | Month value |
|
||||
|---|---|---|
|
||||
| `managed-git` | Workspace members who have signed in to the tenant's active Git instance(s) at least once | Peak of the daily counts (`peak_day` = the earliest peak day) |
|
||||
| `werkpilot`, `firmwerk` | People whose own CLI licence was created or seen in the month | Distinct people in the month |
|
||||
|
||||
- **Managed Git**: each Gitea is read with its own token of scope
|
||||
`read:admin` (`GET {url}/api/v1/admin/users`, paged). Customers sign in
|
||||
only through Keycloak, so Gitea's `login_name` is the Keycloak user id; the
|
||||
count is the users whose `login_name` is a current workspace member's id
|
||||
and whose `last_login` is set. Staff (company realm, other ids) and the CI
|
||||
bot `breakpilot-ci` (local account, empty `login_name`) drop out. A person
|
||||
on two instances of the tenant counts once. A tenant with a failing
|
||||
instance, a missing token or a Keycloak error is reported and not written
|
||||
(never a 0); a re-run overwrites the day.
|
||||
- **Werkpilot / Firmwerk**: from `licences`; CI licences (`apikey:` subject,
|
||||
`ci:` device) and licences issued by a service client (`service:`) don't
|
||||
count. `last_seen_at` keeps only the latest time, so the job adds people
|
||||
to the month's set while it runs (`module_users_seen`). Each run sweeps
|
||||
the times in the current and the previous Berlin month, each into its own
|
||||
month, so a run after midnight still credits the evening before.
|
||||
- **Job**: once per Berlin day in the background (checked every 15 min;
|
||||
also once after a start, a re-run is harmless), or now with
|
||||
`POST /v1/internal/module-users/count`. The report lists errors per tenant
|
||||
and service id.
|
||||
- **Token**: `PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token`
|
||||
with `{"token": "…"}` (`""` clears). Stored AES-256-GCM sealed under
|
||||
`SECRETS_ENCRYPTION_KEY` (bound to the service id); without that key the
|
||||
PUT answers 503 and Managed Git is not counted. Never returned or logged;
|
||||
the admin view shows `admin_token_set`.
|
||||
|
||||
## Storage
|
||||
|
||||
The service picks its store based on `DATABASE_URL`:
|
||||
|
||||
+3
-1
@@ -158,7 +158,7 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
if !secrets.Enabled() {
|
||||
slog.Warn("SECRETS_ENCRYPTION_KEY not set — a reused Werkpilot CI licence cannot hand out its LiteLLM key again")
|
||||
slog.Warn("SECRETS_ENCRYPTION_KEY not set — a reused Werkpilot CI licence cannot hand out its LiteLLM key again, and Managed Git users are not counted (no admin tokens)")
|
||||
}
|
||||
|
||||
// LiteLLM virtual keys for Werkpilot licences (D6).
|
||||
@@ -211,6 +211,8 @@ func main() {
|
||||
go app.RunOutbox(ctx, cfg.ErpOutboxInterval)
|
||||
go app.RunReconcile(ctx, cfg.ErpReconcileEvery)
|
||||
go app.RunMail(ctx, 20*time.Second)
|
||||
// Module users (t81): once per Europe/Berlin day.
|
||||
go app.RunModuleUserCount(ctx, 15*time.Minute)
|
||||
|
||||
go func() {
|
||||
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s))
|
||||
|
||||
@@ -81,6 +81,8 @@ func routeGroup(method, path string) string {
|
||||
return "intake"
|
||||
case strings.HasPrefix(path, "/v1/internal/erp/"):
|
||||
return "erp"
|
||||
case strings.HasPrefix(path, "/v1/internal/module-users/"):
|
||||
return "module-users"
|
||||
case strings.HasPrefix(path, "/v1/entitlements"):
|
||||
return "entitlements"
|
||||
case strings.HasPrefix(path, "/v1/catalog"):
|
||||
|
||||
@@ -70,6 +70,7 @@ func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *ht
|
||||
var tenantSubresources = []string{
|
||||
"members", "documents", "projects", "contracts",
|
||||
"managed-services", "company-profile", "role-dataset", "store",
|
||||
"module-users",
|
||||
}
|
||||
|
||||
// tenantSubresource dispatches GET /v1/tenants/{id}/{sub}. Only the members
|
||||
@@ -95,6 +96,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
|
||||
s.listStore(w, r)
|
||||
case "capability-requests":
|
||||
s.listCapabilityRequests(w, r)
|
||||
case "module-users":
|
||||
s.tenantModuleUsers(w, r)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authz"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/gitea"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// Module users per tenant and month (t81, migration 0031). Counting only:
|
||||
// invoicing, usage events and included amounts come later with t72.
|
||||
//
|
||||
// - Managed Git: once per Berlin day, the workspace members who have
|
||||
// signed in to the tenant's active Gitea instance(s), read with the
|
||||
// instance's read:admin token. Gitea stores the Keycloak user id as
|
||||
// login_name, so intersecting with the workspace members drops staff
|
||||
// (company realm, other ids) and local accounts such as the CI bot. The
|
||||
// month's value is the peak day.
|
||||
// - Werkpilot / Firmwerk: the people with a CLI licence in use (created or
|
||||
// seen) in the month; API-key, service and CI licences don't count. The
|
||||
// job adds them to the month's set as it goes, because last_seen_at only
|
||||
// keeps the latest time. The month's value is the set's size.
|
||||
|
||||
// capBillingView: who may read the tenant's module users with a user token
|
||||
// (the portal shows them on its billing page).
|
||||
const capBillingView = "portal:billing.view"
|
||||
|
||||
const (
|
||||
adminTokenMaxLen = 512
|
||||
giteaTimeout = 20 * time.Second
|
||||
monthLayout = "2006-01"
|
||||
dayLayout = "2006-01-02"
|
||||
)
|
||||
|
||||
// licenceModules are the licence products whose users are counted.
|
||||
var licenceModules = map[string]bool{store.ModuleWerkpilot: true, store.ModuleFirmwerk: true}
|
||||
|
||||
func (s *Server) gitea() *gitea.Client {
|
||||
if s.Gitea != nil {
|
||||
return s.Gitea
|
||||
}
|
||||
return &gitea.Client{}
|
||||
}
|
||||
|
||||
// ─── admin token ──────────────────────────────────────────────────────────
|
||||
|
||||
type adminTokenReq struct {
|
||||
Token *string `json:"token"`
|
||||
}
|
||||
|
||||
// adminSetServiceToken is PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token:
|
||||
// stores the Git instance's read:admin token sealed (write-only), or clears
|
||||
// it with "". The answer is the service record, which says admin_token_set
|
||||
// and never carries the token.
|
||||
func (s *Server) adminSetServiceToken(w http.ResponseWriter, r *http.Request) {
|
||||
var in adminTokenReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if in.Token == nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_token", `token is required ("" clears it)`)
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(*in.Token)
|
||||
if len(token) > adminTokenMaxLen || strings.ContainsFunc(token, func(r rune) bool { return r <= ' ' || r == 0x7f }) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_token", "token must be at most 512 printable characters without spaces")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
t, ms, ok := s.adminManagedService(ctx, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if ms.Kind != store.ManagedServiceKindGit {
|
||||
writeError(w, http.StatusBadRequest, "invalid_kind", "only a git service has an admin token")
|
||||
return
|
||||
}
|
||||
var sealed []byte
|
||||
if token != "" {
|
||||
if !s.Secrets.Enabled() {
|
||||
writeError(w, http.StatusServiceUnavailable, "secrets_disabled", "SECRETS_ENCRYPTION_KEY is not set; the token cannot be stored")
|
||||
return
|
||||
}
|
||||
var err error
|
||||
if sealed, err = s.Secrets.Seal([]byte(token), []byte(ms.ID)); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "sealing the token failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.SetManagedServiceAdminToken(ctx, ms.ID, sealed); err != nil {
|
||||
writeManagedServiceError(w, err)
|
||||
return
|
||||
}
|
||||
updated, err := s.Store.GetManagedService(ctx, ms.ID)
|
||||
if err != nil {
|
||||
writeManagedServiceError(w, err)
|
||||
return
|
||||
}
|
||||
action := "managed_service.admin_token_set"
|
||||
if token == "" {
|
||||
action = "managed_service.admin_token_cleared"
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: action, TargetID: ms.ID, TargetType: "managed_service", TargetName: ms.Name,
|
||||
ActorType: "service", Metadata: map[string]interface{}{"kind": ms.Kind},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// ─── the daily count ──────────────────────────────────────────────────────
|
||||
|
||||
// ModuleUserReport summarises one count pass.
|
||||
type ModuleUserReport struct {
|
||||
Day string `json:"day"`
|
||||
Tenants int `json:"tenants"`
|
||||
// GitCounted: tenants whose Managed Git count for Day was written.
|
||||
GitCounted int `json:"git_counted"`
|
||||
// LicenceUsersAdded: (module, month, person) entries new in this pass.
|
||||
LicenceUsersAdded int `json:"licence_users_added"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
}
|
||||
|
||||
// CountModuleUsers runs one pass over every tenant. A failing tenant or
|
||||
// instance is reported and skipped, never written as 0; the others go on.
|
||||
// Re-runs are harmless: a day's count is overwritten, the month sets only
|
||||
// grow.
|
||||
func (s *Server) CountModuleUsers(ctx context.Context) ModuleUserReport {
|
||||
now := s.now()
|
||||
rep := ModuleUserReport{Day: berlinDate(now).Format(dayLayout)}
|
||||
cursor := ""
|
||||
for {
|
||||
page, next, err := s.Store.ListTenants(ctx, store.TenantFilter{Limit: 200, Cursor: cursor})
|
||||
if err != nil {
|
||||
rep.Errors = append(rep.Errors, "list tenants: "+err.Error())
|
||||
return rep
|
||||
}
|
||||
for i := range page {
|
||||
t := &page[i]
|
||||
rep.Tenants++
|
||||
written, errs := s.countManagedGit(ctx, t, rep.Day)
|
||||
if written {
|
||||
rep.GitCounted++
|
||||
}
|
||||
rep.Errors = append(rep.Errors, errs...)
|
||||
added, err := s.recordLicenceUsers(ctx, t, now)
|
||||
rep.LicenceUsersAdded += added
|
||||
if err != nil {
|
||||
rep.Errors = append(rep.Errors, t.ID+": licences: "+err.Error())
|
||||
}
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
return rep
|
||||
}
|
||||
|
||||
// countManagedGit writes the tenant's Managed Git count for day: the members
|
||||
// signed in to any of its active Git instances (one person counts once).
|
||||
// Nothing is written unless every instance was read.
|
||||
func (s *Server) countManagedGit(ctx context.Context, t *store.Tenant, day string) (bool, []string) {
|
||||
services, err := s.Store.ListManagedServices(ctx, t.ID)
|
||||
if err != nil {
|
||||
return false, []string{t.ID + ": managed services: " + err.Error()}
|
||||
}
|
||||
var gits []store.ManagedService
|
||||
for _, ms := range services {
|
||||
if ms.Kind == store.ManagedServiceKindGit && ms.Status == store.ManagedServiceActive {
|
||||
gits = append(gits, ms)
|
||||
}
|
||||
}
|
||||
if len(gits) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug)
|
||||
if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) { // no organization: nobody to count
|
||||
return false, []string{t.ID + ": members: " + err.Error()}
|
||||
}
|
||||
isMember := make(map[string]bool, len(members))
|
||||
for _, m := range members {
|
||||
if m.UserID != "" {
|
||||
isMember[m.UserID] = true
|
||||
}
|
||||
}
|
||||
var errs []string
|
||||
counted := map[string]bool{}
|
||||
for _, ms := range gits {
|
||||
users, err := s.giteaUsers(ctx, ms)
|
||||
if err != nil {
|
||||
errs = append(errs, t.ID+": git "+ms.ID+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
for _, u := range users {
|
||||
// Local accounts (the CI bot) have no login_name; staff sign in
|
||||
// from the company realm with ids that are no member's.
|
||||
if u.LoginName != "" && u.SignedIn() && isMember[u.LoginName] {
|
||||
counted[u.LoginName] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
return false, errs
|
||||
}
|
||||
if err := s.Store.PutModuleUserDay(ctx, store.ModuleUserDay{
|
||||
TenantID: t.ID, Module: store.ModuleManagedGit, Day: day, Count: len(counted),
|
||||
}); err != nil {
|
||||
return false, []string{t.ID + ": write git count: " + err.Error()}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// giteaUsers opens the service's token and lists the instance's users.
|
||||
func (s *Server) giteaUsers(ctx context.Context, ms store.ManagedService) ([]gitea.User, error) {
|
||||
if len(ms.AdminTokenSealed) == 0 {
|
||||
return nil, errors.New("no admin token set")
|
||||
}
|
||||
if !s.Secrets.Enabled() {
|
||||
return nil, errors.New("SECRETS_ENCRYPTION_KEY not set; the admin token cannot be opened")
|
||||
}
|
||||
token, err := s.Secrets.Open(ms.AdminTokenSealed, []byte(ms.ID))
|
||||
if err != nil {
|
||||
return nil, errors.New("the admin token cannot be opened")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, giteaTimeout)
|
||||
defer cancel()
|
||||
return s.gitea().ListUsers(ctx, ms.URL, string(token))
|
||||
}
|
||||
|
||||
// recordLicenceUsers adds the people whose Werkpilot / Firmwerk licence was
|
||||
// created or seen in the current or the previous Berlin month to that
|
||||
// month's set. Each time counts in its own month, so a run after midnight
|
||||
// still credits the evening before, and a day the job missed is caught up.
|
||||
func (s *Server) recordLicenceUsers(ctx context.Context, t *store.Tenant, now time.Time) (int, error) {
|
||||
rows, err := s.Store.ListLicences(ctx, t.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
cur := berlinDate(now)
|
||||
from := time.Date(cur.Year(), cur.Month()-1, 1, 0, 0, 0, 0, erpZone)
|
||||
sets := map[[2]string]map[string]bool{} // (module, month) → subjects
|
||||
for _, l := range rows {
|
||||
if !licenceModules[l.Product] || !humanLicence(l) {
|
||||
continue
|
||||
}
|
||||
times := []time.Time{l.CreatedAt}
|
||||
if l.LastSeenAt != nil {
|
||||
times = append(times, *l.LastSeenAt)
|
||||
}
|
||||
for _, at := range times {
|
||||
if at.Before(from) {
|
||||
continue
|
||||
}
|
||||
k := [2]string{l.Product, at.In(erpZone).Format(monthLayout)}
|
||||
if sets[k] == nil {
|
||||
sets[k] = map[string]bool{}
|
||||
}
|
||||
sets[k][l.Subject] = true
|
||||
}
|
||||
}
|
||||
keys := make([][2]string, 0, len(sets))
|
||||
for k := range sets {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool { return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1] })
|
||||
added := 0
|
||||
for _, k := range keys {
|
||||
subjects := make([]string, 0, len(sets[k]))
|
||||
for sub := range sets[k] {
|
||||
subjects = append(subjects, sub)
|
||||
}
|
||||
sort.Strings(subjects)
|
||||
n, err := s.Store.AddModuleUsersSeen(ctx, t.ID, k[0], k[1], subjects)
|
||||
added += n
|
||||
if err != nil {
|
||||
return added, err
|
||||
}
|
||||
}
|
||||
return added, nil
|
||||
}
|
||||
|
||||
// humanLicence: a person's own licence. CI licences (subject "apikey:<id>",
|
||||
// device "ci:…", licences_ci.go) and licences a service client issued
|
||||
// ("service:<tenant>") don't count.
|
||||
func humanLicence(l store.Licence) bool {
|
||||
switch {
|
||||
case l.Subject == "",
|
||||
strings.HasPrefix(l.Subject, "apikey:"),
|
||||
strings.HasPrefix(l.Subject, "service:"),
|
||||
strings.HasPrefix(l.Device, ciDevicePrefix):
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RunModuleUserCount runs CountModuleUsers once per Europe/Berlin day: it
|
||||
// looks every `check` and counts when the day has changed since the last
|
||||
// pass (and once after a start; a re-run is harmless).
|
||||
func (s *Server) RunModuleUserCount(ctx context.Context, check time.Duration) {
|
||||
if check <= 0 {
|
||||
check = 15 * time.Minute
|
||||
}
|
||||
t := time.NewTicker(check)
|
||||
defer t.Stop()
|
||||
last := ""
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
day := berlinDate(s.now()).Format(dayLayout)
|
||||
if day == last {
|
||||
continue
|
||||
}
|
||||
rep := s.CountModuleUsers(ctx)
|
||||
last = day
|
||||
s.Log.Info("module users counted", "day", rep.Day, "tenants", rep.Tenants, "git_counted", rep.GitCounted,
|
||||
"licence_users_added", rep.LicenceUsersAdded, "errors", rep.Errors)
|
||||
}
|
||||
}
|
||||
|
||||
// moduleUsersCountNow is POST /v1/internal/module-users/count (ops / tests).
|
||||
func (s *Server) moduleUsersCountNow(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer cancel()
|
||||
writeJSON(w, http.StatusOK, s.CountModuleUsers(ctx))
|
||||
}
|
||||
|
||||
// ─── reads ────────────────────────────────────────────────────────────────
|
||||
|
||||
type moduleUsersResp struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Month string `json:"month"`
|
||||
Items []store.ModuleUserCount `json:"items"`
|
||||
}
|
||||
|
||||
// adminModuleUsers is GET /v1/admin/tenants/{id}/module-users?month=YYYY-MM.
|
||||
func (s *Server) adminModuleUsers(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
t, ok := s.adminTenantOf(ctx, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.writeModuleUsers(ctx, w, r, t)
|
||||
}
|
||||
|
||||
// tenantModuleUsers is GET /v1/tenants/{id}/module-users?month= (a {sub} of
|
||||
// tenantSubresource). Users need portal:billing.view (IT_ADMIN, OWNER, CXO,
|
||||
// FINANCE, AUDITOR); service clients read with tenants.read.
|
||||
func (s *Server) tenantModuleUsers(w http.ResponseWriter, r *http.Request) {
|
||||
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !authz.AnyGrants(p.OrgRoles, capBillingView) {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "module users require the portal:billing.view right")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
t, ok := s.tenantInScope(ctx, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.writeModuleUsers(ctx, w, r, t)
|
||||
}
|
||||
|
||||
func (s *Server) writeModuleUsers(ctx context.Context, w http.ResponseWriter, r *http.Request, t *store.Tenant) {
|
||||
month := r.URL.Query().Get("month")
|
||||
if month == "" {
|
||||
month = berlinDate(s.now()).Format(monthLayout)
|
||||
}
|
||||
if !store.ValidMonth(month) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_month", "month must be YYYY-MM")
|
||||
return
|
||||
}
|
||||
items, err := s.Store.ModuleUserCounts(ctx, t.ID, month)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, moduleUsersResp{TenantID: t.ID, Month: month, Items: items})
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
)
|
||||
|
||||
func TestModuleUsers_tenantRoles(t *testing.T) {
|
||||
tenantID := "00000000-0000-0000-0000-000000000001"
|
||||
for _, c := range []struct {
|
||||
roles []string
|
||||
want int
|
||||
}{
|
||||
{[]string{"IT_ADMIN"}, http.StatusOK},
|
||||
{[]string{"OWNER"}, http.StatusOK},
|
||||
{[]string{"CXO"}, http.StatusOK},
|
||||
{[]string{"FINANCE"}, http.StatusOK},
|
||||
{[]string{"AUDITOR"}, http.StatusOK},
|
||||
{[]string{"USER"}, http.StatusForbidden},
|
||||
{[]string{"LEGAL"}, http.StatusForbidden},
|
||||
{[]string{"EXTERNAL"}, http.StatusForbidden},
|
||||
{nil, http.StatusForbidden},
|
||||
} {
|
||||
p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: tenantID, OrgRoles: c.roles}
|
||||
_, h, tenant := scopedServer(t, p)
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/module-users", nil))
|
||||
if rr.Code != c.want || (c.want == http.StatusForbidden && !strings.Contains(rr.Body.String(), "FORBIDDEN_ROLE")) {
|
||||
t.Fatalf("%v: %d %s", c.roles, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
// Another tenant's user: 404.
|
||||
other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}}
|
||||
_, h, tenant := scopedServer(t, other)
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/module-users", nil))
|
||||
if rr.Code != http.StatusNotFound {
|
||||
t.Fatalf("cross-tenant: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleUsers_clients(t *testing.T) {
|
||||
// Today's portal rule (orca-platform): reads need no change; the count
|
||||
// on demand needs the module-users group.
|
||||
const rules = "portal-svc:tenants,catalog,api-keys,audit,users,entitlements,usage.read,licences,admin,authz;ops-svc:module-users"
|
||||
portal := &authn.Principal{Subject: "svc", ClientID: "portal-svc"}
|
||||
_, h, tenant := scopedServer(t, portal, rules)
|
||||
for _, c := range []struct {
|
||||
method, path string
|
||||
want int
|
||||
}{
|
||||
{http.MethodGet, "/v1/tenants/" + tenant.ID + "/module-users", http.StatusOK},
|
||||
{http.MethodGet, "/v1/admin/tenants/" + tenant.ID + "/module-users?month=2026-11", http.StatusOK},
|
||||
{http.MethodPost, "/v1/internal/module-users/count", http.StatusForbidden},
|
||||
} {
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest(c.method, c.path, nil))
|
||||
if rr.Code != c.want {
|
||||
t.Fatalf("portal %s %s: %d %s", c.method, c.path, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
ops := &authn.Principal{Subject: "svc", ClientID: "ops-svc"}
|
||||
_, h, _ = scopedServer(t, ops, rules)
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/internal/module-users/count", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("ops count: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGroup_moduleUsers(t *testing.T) {
|
||||
for _, c := range []struct{ method, path, want string }{
|
||||
{http.MethodGet, "/v1/tenants/x/module-users", "tenants.read"},
|
||||
{http.MethodGet, "/v1/admin/tenants/x/module-users", "admin"},
|
||||
{http.MethodPut, "/v1/admin/tenants/x/managed-services/y/admin-token", "admin"},
|
||||
{http.MethodPost, "/v1/internal/module-users/count", "module-users"},
|
||||
} {
|
||||
if g := routeGroup(c.method, c.path); g != c.want {
|
||||
t.Errorf("%s %s: group %q, want %q", c.method, c.path, g, c.want)
|
||||
}
|
||||
}
|
||||
if got := subRoute("/v1/tenants/x/module-users"); got != "GET /v1/tenants/{id}/module-users" {
|
||||
t.Errorf("route name %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
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 = "gta_SENTINEL_0123456789abcdef"
|
||||
|
||||
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 /<instance>/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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -109,6 +109,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services"},
|
||||
{"PATCH", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002"},
|
||||
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002"},
|
||||
{"PUT", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002/admin-token"},
|
||||
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/module-users?month=2026-11"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/module-users?month=2026-11"},
|
||||
{"POST", "/v1/internal/module-users/count"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
req := newRequest(t, c.method, c.path)
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/buildinfo"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/gitea"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
||||
@@ -46,6 +47,7 @@ type Server struct {
|
||||
Secrets *secretbox.Box
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
||||
Gitea *gitea.Client // Managed Git user lists (t81); nil ⇒ http.DefaultClient
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
// Contracts are the released contract documents; nil ⇒ the committed
|
||||
// ones (contractdocs.Default). Tests pass their own.
|
||||
@@ -254,6 +256,12 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/managed-services", s.adminCreateManagedService)
|
||||
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/managed-services/{sid}", s.adminUpdateManagedService)
|
||||
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/managed-services/{sid}", s.adminDeleteManagedService)
|
||||
// Module users (0031, t81): the Git instance's read:admin token (sealed,
|
||||
// write-only), the month's counts, and the count pass on demand; the
|
||||
// tenant's counts are a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token", s.adminSetServiceToken)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}/module-users", s.adminModuleUsers)
|
||||
mux.HandleFunc("POST /v1/internal/module-users/count", s.moduleUsersCountNow)
|
||||
|
||||
// Notifications from products (F3; group "notify").
|
||||
mux.HandleFunc("POST /v1/notifications", s.postNotification)
|
||||
|
||||
+121
-1
@@ -847,6 +847,26 @@ paths:
|
||||
"403": { description: The user's org role may not see managed services (FORBIDDEN_ROLE). }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/module-users:
|
||||
get:
|
||||
summary: A tenant's module users for one month (t81).
|
||||
description: |
|
||||
Served by the `{id}/{sub}` route; user tokens reach their own tenant
|
||||
only and need a bundle granting portal:billing.view (IT_ADMIN, OWNER,
|
||||
CXO, FINANCE, AUDITOR; else 403 FORBIDDEN_ROLE). Service clients read
|
||||
with tenants.read. Same answer as the staff route.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- $ref: "#/components/parameters/ModuleUsersMonth"
|
||||
responses:
|
||||
"200":
|
||||
description: The month's counts per module.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ModuleUsers" } }
|
||||
"400": { description: "month is not YYYY-MM (invalid_month)." }
|
||||
"403": { description: The user's org role may not see module users (FORBIDDEN_ROLE). }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/members:
|
||||
get:
|
||||
summary: List the tenant's Keycloak organization members.
|
||||
@@ -1692,6 +1712,69 @@ paths:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/admin/tenants/{id}/managed-services/{sid}/admin-token:
|
||||
put:
|
||||
summary: Set or clear the Git instance's admin token (staff, t81).
|
||||
description: |
|
||||
A Gitea token with scope read:admin, used by the module-user count
|
||||
(GET /api/v1/admin/users). Stored AES-256-GCM sealed under
|
||||
SECRETS_ENCRYPTION_KEY and never returned: the answer only says
|
||||
admin_token_set. `""` clears it. Only for kind git. Audited as
|
||||
managed_service.admin_token_set / managed_service.admin_token_cleared
|
||||
(without the token).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: sid, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [token]
|
||||
properties:
|
||||
token: { type: string, maxLength: 512, writeOnly: true, description: "the token; \"\" clears it" }
|
||||
responses:
|
||||
"200":
|
||||
description: The service (admin_token_set shows the result).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ManagedServiceAdmin" } }
|
||||
"400": { description: "invalid_body, invalid_token (missing, spaces, longer than 512), invalid_kind (not a git service)." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"503": { description: SECRETS_ENCRYPTION_KEY is not set (secrets_disabled). }
|
||||
|
||||
/v1/admin/tenants/{id}/module-users:
|
||||
get:
|
||||
summary: A tenant's module users for one month (staff, t81).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- $ref: "#/components/parameters/ModuleUsersMonth"
|
||||
responses:
|
||||
"200":
|
||||
description: The month's counts per module.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ModuleUsers" } }
|
||||
"400": { description: "month is not YYYY-MM (invalid_month)." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/internal/module-users/count:
|
||||
post:
|
||||
summary: Run the module-user count now (ops / tests, t81).
|
||||
description: |
|
||||
Runs once per Europe/Berlin day in the background as well. Managed
|
||||
Git: per tenant, the workspace members signed in to its active Git
|
||||
instances, written as the day's count (a re-run overwrites it); a
|
||||
tenant with a failing instance, a missing token or a Keycloak error
|
||||
is reported in `errors` and not written. Werkpilot / Firmwerk: the
|
||||
people whose licence was created or seen in the current or previous
|
||||
Berlin month are added to that month's set. Route group
|
||||
module-users.
|
||||
responses:
|
||||
"200":
|
||||
description: Report.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/ModuleUserReport" } }
|
||||
|
||||
/v1/tenants/{id}/documents/{doc}/download:
|
||||
get:
|
||||
summary: A five-minute download link for a published document.
|
||||
@@ -2355,6 +2438,14 @@ components:
|
||||
Keycloak-issued token (client_credentials for services). Enforced
|
||||
on all non-health routes when AUTH_ENABLED=true.
|
||||
|
||||
parameters:
|
||||
ModuleUsersMonth:
|
||||
in: query
|
||||
name: month
|
||||
required: false
|
||||
description: The Europe/Berlin calendar month; default the current one.
|
||||
schema: { type: string, pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$", example: "2026-11" }
|
||||
|
||||
responses:
|
||||
BadRequest:
|
||||
description: Input failed validation.
|
||||
@@ -2853,13 +2944,42 @@ components:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ManagedService"
|
||||
- type: object
|
||||
required: [instance_id, notes]
|
||||
required: [instance_id, notes, admin_token_set]
|
||||
properties:
|
||||
instance_id: { type: string }
|
||||
notes: { type: string }
|
||||
admin_token_set: { type: boolean, description: "a Gitea admin token is stored (git only; the token is never returned)" }
|
||||
ManagedServiceStatus:
|
||||
type: string
|
||||
enum: [provisioning, active, restricted, halted]
|
||||
ModuleUsers:
|
||||
type: object
|
||||
required: [tenant_id, month, items]
|
||||
properties:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
month: { type: string, example: "2026-11" }
|
||||
items:
|
||||
type: array
|
||||
description: One entry per module with a count in the month, by module.
|
||||
items:
|
||||
type: object
|
||||
required: [module, count]
|
||||
properties:
|
||||
module: { type: string, enum: [firmwerk, managed-git, werkpilot] }
|
||||
count:
|
||||
type: integer
|
||||
description: |
|
||||
managed-git: the peak of the daily counts; werkpilot /
|
||||
firmwerk: the distinct people active in the month.
|
||||
peak_day: { type: string, format: date, description: "managed-git only: the peak day (the earliest on a tie)" }
|
||||
ModuleUserReport:
|
||||
type: object
|
||||
properties:
|
||||
day: { type: string, format: date, description: "the Europe/Berlin day counted" }
|
||||
tenants: { type: integer }
|
||||
git_counted: { type: integer, description: "tenants whose Managed Git count was written" }
|
||||
licence_users_added: { type: integer }
|
||||
errors: { type: array, items: { type: string } }
|
||||
ManagedServiceCreate:
|
||||
type: object
|
||||
required: [kind, name, url, sku]
|
||||
|
||||
Reference in new issue
Block a user