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
Owner

Part 1 of t81: count module users per tenant and month. This covers counting, storage and the read endpoints only. Invoicing, usage events to the ERP, included amounts and prices come later with t72.

What it does

Migration 0031_module_users (the down migration is included):

  • managed_services.admin_token_enc BYTEA: the Gitea read:admin token, sealed with secretbox under SECRETS_ENCRYPTION_KEY and bound to the service id;
  • module_user_days (tenant_id, module, day, count) for Managed Git. The month value is the max, and peak_day is the earliest day with that max;
  • module_users_seen (tenant_id, module, month 'YYYY-MM', subject) for Werkpilot and Firmwerk. The month value is the row count.
  • Both tables use ON DELETE CASCADE on tenants. The Memory store mirrors this on purge.

Managed Git count (managed-git): for each tenant's active git services, the job calls GET {url}/api/v1/admin/users (paged, token in the Authorization header). It counts users whose login_name is the Keycloak id of a current workspace member and who have signed in (last_login is neither zero nor epoch).

  • Staff accounts (company realm, other subs), the local CI bot (empty login_name) and removed members drop out.
  • If a tenant has several instances, one person counts once.
  • A failing instance, a missing token or a Keycloak error goes into the report and nothing is written for that tenant. It is never written as 0. A tenant without a Keycloak organization gets a real 0.

Werkpilot / Firmwerk count: taken from licences. CI licences (apikey: subject, ci: device) and licences issued by service clients (service:) don't count.

  • Deliberate deviation from the brief. The brief says to use timestamps inside the current Berlin day. A once-a-day run after midnight would then see almost nothing. Instead, each run sweeps created_at and last_seen_at in the current and previous Berlin month and puts each time into its own month. This is a superset of the brief's rule, it is idempotent, and it catches the evening before midnight as well as a missed day.
  • Side effect: in the first month after deploy, the previous month gets a partial set (people last seen there).

Job: RunModuleUserCount checks every 15 minutes and counts once per Europe/Berlin day. It also counts once after a start, which is harmless because a re-run overwrites the day and only grows the sets.

  • It reuses berlinDate / erpZone. erp.go and config.go are unchanged.
  • The report is ModuleUserReport (day, tenants, git_counted, licence_users_added, errors). Gitea errors name the tenant and service id and the status only, never the instance URL, the response body or the token. Keycloak and store errors pass their message through.

Endpoints

  • PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token: {"token":"…"} sets the token and "" clears it.
    • git only. Without SECRETS_ENCRYPTION_KEY it answers 503.
    • Audited without the value.
    • The answer and the admin list show only admin_token_set. The tenant view shows nothing about the token.
  • GET /v1/admin/tenants/{id}/module-users?month=YYYY-MM (staff, group admin).
  • GET /v1/tenants/{id}/module-users?month= (a {sub} of the tenant route, group tenants.read).
    • User tokens need portal:billing.view (IT_ADMIN, OWNER, CXO, FINANCE, AUDITOR), because the portal billing page will show it. This avoids a new registry:* right.
  • POST /v1/internal/module-users/count: runs the count now. New route group module-users.

Both reads return {tenant_id, month, items:[{module, count, peak_day?}]}. month defaults to the current Berlin month.

Operator steps

  1. Migration 0031: applied by MIGRATE_ON_START or make migrate-up. It only adds things (one nullable column and two tables).
  2. SECRETS_ENCRYPTION_KEY must be set on the registry, as it already is for CI licences. Without it, Managed Git is not counted and the token PUT answers 503.
  3. Token per Managed Git instance (Sharang, once per instance; later the provision.sh step in orca-platform from the design):
    • On the instance, as the Gitea site admin, create a token with scope read:admin only. For example: gitea admin user generate-access-token --username <admin> --token-name breakpilot-registry-metering --scopes read:admin --raw inside the Gitea container, or UI → Settings → Applications.
    • Hand it to the registry through the staff route, for example from the portal admin client: PUT /v1/admin/tenants/<tenant-id>/managed-services/<service-id>/admin-token with {"token":"<token>"}. Keep it out of shell history and logs.
    • Make sure the git service record has status active. Only active instances are counted.
  4. AUTHZ_RULES: no change is needed for the reads (portal-svc-* already holds admin and tenants) or for the token PUT (admin). The daily job runs in-process. Only if someone should trigger POST /v1/internal/module-users/count on demand, add the group module-users to that client in services/platform-{stage,prod}/service.toml (orca-platform; not edited here).

