feat(metering): count module users per tenant and month (t81, part 1) #136

Merged
sharang merged 4 commits from feat/module-user-count into main 2026-11-17 09:01:55 +00:00
23 changed files with 1638 additions and 6 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# False positives: test-only sentinel values (no real secrets).
692a9dd378acb5f51e621ed1cd9d9ec8ba10c55b:internal/server/module_users_test.go:generic-api-key:23
+40
View File
@@ -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
View File
@@ -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))
+118
View File
@@ -0,0 +1,118 @@
// Package gitea reads the user list of a Managed Git instance (t81): one
// Gitea per customer, read with a token of scope read:admin.
package gitea
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// pageLimit is the page size asked for; Gitea may cap it lower
// (API.MAX_RESPONSE_ITEMS), so paging stops on an empty page, not a short one.
const (
pageLimit = 50
maxPages = 2000 // 100,000 users: a guard against a server that never ends
maxBody = 8 << 20
)
// User is the part of Gitea's admin user record the count uses.
type User struct {
Login string `json:"login"`
// LoginName is the user's name at its login source: for accounts that
// sign in through the tenant's Keycloak client, the Keycloak user id
// (sub). Local accounts (the CI bot) have none.
LoginName string `json:"login_name"`
LastLogin time.Time `json:"last_login"`
}
// SignedIn reports whether the user has signed in at least once. Gitea
// reports "never" as the Unix epoch (in the server's zone); the Go zero time
// covers a missing field.
func (u User) SignedIn() bool {
return !u.LastLogin.IsZero() && u.LastLogin.Unix() > 0
}
// Client calls Gitea instances. The zero value uses http.DefaultClient.
type Client struct {
HTTP *http.Client
}
func (c *Client) http() *http.Client {
if c != nil && c.HTTP != nil {
return c.HTTP
}
return http.DefaultClient
}
// ErrStatus is an unexpected HTTP status from Gitea. Its message carries the
// status only, never the response body.
type ErrStatus struct{ Code int }
func (e *ErrStatus) Error() string { return "gitea: status " + strconv.Itoa(e.Code) }
// ListUsers returns every user of the instance at baseURL
// (GET /api/v1/admin/users, paged). The token goes in the Authorization
// header only, so it never appears in a URL or an error.
func (c *Client) ListUsers(ctx context.Context, baseURL, token string) ([]User, error) {
if token == "" {
return nil, errors.New("gitea: no token")
}
base, err := url.Parse(strings.TrimRight(baseURL, "/") + "/api/v1/admin/users")
if err != nil || base.Host == "" {
return nil, errors.New("gitea: invalid instance url")
}
var out []User
for page := 1; page <= maxPages; page++ {
u := *base
u.RawQuery = url.Values{"page": {strconv.Itoa(page)}, "limit": {strconv.Itoa(pageLimit)}}.Encode()
users, err := c.page(ctx, u.String(), token)
if err != nil {
return nil, fmt.Errorf("page %d: %w", page, err)
}
if len(users) == 0 {
return out, nil
}
out = append(out, users...)
}
return nil, errors.New("gitea: too many pages")
}
func (c *Client) page(ctx context.Context, u, token string) ([]User, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, errors.New("gitea: build request")
}
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/json")
resp, err := c.http().Do(req)
if err != nil {
// Not the *url.Error itself: it names the instance's URL, and the
// report this ends up in should name the service id only.
var ue *url.Error
if errors.As(err, &ue) && ue.Timeout() {
return nil, errors.New("gitea: request timed out")
}
if ctx.Err() != nil {
return nil, fmt.Errorf("gitea: %w", ctx.Err())
}
return nil, errors.New("gitea: request failed")
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxBody))
return nil, &ErrStatus{Code: resp.StatusCode}
}
var users []User
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&users); err != nil {
return nil, errors.New("gitea: response is not a user list")
}
return users, nil
}
+102
View File
@@ -0,0 +1,102 @@
package gitea
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
const token = "sentinel-gitea-token-0123456789"
func TestListUsers_pagesUntilEmpty(t *testing.T) {
all := []map[string]any{}
for i := range 7 {
all = append(all, map[string]any{"login": "u" + strconv.Itoa(i), "login_name": "kc-" + strconv.Itoa(i), "last_login": "2026-11-16T10:00:00+01:00"})
}
var pages []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/sub/api/v1/admin/users" {
http.NotFound(w, r)
return
}
if r.Header.Get("Authorization") != "token "+token || strings.Contains(r.URL.RawQuery, token) {
w.WriteHeader(http.StatusUnauthorized)
return
}
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
pages = append(pages, r.URL.Query().Get("page")+"/"+r.URL.Query().Get("limit"))
// The server caps the page size at 3, below the limit asked for.
lo, hi := (page-1)*3, page*3
lo, hi = min(lo, len(all)), min(hi, len(all))
_ = json.NewEncoder(w).Encode(all[lo:hi])
}))
defer srv.Close()
users, err := (&Client{}).ListUsers(context.Background(), srv.URL+"/sub/", token)
if err != nil {
t.Fatal(err)
}
if len(users) != 7 || users[6].LoginName != "kc-6" || !users[0].SignedIn() {
t.Fatalf("users: %+v", users)
}
if strings.Join(pages, ",") != "1/50,2/50,3/50,4/50" {
t.Fatalf("pages asked: %v", pages)
}
}
func TestListUsers_errorsCarryNoBodyOrToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"token ` + token + ` lacks read:admin"}`))
}))
defer srv.Close()
_, err := (&Client{}).ListUsers(context.Background(), srv.URL, token)
if err == nil || err.Error() != "page 1: gitea: status 403" {
t.Fatalf("err: %v", err)
}
// Unreachable: no URL, no token in the message.
srv.Close()
_, err = (&Client{}).ListUsers(context.Background(), srv.URL, token)
if err == nil || strings.Contains(err.Error(), token) || strings.Contains(err.Error(), "127.0.0.1") {
t.Fatalf("unreachable err: %v", err)
}
if _, err := (&Client{}).ListUsers(context.Background(), "https://git.k-00001.example", ""); err == nil {
t.Fatal("no token: want an error")
}
}
func TestListUsers_notAList(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"message":"x"}`))
}))
defer srv.Close()
if _, err := (&Client{}).ListUsers(context.Background(), srv.URL, token); err == nil || !strings.Contains(err.Error(), "not a user list") {
t.Fatalf("err: %v", err)
}
}
func TestUser_signedIn(t *testing.T) {
var never []User
if err := json.Unmarshal([]byte(`[
{"login_name":"a","last_login":"1970-01-01T01:00:00+01:00"},
{"login_name":"b","last_login":"0001-01-01T00:00:00Z"},
{"login_name":"c"}
]`), &never); err != nil {
t.Fatal(err)
}
for _, u := range never {
if u.SignedIn() {
t.Errorf("%s: signed in", u.LoginName)
}
}
if !(User{LastLogin: time.Date(2026, 11, 1, 8, 0, 0, 0, time.UTC)}).SignedIn() {
t.Error("a real sign-in does not count")
}
}
+2
View File
@@ -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"):
+3
View File
@@ -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")
}
+390
View File
@@ -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)
}
}
+412
View File
@@ -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 = "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 /<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)
}
})
}
+4
View File
@@ -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)
+8
View File
@@ -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)
+7
View File
@@ -58,6 +58,9 @@ type Memory struct {
contractDocID int64
capRequests []CapabilityRequest // pending four-eyes grants, oldest first (0029)
moduleDays map[moduleDayKey]int // Managed Git daily counts (0031)
moduleSeen map[moduleSeenKey]time.Time // licence users per month (0031) → first seen
}
type apiKeyWithHash struct {
@@ -90,6 +93,9 @@ func NewMemory() *Memory {
documents: make(map[string]*Document),
prodSets: make(map[string]*TenantProductSettings),
moduleDays: make(map[moduleDayKey]int),
moduleSeen: make(map[moduleSeenKey]time.Time),
}
now := time.Now().UTC()
seed := &Tenant{
@@ -621,6 +627,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error {
m.contractDocs = kept
m.deleteIntake(id)
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id })
m.deleteModuleUsers(id)
for kid, k := range m.apiKeys {
if k.TenantID == id {
delete(m.apiKeys, kid)
+110
View File
@@ -0,0 +1,110 @@
package store
import (
"context"
"sort"
"strings"
"time"
)
type moduleDayKey struct{ tenant, module, day string }
type moduleSeenKey struct{ tenant, module, month, subject string }
func (m *Memory) PutModuleUserDay(_ context.Context, d ModuleUserDay) error {
if d.Module == "" || d.Count < 0 || !validDay(d.Day) {
return ErrInvalidInput
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[d.TenantID]; !ok {
return ErrNotFound
}
m.moduleDays[moduleDayKey{d.TenantID, d.Module, d.Day}] = d.Count
return nil
}
func (m *Memory) AddModuleUsersSeen(_ context.Context, tenantID, module, month string, subjects []string) (int, error) {
if module == "" || !ValidMonth(month) {
return 0, ErrInvalidInput
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[tenantID]; !ok {
return 0, ErrNotFound
}
now, added := time.Now().UTC(), 0
for _, sub := range subjects {
if sub == "" {
continue
}
k := moduleSeenKey{tenantID, module, month, sub}
if _, ok := m.moduleSeen[k]; !ok {
m.moduleSeen[k] = now
added++
}
}
return added, nil
}
func (m *Memory) ModuleUserCounts(_ context.Context, tenantID, month string) ([]ModuleUserCount, error) {
if !ValidMonth(month) {
return nil, ErrInvalidInput
}
m.mu.RLock()
defer m.mu.RUnlock()
byModule := map[string]*ModuleUserCount{}
for k, n := range m.moduleDays {
if k.tenant != tenantID || !strings.HasPrefix(k.day, month+"-") {
continue
}
c, ok := byModule[k.module]
// The peak; on a tie the earliest day (as the Postgres query).
if !ok || n > c.Count || (n == c.Count && k.day < c.PeakDay) {
byModule[k.module] = &ModuleUserCount{Module: k.module, Count: n, PeakDay: k.day}
}
}
seen := map[string]int{}
for k := range m.moduleSeen {
if k.tenant == tenantID && k.month == month {
seen[k.module]++
}
}
for mod, n := range seen {
if _, ok := byModule[mod]; !ok { // a module is counted one way only
byModule[mod] = &ModuleUserCount{Module: mod, Count: n}
}
}
out := make([]ModuleUserCount, 0, len(byModule))
for _, c := range byModule {
out = append(out, *c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module })
return out, nil
}
// deleteModuleUsers drops a purged tenant's counts (ON DELETE CASCADE in
// Postgres). Caller holds the lock.
func (m *Memory) deleteModuleUsers(tenantID string) {
for k := range m.moduleDays {
if k.tenant == tenantID {
delete(m.moduleDays, k)
}
}
for k := range m.moduleSeen {
if k.tenant == tenantID {
delete(m.moduleSeen, k)
}
}
}
// ValidMonth reports whether s is a calendar month "YYYY-MM".
func ValidMonth(s string) bool {
_, err := time.Parse("2006-01", s)
return err == nil && len(s) == 7
}
func validDay(s string) bool {
_, err := time.Parse("2006-01-02", s)
return err == nil && len(s) == 10
}
+17
View File
@@ -65,6 +65,7 @@ func (m *Memory) CreateManagedService(_ context.Context, ms ManagedService) (*Ma
return nil, ErrInvalidInput
}
ms.ID = uuid.NewString()
ms.AdminTokenSealed, ms.AdminTokenSet = nil, false
if m.serviceTaken(ms) {
return nil, ErrConflict
}
@@ -105,3 +106,19 @@ func (m *Memory) DeleteManagedService(_ context.Context, id string) error {
delete(m.services, id)
return nil
}
func (m *Memory) SetManagedServiceAdminToken(_ context.Context, id string, sealed []byte) error {
m.mu.Lock()
defer m.mu.Unlock()
ms, ok := m.services[id]
if !ok {
return ErrNotFound
}
ms.AdminTokenSealed = nil
if len(sealed) > 0 {
ms.AdminTokenSealed = append([]byte(nil), sealed...)
}
ms.AdminTokenSet = len(ms.AdminTokenSealed) > 0
ms.UpdatedAt = time.Now().UTC()
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package store
import (
"context"
"sort"
)
func (p *Postgres) PutModuleUserDay(ctx context.Context, d ModuleUserDay) error {
if d.Module == "" || d.Count < 0 || !validDay(d.Day) {
return ErrInvalidInput
}
_, err := p.pool.Exec(ctx, `
INSERT INTO module_user_days (tenant_id, module, day, count)
VALUES ($1::uuid, $2, $3::date, $4)
ON CONFLICT (tenant_id, module, day) DO UPDATE SET count = EXCLUDED.count, counted_at = now()`,
d.TenantID, d.Module, d.Day, d.Count)
switch {
case isFKViolation(err), isInvalidUUID(err):
return ErrNotFound
case isCheckViolation(err):
return ErrInvalidInput
}
return err
}
func (p *Postgres) AddModuleUsersSeen(ctx context.Context, tenantID, module, month string, subjects []string) (int, error) {
if module == "" || !ValidMonth(month) {
return 0, ErrInvalidInput
}
subs := make([]string, 0, len(subjects))
for _, s := range subjects {
if s != "" {
subs = append(subs, s)
}
}
if len(subs) == 0 {
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return 0, err
}
return 0, nil
}
tag, err := p.pool.Exec(ctx, `
INSERT INTO module_users_seen (tenant_id, module, month, subject)
SELECT $1::uuid, $2, $3, s FROM unnest($4::text[]) AS s
ON CONFLICT DO NOTHING`, tenantID, module, month, subs)
switch {
case isFKViolation(err), isInvalidUUID(err):
return 0, ErrNotFound
case isCheckViolation(err):
return 0, ErrInvalidInput
case err != nil:
return 0, err
}
return int(tag.RowsAffected()), nil
}
func (p *Postgres) ModuleUserCounts(ctx context.Context, tenantID, month string) ([]ModuleUserCount, error) {
if !ValidMonth(month) {
return nil, ErrInvalidInput
}
byModule := map[string]ModuleUserCount{}
// The peak day per module; on a tie the earliest day.
rows, err := p.pool.Query(ctx, `
SELECT DISTINCT ON (module) module, count, to_char(day, 'YYYY-MM-DD')
FROM module_user_days
WHERE tenant_id = $1::uuid AND day >= $2::date AND day < ($2::date + interval '1 month')
ORDER BY module, count DESC, day`, tenantID, month+"-01")
if isInvalidUUID(err) {
return []ModuleUserCount{}, nil
}
if err != nil {
return nil, err
}
for rows.Next() {
var c ModuleUserCount
if err := rows.Scan(&c.Module, &c.Count, &c.PeakDay); err != nil {
rows.Close()
return nil, err
}
byModule[c.Module] = c
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
rows, err = p.pool.Query(ctx, `
SELECT module, count(*) FROM module_users_seen
WHERE tenant_id = $1::uuid AND month = $2 GROUP BY module`, tenantID, month)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var c ModuleUserCount
if err := rows.Scan(&c.Module, &c.Count); err != nil {
return nil, err
}
if _, ok := byModule[c.Module]; !ok { // a module is counted one way only
byModule[c.Module] = c
}
}
if err := rows.Err(); err != nil {
return nil, err
}
out := make([]ModuleUserCount, 0, len(byModule))
for _, c := range byModule {
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module })
return out, nil
}
+20 -2
View File
@@ -8,18 +8,19 @@ import (
)
const serviceSelect = `
SELECT id::text, tenant_id::text, kind, name, url, sku, status, instance_id, notes, created_at, updated_at
SELECT id::text, tenant_id::text, kind, name, url, sku, status, instance_id, notes, created_at, updated_at, admin_token_enc
FROM managed_services `
func scanManagedService(row pgx.Row) (*ManagedService, error) {
var ms ManagedService
if err := row.Scan(&ms.ID, &ms.TenantID, &ms.Kind, &ms.Name, &ms.URL, &ms.SKU, &ms.Status,
&ms.InstanceID, &ms.Notes, &ms.CreatedAt, &ms.UpdatedAt); err != nil {
&ms.InstanceID, &ms.Notes, &ms.CreatedAt, &ms.UpdatedAt, &ms.AdminTokenSealed); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
ms.AdminTokenSet = len(ms.AdminTokenSealed) > 0
return &ms, nil
}
@@ -107,3 +108,20 @@ func (p *Postgres) DeleteManagedService(ctx context.Context, id string) error {
}
return nil
}
func (p *Postgres) SetManagedServiceAdminToken(ctx context.Context, id string, sealed []byte) error {
if len(sealed) == 0 {
sealed = nil
}
tag, err := p.pool.Exec(ctx, `UPDATE managed_services SET admin_token_enc = $2, updated_at = now() WHERE id = $1::uuid`, id, sealed)
if isInvalidUUID(err) {
return ErrNotFound
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
+12
View File
@@ -312,6 +312,18 @@ type Store interface {
// UpdateManagedService writes name, url, sku, status, instance_id, notes.
UpdateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
DeleteManagedService(ctx context.Context, id string) error
// SetManagedServiceAdminToken stores the sealed Gitea admin token of a
// service (0031, t81); nil or empty clears it. ErrNotFound for no row.
SetManagedServiceAdminToken(ctx context.Context, id string, sealed []byte) error
// Module users (0031, t81). PutModuleUserDay writes (overwrites) one
// day's count; AddModuleUsersSeen adds subjects to a month's set and
// returns how many were new; ModuleUserCounts returns the month's value
// per module (peak day or set size), sorted by module. ErrNotFound for
// an unknown tenant on the writes.
PutModuleUserDay(ctx context.Context, d ModuleUserDay) error
AddModuleUsersSeen(ctx context.Context, tenantID, module, month string, subjects []string) (int, error)
ModuleUserCounts(ctx context.Context, tenantID, month string) ([]ModuleUserCount, error)
// Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey
// (false when the key existed). ClaimMail leases due unsent rows.
+29
View File
@@ -352,6 +352,10 @@ type ManagedService struct {
Notes string `json:"notes"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// AdminTokenSet: a sealed Gitea admin token is stored (0031, t81). The
// token itself (AdminTokenSealed) is never serialised.
AdminTokenSet bool `json:"admin_token_set"`
AdminTokenSealed []byte `json:"-"`
}
const (
@@ -364,6 +368,31 @@ const (
ManagedServiceHalted = "halted"
)
// Module users (0031, t81): the modules counted.
const (
ModuleManagedGit = "managed-git" // peak of the daily counts
ModuleWerkpilot = "werkpilot" // distinct users active in the month
ModuleFirmwerk = "firmwerk" // distinct users active in the month
)
// ModuleUserDay is one day's Managed Git count of a tenant. Day is
// "YYYY-MM-DD" (Europe/Berlin).
type ModuleUserDay struct {
TenantID string
Module string
Day string
Count int
}
// ModuleUserCount is a module's value for one month: the peak day's count
// (PeakDay set, the earliest day on a tie) or the number of distinct users
// seen in the month (PeakDay empty).
type ModuleUserCount struct {
Module string `json:"module"`
Count int `json:"count"`
PeakDay string `json:"peak_day,omitempty"`
}
// ValidManagedServiceKind and ValidManagedServiceStatus mirror the CHECK
// constraints of 0012 and 0013.
func ValidManagedServiceKind(k string) bool {
+3
View File
@@ -0,0 +1,3 @@
DROP TABLE module_users_seen;
DROP TABLE module_user_days;
ALTER TABLE managed_services DROP COLUMN admin_token_enc;
+31
View File
@@ -0,0 +1,31 @@
-- Module users per tenant and month (t81). Counting only; invoicing comes
-- later with t72.
--
-- managed_services.admin_token_enc: a Gitea token with read:admin scope per
-- Managed Git instance, AES-256-GCM sealed under SECRETS_ENCRYPTION_KEY and
-- bound to the service id (like licences.llm_key_secret_enc, 0017). Write
-- only: the API never returns it.
ALTER TABLE managed_services ADD COLUMN admin_token_enc BYTEA;
-- Managed Git: one count per Berlin day (workspace members who have signed
-- in to the tenant's instance). The month's value is the peak day.
CREATE TABLE module_user_days (
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
module TEXT NOT NULL,
day DATE NOT NULL,
count INTEGER NOT NULL CHECK (count >= 0),
counted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, module, day)
);
-- Werkpilot / Firmwerk: the people (Keycloak subjects) active in a Berlin
-- month. licences.last_seen_at keeps only the latest time, so the daily job
-- records them while the month runs. The month's value is the row count.
CREATE TABLE module_users_seen (
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
module TEXT NOT NULL,
month TEXT NOT NULL CHECK (month ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'),
subject TEXT NOT NULL,
first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, module, month, subject)
);
+4 -2
View File
@@ -109,6 +109,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
"role_dataset_revisions",
"tenant_product_settings",
"tenant_contract_documents",
"module_user_days",
"module_users_seen",
}
for _, table := range wantTables {
var exists bool
@@ -124,8 +126,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
}
}
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents; 0028: intake).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}, {"intake_reports", "danger"}, {"intake_entries", "content"}, {"intake_receipts", "handoff_id"}, {"intake_counters", "last"}} {
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents; 0028: intake; 0031: module users).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}, {"intake_reports", "danger"}, {"intake_entries", "content"}, {"intake_receipts", "handoff_id"}, {"intake_counters", "last"}, {"managed_services", "admin_token_enc"}, {"module_user_days", "count"}, {"module_users_seen", "subject"}} {
var exists bool
err := db.QueryRow(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
+121 -1
View File
@@ -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]