Registry side of Prüfwerk metering (backlog t72). Stage first; nothing deployed.
## What changes
- **Entitlement check**: for `pruefwerk` the limits now always carry `included_targets`, `monthly_pruefungen` and `prueftag_cap`, with `null` meaning unlimited or no cap. The values come from one plan table in `internal/server/pruefwerk.go`:
| Plan | SKU | included_targets | monthly_pruefungen | prueftag_cap |
|---|---|---|---|---|
| Standard | CRA-CSA-CLD-STD | 5 | 100 | the workspace's cap or null |
| Business | CRA-CSA-CLD-BUS | 25 | 500 | the workspace's cap or null |
| Enterprise | CRA-CSA-CLD-ENT | null | null | always null |
The highest plan SKU in `config.skus` wins. A tenant with no plan SKU (trial, preview grant, SCAN-only order) gets Standard. The limits are built on a copy of `tenant_products.config`, so the existing keys stay and the stored config is not changed. Other products are unchanged.
- **Migration 0025** adds `tenant_product_settings(tenant_id, product, settings jsonb, updated_by, updated_at)`, PK `(tenant_id, product)`, with ON DELETE CASCADE. Both stores implement it (Postgres and Memory). `recomputeEntitlements` never touches this table, so the cap survives ERP recomputes.
- **`GET`/`PUT /v1/tenants/{id}/products/pruefwerk/settings`**: the body is `{"prueftag_cap": 0..10000 | null}`. Unknown keys, a missing key, non-integers and out-of-range values all return 400.
- **User tokens** must be in their own tenant (404 otherwise) and have the IT_ADMIN, OWNER or FINANCE org role (403 `FORBIDDEN_ROLE` otherwise).
- **Service clients** are gated by their route group, as for the company profile: GET needs `tenants.read`, PUT needs `tenants.write`. Staff come through the admin client with `X-Staff-*`.
- **Audit**: a change is logged as `product_settings.changed` with `old`, `new`, `plan` and `applies`. A PUT that changes nothing writes nothing and logs nothing.
- **Enterprise**: PUT still stores the cap and GET shows it with `cap_applies: false`, but the check sends `null`.
- **Usage metrics**: `prueftag.booked` and `target.extra` go through the existing `POST /v1/usage/events`. A test checks that both are stored once per idempotency key and that a repeat, even with a different quantity, counts as a duplicate. No update-in-place path, no invoicing, no ERP item or price changes.
- OpenAPI: the new path, a `PruefwerkSettings` schema, and the three keys described on `EntitlementCheck.limits`.
## Deploy note
Run **`migrate-up` (0025) before the new build takes traffic.** If reading the settings table fails, the Prüfwerk check returns 500 rather than silently sending `prueftag_cap: null`.
## Decisions not in the brief
1. OWNER is allowed alongside IT_ADMIN and FINANCE, because every other admin check in the registry treats OWNER like IT_ADMIN. Dropping it is a one-line change.
2. The registry enforces the org role only on user tokens. Service clients are trusted by route group (the portal checks roles for its users), which matches the company-profile route.
3. The plan table wins over same-named keys that a staff `activate` may have written into the config.
4. The settings response also carries `plan` and `cap_applies`. GET with nothing saved returns 200 with `prueftag_cap: null`.
## Tests
- `go build ./... && go vet ./...` pass.
- `go test -race ./...` passed with the Postgres harness, using rootless podman as the testcontainers backend.
- After two small edits I re-ran `-short` and the new and related tests against Postgres; all passed.
- New tests cover: plan resolution (STD, BUS, ENT, none, SCAN-only, mixed SKUs, JSONB `[]interface{}`); limits per plan, checking that null keys are present in the JSON rather than left out; settings validation; the role matrix with audit (user token, portal user, staff); a product client reading but not writing; the cap surviving an ERP recompute; the store contract on both stores; usage dedup for both metrics; and migration 0025 (table, one row per product, object check, cascade).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #114
307 lines
10 KiB
Go
307 lines
10 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Prüfwerk metering (t72): the plan limits the Prüfwerk agent reads from
|
|
// the entitlement check, and the workspace's own monthly cap on Prüftage.
|
|
//
|
|
// GET /v1/tenants/{id}/products/pruefwerk/settings (tenants.read)
|
|
// PUT /v1/tenants/{id}/products/pruefwerk/settings (tenants.write) {"prueftag_cap": <0..10000> | null}
|
|
//
|
|
// Who may: a user token needs IT_ADMIN, OWNER or FINANCE in its own tenant
|
|
// (403 FORBIDDEN_ROLE otherwise). Service clients are gated by their route
|
|
// group; the portal calls as its service client for the users it allows
|
|
// (named in X-Portal-User-*), staff through the admin client (X-Staff-*),
|
|
// as for the company profile.
|
|
//
|
|
// The cap is kept in tenant_product_settings (0025), not in
|
|
// tenant_products.config, which recomputeEntitlements rebuilds from the
|
|
// ERP subscriptions. On Enterprise the cap is stored but not applied: the
|
|
// check sends prueftag_cap null whatever was saved, and keeps the saved
|
|
// value for a later change of plan.
|
|
|
|
const pruefwerkProduct = "pruefwerk"
|
|
|
|
// Limit keys of the entitlement check, always sent for Prüfwerk; null is
|
|
// unlimited (no cap set).
|
|
const (
|
|
limitIncludedTargets = "included_targets"
|
|
limitMonthlyPruefungen = "monthly_pruefungen"
|
|
limitPrueftagCap = "prueftag_cap"
|
|
)
|
|
|
|
// maxPrueftagCap bounds the cap a workspace can set.
|
|
const maxPrueftagCap = 10000
|
|
|
|
// pruefwerkPlan is one Prüfwerk plan, identified by its subscription SKU.
|
|
// Unlimited: no target or Prüfung limit and no Prüftag cap.
|
|
type pruefwerkPlan struct {
|
|
Name string
|
|
SKU string
|
|
IncludedTargets int
|
|
MonthlyPruefungen int
|
|
Unlimited bool
|
|
}
|
|
|
|
// pruefwerkPlans, lowest first: a tenant holding several plan SKUs gets the
|
|
// highest, one without any (trial, preview grant, SCAN-only order) the first.
|
|
var pruefwerkPlans = []pruefwerkPlan{
|
|
{Name: "standard", SKU: "CRA-CSA-CLD-STD", IncludedTargets: 5, MonthlyPruefungen: 100},
|
|
{Name: "business", SKU: "CRA-CSA-CLD-BUS", IncludedTargets: 25, MonthlyPruefungen: 500},
|
|
{Name: "enterprise", SKU: "CRA-CSA-CLD-ENT", Unlimited: true},
|
|
}
|
|
|
|
// pruefwerkPlanFor resolves the plan from tenant_products.config["skus"]:
|
|
// []string as recomputeEntitlements writes it, []interface{} once it has
|
|
// been through JSONB.
|
|
func pruefwerkPlanFor(skus interface{}) pruefwerkPlan {
|
|
var list []string
|
|
switch v := skus.(type) {
|
|
case []string:
|
|
list = v
|
|
case []interface{}:
|
|
for _, x := range v {
|
|
if s, ok := x.(string); ok {
|
|
list = append(list, s)
|
|
}
|
|
}
|
|
}
|
|
best := 0
|
|
for _, sku := range list {
|
|
for i, p := range pruefwerkPlans {
|
|
if p.SKU == sku && i > best {
|
|
best = i
|
|
}
|
|
}
|
|
}
|
|
return pruefwerkPlans[best]
|
|
}
|
|
|
|
// pruefwerkLimits is the stored config plus the plan's limits and the
|
|
// workspace's cap, as a new map: the stored config stays as it is.
|
|
func pruefwerkLimits(cfg map[string]interface{}, prueftagCap *int) map[string]interface{} {
|
|
out := make(map[string]interface{}, len(cfg)+3)
|
|
for k, v := range cfg {
|
|
out[k] = v
|
|
}
|
|
plan := pruefwerkPlanFor(cfg["skus"])
|
|
if plan.Unlimited {
|
|
out[limitIncludedTargets], out[limitMonthlyPruefungen], out[limitPrueftagCap] = nil, nil, nil
|
|
return out
|
|
}
|
|
out[limitIncludedTargets] = plan.IncludedTargets
|
|
out[limitMonthlyPruefungen] = plan.MonthlyPruefungen
|
|
out[limitPrueftagCap] = capValue(prueftagCap)
|
|
return out
|
|
}
|
|
|
|
// capValue is the cap as a JSON value: an untyped nil marshals as null.
|
|
func capValue(c *int) interface{} {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
return *c
|
|
}
|
|
|
|
// pruefwerkSettings is the settings document of Prüfwerk.
|
|
type pruefwerkSettings struct {
|
|
PrueftagCap *int `json:"prueftag_cap"`
|
|
}
|
|
|
|
// loadPruefwerkSettings returns the saved settings; none saved is the zero
|
|
// value and a nil row.
|
|
func (s *Server) loadPruefwerkSettings(ctx context.Context, tenantID string) (pruefwerkSettings, *store.TenantProductSettings, error) {
|
|
row, err := s.Store.GetTenantProductSettings(ctx, tenantID, pruefwerkProduct)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
return pruefwerkSettings{}, nil, nil
|
|
}
|
|
if err != nil {
|
|
return pruefwerkSettings{}, nil, err
|
|
}
|
|
var set pruefwerkSettings
|
|
if err := json.Unmarshal(row.Settings, &set); err != nil {
|
|
return pruefwerkSettings{}, nil, fmt.Errorf("stored pruefwerk settings of %s: %v", tenantID, err)
|
|
}
|
|
return set, row, nil
|
|
}
|
|
|
|
// pruefwerkPlanOf is the tenant's current Prüfwerk plan (standard without a
|
|
// Prüfwerk entitlement).
|
|
func (s *Server) pruefwerkPlanOf(ctx context.Context, tenantID string) (pruefwerkPlan, error) {
|
|
tps, err := s.Store.ListTenantProducts(ctx, tenantID)
|
|
if err != nil {
|
|
return pruefwerkPlan{}, err
|
|
}
|
|
for _, tp := range tps {
|
|
if tp.Product == pruefwerkProduct {
|
|
return pruefwerkPlanFor(tp.Config["skus"]), nil
|
|
}
|
|
}
|
|
return pruefwerkPlans[0], nil
|
|
}
|
|
|
|
var pruefwerkSettingsRole = map[string]bool{authn.RoleITAdmin: true, authn.RoleOwner: true, "FINANCE": true}
|
|
|
|
type pruefwerkSettingsResp struct {
|
|
TenantID string `json:"tenant_id"`
|
|
Product string `json:"product"`
|
|
PrueftagCap *int `json:"prueftag_cap"`
|
|
// Plan is the Prüfwerk plan the limits come from; CapApplies is false
|
|
// on Enterprise, where a saved cap is kept but not applied.
|
|
Plan string `json:"plan"`
|
|
CapApplies bool `json:"cap_applies"`
|
|
UpdatedBy string `json:"updated_by,omitempty"`
|
|
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
|
}
|
|
|
|
func pruefwerkSettingsAnswer(tenantID string, set pruefwerkSettings, row *store.TenantProductSettings, plan pruefwerkPlan) pruefwerkSettingsResp {
|
|
out := pruefwerkSettingsResp{
|
|
TenantID: tenantID, Product: pruefwerkProduct, PrueftagCap: set.PrueftagCap,
|
|
Plan: plan.Name, CapApplies: !plan.Unlimited,
|
|
}
|
|
if row != nil {
|
|
at := row.UpdatedAt
|
|
out.UpdatedBy, out.UpdatedAt = row.UpdatedBy, &at
|
|
}
|
|
return out
|
|
}
|
|
|
|
// pruefwerkSettingsRoleOK checks the org role of a user token; on false the
|
|
// response is written.
|
|
func pruefwerkSettingsRoleOK(w http.ResponseWriter, r *http.Request) bool {
|
|
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !hasAnyRole(p.OrgRoles, pruefwerkSettingsRole) {
|
|
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "Prüfwerk settings require the IT_ADMIN, OWNER or FINANCE org role")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// getPruefwerkSettings is GET /v1/tenants/{id}/products/pruefwerk/settings.
|
|
// Nothing saved yet is prueftag_cap null.
|
|
func (s *Server) getPruefwerkSettings(w http.ResponseWriter, r *http.Request) {
|
|
if !pruefwerkSettingsRoleOK(w, r) {
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
t, ok := s.tenantInScope(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
set, row, err := s.loadPruefwerkSettings(ctx, t.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
plan, err := s.pruefwerkPlanOf(ctx, t.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, set, row, plan))
|
|
}
|
|
|
|
// putPruefwerkSettings is PUT /v1/tenants/{id}/products/pruefwerk/settings.
|
|
// A save that changes nothing writes nothing.
|
|
func (s *Server) putPruefwerkSettings(w http.ResponseWriter, r *http.Request) {
|
|
if !pruefwerkSettingsRoleOK(w, r) {
|
|
return
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
|
var in map[string]json.RawMessage
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
next, code, msg := parsePruefwerkSettings(in)
|
|
if code != "" {
|
|
writeError(w, http.StatusBadRequest, code, msg)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
t, ok := s.tenantInScope(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
cur, row, err := s.loadPruefwerkSettings(ctx, t.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
plan, err := s.pruefwerkPlanOf(ctx, t.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
if sameCap(cur.PrueftagCap, next.PrueftagCap) {
|
|
writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, cur, row, plan))
|
|
return
|
|
}
|
|
doc, _ := json.Marshal(next)
|
|
actor := s.teamActor(r)
|
|
saved, err := s.Store.PutTenantProductSettings(ctx, store.TenantProductSettings{
|
|
TenantID: t.ID, Product: pruefwerkProduct, Settings: doc,
|
|
UpdatedBy: firstNonEmpty(actor.Email, actor.ID), UpdatedAt: s.now(),
|
|
})
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: t.ID, Action: "product_settings.changed", TargetID: pruefwerkProduct, TargetType: "product_settings",
|
|
TargetName: "Prüfwerk", ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type,
|
|
Metadata: map[string]interface{}{
|
|
"setting": limitPrueftagCap, "old": capValue(cur.PrueftagCap), "new": capValue(next.PrueftagCap),
|
|
"plan": plan.Name, "applies": !plan.Unlimited,
|
|
},
|
|
})
|
|
writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, next, saved, plan))
|
|
}
|
|
|
|
// parsePruefwerkSettings checks a PUT body: exactly prueftag_cap, an integer
|
|
// 0..maxPrueftagCap or null. code is "" when the body is fine.
|
|
func parsePruefwerkSettings(in map[string]json.RawMessage) (set pruefwerkSettings, code, msg string) {
|
|
if in == nil {
|
|
return set, "invalid_body", "request body must be a JSON object"
|
|
}
|
|
for k := range in {
|
|
if k != limitPrueftagCap {
|
|
return set, "unknown_setting", fmt.Sprintf("unknown setting %q", k)
|
|
}
|
|
}
|
|
raw, ok := in[limitPrueftagCap]
|
|
if !ok {
|
|
return set, "prueftag_cap_required", "prueftag_cap is required (null for no cap)"
|
|
}
|
|
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
|
return set, "", ""
|
|
}
|
|
var n int
|
|
if err := json.Unmarshal(raw, &n); err != nil || n < 0 || n > maxPrueftagCap {
|
|
return set, "invalid_prueftag_cap", fmt.Sprintf("prueftag_cap must be an integer 0..%d or null", maxPrueftagCap)
|
|
}
|
|
set.PrueftagCap = &n
|
|
return set, "", ""
|
|
}
|
|
|
|
func sameCap(a, b *int) bool {
|
|
if a == nil || b == nil {
|
|
return a == nil && b == nil
|
|
}
|
|
return *a == *b
|
|
}
|