Tests

  • Gitea client: paging with a server-capped page size (stops on an empty page), token only in the header, errors without body, URL or token, epoch and zero last_login.
  • Count: two instances (union), halted instance skipped, failing instance (500 with the token in its body) reported and not written, missing token, no organization = 0, Keycloak down, re-run overwrites; the token sentinel never appears in the report.
  • Licences: CI, service: and pruefwerk excluded, previous-month bucket, older months outside the sweep, idempotent re-run.
  • Reads: peak-day tie (earliest), month bounds, default month, invalid month, unknown tenant; role matrix and cross-tenant 404 for the tenant route; route groups; AUTHZ_RULES client matrix.
  • Token endpoint: 503 without key, validation, non-git 400, sealed at rest, PATCH keeps it, clear, audit without value, token absent from every response.
  • All eachStore tests run against Memory and Postgres (testcontainers). The migration round-trip test lists the new tables and column.
  • go vet ./... is clean and golangci-lint run ./... reports 0 issues. A trial merge with feat/mahnung-ladder (#134) is clean, and #134 adds no migration.
  • Pre-existing and not from this PR: migrations/TestSeed_canInsertAndQuery fails on main (8a72469) as well. Deleting a tenant hits intake_reports_tenant_id_fkey (ON DELETE RESTRICT since 0030).

🤖 Generated with Claude Code

Part 1 of t81: count module users per tenant and month. This covers counting, storage and the read endpoints only. Invoicing, usage events to the ERP, included amounts and prices come later with t72. ## What it does **Migration `0031_module_users`** (the down migration is included): - `managed_services.admin_token_enc BYTEA`: the Gitea `read:admin` token, sealed with secretbox under `SECRETS_ENCRYPTION_KEY` and bound to the service id; - `module_user_days (tenant_id, module, day, count)` for Managed Git. The month value is the max, and `peak_day` is the earliest day with that max; - `module_users_seen (tenant_id, module, month 'YYYY-MM', subject)` for Werkpilot and Firmwerk. The month value is the row count. - Both tables use `ON DELETE CASCADE` on tenants. The Memory store mirrors this on purge. **Managed Git count** (`managed-git`): for each tenant's **active** git services, the job calls `GET {url}/api/v1/admin/users` (paged, token in the `Authorization` header). It counts users whose `login_name` is the Keycloak id of a current workspace member and who have signed in (`last_login` is neither zero nor epoch). - Staff accounts (company realm, other subs), the local CI bot (empty `login_name`) and removed members drop out. - If a tenant has several instances, one person counts once. - A failing instance, a missing token or a Keycloak error goes into the report and nothing is written for that tenant. It is never written as 0. A tenant without a Keycloak organization gets a real 0. **Werkpilot / Firmwerk count**: taken from `licences`. CI licences (`apikey:` subject, `ci:` device) and licences issued by service clients (`service:`) don't count. - **Deliberate deviation from the brief.** The brief says to use timestamps inside the current Berlin day. A once-a-day run after midnight would then see almost nothing. Instead, each run sweeps `created_at` and `last_seen_at` in the **current and previous Berlin month** and puts each time into its own month. This is a superset of the brief's rule, it is idempotent, and it catches the evening before midnight as well as a missed day. - Side effect: in the first month after deploy, the previous month gets a partial set (people last seen there). **Job**: `RunModuleUserCount` checks every 15 minutes and counts once per Europe/Berlin day. It also counts once after a start, which is harmless because a re-run overwrites the day and only grows the sets. - It reuses `berlinDate` / `erpZone`. `erp.go` and `config.go` are unchanged. - The report is `ModuleUserReport` (day, tenants, git_counted, licence_users_added, errors). Gitea errors name the tenant and service id and the status only, never the instance URL, the response body or the token. Keycloak and store errors pass their message through. **Endpoints** - `PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token`: `{"token":"…"}` sets the token and `""` clears it. - git only. Without `SECRETS_ENCRYPTION_KEY` it answers 503. - Audited without the value. - The answer and the admin list show only `admin_token_set`. The tenant view shows nothing about the token. - `GET /v1/admin/tenants/{id}/module-users?month=YYYY-MM` (staff, group `admin`). - `GET /v1/tenants/{id}/module-users?month=` (a `{sub}` of the tenant route, group `tenants.read`). - User tokens need `portal:billing.view` (IT_ADMIN, OWNER, CXO, FINANCE, AUDITOR), because the portal billing page will show it. This avoids a new `registry:*` right. - `POST /v1/internal/module-users/count`: runs the count now. New route group `module-users`. Both reads return `{tenant_id, month, items:[{module, count, peak_day?}]}`. `month` defaults to the current Berlin month. ## Operator steps 1. **Migration 0031**: applied by `MIGRATE_ON_START` or `make migrate-up`. It only adds things (one nullable column and two tables). 2. **`SECRETS_ENCRYPTION_KEY`** must be set on the registry, as it already is for CI licences. Without it, Managed Git is not counted and the token PUT answers 503. 3. **Token per Managed Git instance** (Sharang, once per instance; later the `provision.sh` step in orca-platform from the design): - On the instance, as the Gitea site admin, create a token with scope **`read:admin`** only. For example: `gitea admin user generate-access-token --username <admin> --token-name breakpilot-registry-metering --scopes read:admin --raw` inside the Gitea container, or UI → Settings → Applications. - Hand it to the registry through the staff route, for example from the portal admin client: `PUT /v1/admin/tenants/<tenant-id>/managed-services/<service-id>/admin-token` with `{"token":"<token>"}`. Keep it out of shell history and logs. - Make sure the git service record has status `active`. Only active instances are counted. 4. **AUTHZ_RULES**: no change is needed for the reads (`portal-svc-*` already holds `admin` and `tenants`) or for the token PUT (`admin`). The daily job runs in-process. Only if someone should trigger `POST /v1/internal/module-users/count` on demand, add the group `module-users` to that client in `services/platform-{stage,prod}/service.toml` (orca-platform; not edited here). ## Tests - Gitea client: paging with a server-capped page size (stops on an empty page), token only in the header, errors without body, URL or token, epoch and zero `last_login`. - Count: two instances (union), halted instance skipped, failing instance (500 with the token in its body) reported and not written, missing token, no organization = 0, Keycloak down, re-run overwrites; the token sentinel never appears in the report. - Licences: CI, `service:` and pruefwerk excluded, previous-month bucket, older months outside the sweep, idempotent re-run. - Reads: peak-day tie (earliest), month bounds, default month, invalid month, unknown tenant; role matrix and cross-tenant 404 for the tenant route; route groups; AUTHZ_RULES client matrix. - Token endpoint: 503 without key, validation, non-git 400, sealed at rest, PATCH keeps it, clear, audit without value, token absent from every response. - All `eachStore` tests run against Memory **and** Postgres (testcontainers). The migration round-trip test lists the new tables and column. - `go vet ./...` is clean and `golangci-lint run ./...` reports 0 issues. A trial merge with `feat/mahnung-ladder` (#134) is clean, and #134 adds no migration. - Pre-existing and not from this PR: `migrations/TestSeed_canInsertAndQuery` fails on `main` (8a72469) as well. Deleting a tenant hits `intake_reports_tenant_id_fkey` (ON DELETE RESTRICT since 0030). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sharang added 3 commits 2026-11-17 08:31:14 +00:00
Migration 0031 adds managed_services.admin_token_enc (sealed, write-only),
module_user_days (Managed Git daily counts, month = peak day) and
module_users_seen (Werkpilot/Firmwerk people per month). Postgres and
Memory stores implement both.

Refs: t81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GET /api/v1/admin/users with a read:admin token in the Authorization
header, paged until an empty page. Errors carry no body, URL or token.

Refs: t81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat(metering): count module users per tenant and month
ci / shared (pull_request) Failing after 3s
ci / test (pull_request) Failing after 26s
ci / image (pull_request) Skipped
692a9dd378
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>
CODEOWNERS rules requested review from Benjamin_Boenisch 2026-11-17 08:31:14 +00:00
sharang added 1 commit 2026-11-17 08:33:00 +00:00
test(metering): low-entropy token sentinel for gitleaks
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 7m23s
ci / image (pull_request) Skipped
9af0d9f8e1
The first sentinel looked like an API key to gitleaks' generic rule. It
is a test value; its fingerprint goes into .gitleaksignore since the
commit is already pushed.

Refs: t81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sharang merged commit f6bb84933c into main 2026-11-17 09:01:55 +00:00
Sign in to join this conversation.