Files
Sharang ParnerkarandClaude Opus 5.5 692a9dd378
ci / shared (pull_request) Failing after 3s
ci / test (pull_request) Failing after 26s
ci / image (pull_request) Skipped
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>
2026-11-17 09:28:20 +01:00

391 lines
13 KiB
Go

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})
}