Files
sharangandSharang Parnerkar 32e10e0e13
ci / shared (push) Successful in 15s
ci / test (push) Successful in 26m37s
ci / image (push) Failing after 39s
feat(entitlements): Prüfwerk plan limits and Prüftag cap setting (t72) (#114)
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
2026-11-06 14:29:49 +00:00

283 lines
11 KiB
Go

package server_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// pruefwerkCheck posts the entitlement check and returns the raw body too,
// so a test can tell a null limit from a missing one.
func pruefwerkCheck(t *testing.T, h *testHarness, tenantID string) (map[string]any, []byte) {
t.Helper()
resp, raw := h.do("POST", "/v1/internal/entitlements/check", map[string]any{"tenant_id": tenantID, "product": "pruefwerk"})
if resp.StatusCode != http.StatusOK {
t.Fatalf("check: %d %s", resp.StatusCode, raw)
}
var out struct {
Allowed bool `json:"allowed"`
Limits map[string]any `json:"limits"`
}
if err := json.Unmarshal(raw, &out); err != nil || !out.Allowed {
t.Fatalf("check: %v %s", err, raw)
}
return out.Limits, raw
}
// bookSKUs submits a sales order for the tenant with the given items.
func bookSKUs(t *testing.T, h *testHarness, tenantID, order string, skus ...string) {
t.Helper()
items := make([]erp.WebhookItem, len(skus))
for i, sku := range skus {
items[i] = erp.WebhookItem{ItemCode: sku, Qty: 1}
}
ev := erp.WebhookEvent{Event: erp.EventSalesOrderSubmit, Doctype: "Sales Order", Name: order, TenantID: tenantID,
Subscription: "SUB-" + order, Items: items}
if resp, raw := h.webhook(t, ev, "evt-"+order); resp.StatusCode != http.StatusOK {
t.Fatalf("sales order %s: %d %s", order, resp.StatusCode, raw)
}
}
func putCap(t *testing.T, h *testHarness, tenantID, body string) (*http.Response, []byte) {
t.Helper()
return h.doRaw("PUT", "/v1/tenants/"+tenantID+"/products/pruefwerk/settings", body)
}
// The three Prüfwerk keys per plan, always present; null where unlimited.
func TestEntitlementCheck_pruefwerkPlanLimits(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
cases := []struct {
slug string
skus []string // nil: a trial, no plan SKU
targets any
pruefung any
plan string
}{
{"pw-trial", nil, 5.0, 100.0, "standard"},
{"pw-scan", []string{"CRA-CSA-CLD-SCAN"}, 5.0, 100.0, "standard"},
{"pw-std", []string{"CRA-CSA-CLD-STD"}, 5.0, 100.0, "standard"},
{"pw-bus", []string{"CRA-CSA-CLD-BUS", "CRA-WBK-CLD-ENT"}, 25.0, 500.0, "business"},
{"pw-mixed", []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-BUS"}, nil, nil, "enterprise"},
{"pw-ent", []string{"CRA-CSA-CLD-ENT"}, nil, nil, "enterprise"},
}
for i, c := range cases {
tn := newTenant(t, h, c.slug)
if c.skus == nil {
if resp, raw := h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); resp.StatusCode != http.StatusCreated {
t.Fatalf("%s trial: %d %s", c.slug, resp.StatusCode, raw)
}
} else {
bookSKUs(t, h, tn.ID, "SO-PW-"+string(rune('A'+i)), c.skus...)
}
// A cap the workspace set: passed on below Enterprise only.
if resp, raw := putCap(t, h, tn.ID, `{"prueftag_cap":12}`); resp.StatusCode != http.StatusOK {
t.Fatalf("%s put: %d %s", c.slug, resp.StatusCode, raw)
}
limits, raw := pruefwerkCheck(t, h, tn.ID)
wantCap := any(12.0)
if c.plan == "enterprise" {
wantCap = nil
}
for key, want := range map[string]any{"included_targets": c.targets, "monthly_pruefungen": c.pruefung, "prueftag_cap": wantCap} {
got, ok := limits[key]
if !ok || got != want {
t.Errorf("%s %s = %v (present %v), want %v; %s", c.slug, key, got, ok, want, raw)
}
if want == nil && !bytes.Contains(raw, []byte(`"`+key+`":null`)) {
t.Errorf("%s %s not sent as null: %s", c.slug, key, raw)
}
}
if c.skus != nil && limits["skus"] == nil {
t.Errorf("%s: stored config keys dropped: %s", c.slug, raw)
}
_, raw = h.do("GET", "/v1/tenants/"+tn.ID+"/products/pruefwerk/settings", nil)
got := decode[map[string]any](t, raw)
if got["plan"] != c.plan || got["cap_applies"] != (c.plan != "enterprise") || got["prueftag_cap"] != 12.0 {
t.Errorf("%s settings: %s", c.slug, raw)
}
}
// The limits are a copy: the stored config gains none of the keys.
tn := newTenant(t, h, "pw-copy")
bookSKUs(t, h, tn.ID, "SO-PW-COPY", "CRA-CSA-CLD-BUS")
pruefwerkCheck(t, h, tn.ID)
tps, err := h.store.ListTenantProducts(context.Background(), tn.ID)
if err != nil {
t.Fatal(err)
}
for _, tp := range tps {
if _, ok := tp.Config["included_targets"]; ok {
t.Fatalf("stored config mutated: %+v", tp.Config)
}
}
// Other products are unchanged.
bookSKUs(t, h, tn.ID, "SO-PW-FWK", "DEV-FWK-CLD-STD")
resp, raw := h.do("POST", "/v1/internal/entitlements/check", map[string]any{"tenant_id": tn.ID, "product": "firmwerk"})
if resp.StatusCode != http.StatusOK || bytes.Contains(raw, []byte("included_targets")) || bytes.Contains(raw, []byte("prueftag_cap")) {
t.Fatalf("firmwerk check: %d %s", resp.StatusCode, raw)
}
})
}
// recomputeEntitlements rebuilds tenant_products.config; the cap lives
// elsewhere and stays.
func TestPruefwerkSettings_surviveRecompute(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := newTenant(t, h, "pw-recompute")
bookSKUs(t, h, tn.ID, "SO-RC-1", "CRA-CSA-CLD-STD")
if resp, raw := putCap(t, h, tn.ID, `{"prueftag_cap":7}`); resp.StatusCode != http.StatusOK {
t.Fatalf("put: %d %s", resp.StatusCode, raw)
}
// Upgrade: a new order recomputes the entitlement from scratch.
bookSKUs(t, h, tn.ID, "SO-RC-2", "CRA-CSA-CLD-BUS")
limits, raw := pruefwerkCheck(t, h, tn.ID)
if limits["prueftag_cap"] != 7.0 || limits["included_targets"] != 25.0 {
t.Fatalf("after recompute: %s", raw)
}
tps, err := h.store.ListTenantProducts(context.Background(), tn.ID)
if err != nil {
t.Fatal(err)
}
for _, tp := range tps {
if _, ok := tp.Config["prueftag_cap"]; ok {
t.Fatalf("cap leaked into the ERP-derived config: %+v", tp.Config)
}
}
})
}
func TestPruefwerkSettings_putValidation(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
id := h.tenant.ID
_, raw := h.do("GET", "/v1/tenants/"+id+"/products/pruefwerk/settings", nil)
if got := decode[map[string]any](t, raw); got["prueftag_cap"] != nil || !bytes.Contains(raw, []byte(`"prueftag_cap":null`)) {
t.Fatalf("nothing saved: %s", raw)
}
for _, c := range []struct {
body string
code int
want string
}{
{`{"prueftag_cap":0}`, 200, `"prueftag_cap":0`},
{`{"prueftag_cap":10000}`, 200, `"prueftag_cap":10000`},
{`{"prueftag_cap":null}`, 200, `"prueftag_cap":null`},
{`{"prueftag_cap":-1}`, 400, "invalid_prueftag_cap"},
{`{"prueftag_cap":10001}`, 400, "invalid_prueftag_cap"},
{`{"prueftag_cap":2.5}`, 400, "invalid_prueftag_cap"},
{`{"prueftag_cap":"5"}`, 400, "invalid_prueftag_cap"},
{`{"prueftag_cap":true}`, 400, "invalid_prueftag_cap"},
{`{"prueftag_cap":5,"monthly_pruefungen":900}`, 400, "unknown_setting"},
{`{}`, 400, "prueftag_cap_required"},
{`null`, 400, "invalid_body"},
{`[5]`, 400, "invalid_body"},
} {
resp, raw := putCap(t, h, id, c.body)
if resp.StatusCode != c.code || !bytes.Contains(raw, []byte(c.want)) {
t.Errorf("PUT %s: %d %s", c.body, resp.StatusCode, raw)
}
}
_, raw = h.do("GET", "/v1/tenants/"+id+"/products/pruefwerk/settings", nil)
if !bytes.Contains(raw, []byte(`"prueftag_cap":null`)) {
t.Fatalf("after clearing: %s", raw)
}
// 0 → 10000 → null: three changes, each audited with old and new.
_, raw = h.do("GET", "/v1/audit?tenant_id="+id+"&action=product_settings.changed&limit=10", nil)
evs := decode[struct {
Items []store.AuditEvent `json:"items"`
}](t, raw).Items
if len(evs) != 3 {
t.Fatalf("audit events: %s", raw)
}
if resp, _ := putCap(t, h, "00000000-0000-0000-0000-00000000beef", `{"prueftag_cap":1}`); resp.StatusCode != http.StatusNotFound {
t.Fatalf("unknown tenant: %d", resp.StatusCode)
}
})
}
// Both stores: replace, read back, unknown tenant, bad id, not an object.
func TestProductSettingsStore(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
put := func(tenantID, doc string) (*store.TenantProductSettings, error) {
return h.store.PutTenantProductSettings(ctx, store.TenantProductSettings{
TenantID: tenantID, Product: "pruefwerk", Settings: json.RawMessage(doc), UpdatedBy: "u-1", UpdatedAt: time.Now(),
})
}
if _, err := h.store.GetTenantProductSettings(ctx, h.tenant.ID, "pruefwerk"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("none yet: %v", err)
}
if _, err := put(h.tenant.ID, `{"prueftag_cap":3}`); err != nil {
t.Fatal(err)
}
got, err := put(h.tenant.ID, `{"prueftag_cap":null}`)
if err != nil || got.UpdatedBy != "u-1" || mustCanon(t, got.Settings) != `{"prueftag_cap":null}` {
t.Fatalf("replace: %+v %v", got, err)
}
got, err = h.store.GetTenantProductSettings(ctx, h.tenant.ID, "pruefwerk")
if err != nil || mustCanon(t, got.Settings) != `{"prueftag_cap":null}` || got.Product != "pruefwerk" {
t.Fatalf("read back: %+v %v", got, err)
}
if _, err := h.store.GetTenantProductSettings(ctx, h.tenant.ID, "firmwerk"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("other product: %v", err)
}
if _, err := put("00000000-0000-0000-0000-00000000beef", `{}`); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("unknown tenant: %v", err)
}
if _, err := h.store.GetTenantProductSettings(ctx, "not-a-uuid", "pruefwerk"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("bad id: %v", err)
}
if _, err := put(h.tenant.ID, `[1]`); !errors.Is(err, store.ErrInvalidInput) {
t.Fatalf("not an object: %v", err)
}
})
}
// The two Prüfwerk metering metrics go through the generic usage path:
// stored once per idempotency key, a repeat is a duplicate (no update in
// place, so a later, higher target.extra peak comes with its own key).
func TestUsageEvents_pruefwerkMeteringMetrics(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := newTenant(t, h, "pw-usage")
events := []map[string]any{
{"idempotency_key": "prueftag:" + tn.ID + ":tgt-1:2026-11-05", "tenant_id": tn.ID, "product": "pruefwerk",
"metric": "prueftag.booked", "quantity": 1, "occurred_at": "2026-11-05T09:00:00Z"},
{"idempotency_key": "target-extra:" + tn.ID + ":2026-11:3", "tenant_id": tn.ID, "product": "pruefwerk",
"metric": "target.extra", "quantity": 3, "occurred_at": "2026-11-05T09:00:00Z"},
}
resp, raw := h.do("POST", "/v1/usage/events", map[string]any{"events": events})
if resp.StatusCode != http.StatusAccepted || !bytes.Contains(raw, []byte(`"accepted":2`)) {
t.Fatalf("first: %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("POST", "/v1/usage/events", map[string]any{"events": events})
if resp.StatusCode != http.StatusAccepted || !bytes.Contains(raw, []byte(`"accepted":0`)) || !bytes.Contains(raw, []byte(`"duplicates":2`)) {
t.Fatalf("repeat: %d %s", resp.StatusCode, raw)
}
// Same Prüftag key with another quantity: still the first event.
again := map[string]any{}
for k, v := range events[0] {
again[k] = v
}
again["quantity"] = 5
if _, raw := h.do("POST", "/v1/usage/events", again); !bytes.Contains(raw, []byte(`"duplicates":1`)) {
t.Fatalf("changed repeat: %s", raw)
}
for metric, qty := range map[string]float64{"prueftag.booked": 1, "target.extra": 3} {
_, raw := h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&metric="+metric, nil)
items := decode[struct {
Items []store.UsageEvent `json:"items"`
}](t, raw).Items
if len(items) != 1 || items[0].Quantity != qty || items[0].Product != "pruefwerk" {
t.Fatalf("%s: %s", metric, raw)
}
}
})
}