Files
tenant-registry/internal/store/memory.go
T
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

660 lines
17 KiB
Go

package store
import (
"bytes"
"context"
"sort"
"strings"
"sync"
"time"
"github.com/google/uuid"
)
// Memory — in-process Store used when DATABASE_URL is empty. Convenient for
// local dev when you don't want to bring up Postgres + run migrations.
// Pre-seeded with the acme tenant.
type Memory struct {
mu sync.RWMutex
tenants map[string]*Tenant // id → tenant
bySlug map[string]string // slug → id
products map[string]map[string]*TenantProduct // tenant_id → product → row
apiKeys map[string]*apiKeyWithHash // id → key
audit []*AuditEvent
auditID int64
catalog []Product
// M-MIG-7
subs map[string]*Subscription // id → row
usage []*UsageEvent
usageKey map[string]int64 // idempotency key → id
usageID int64
outbox []*OutboxItem
outboxID int64
receipts map[string]time.Time
licences map[string]*Licence
documents map[string]*Document
projects map[string]*Project
offers map[string]*TrialOffer
services map[string]*ManagedService
preparations map[string]*Preparation // document id → delivered prepared version (0022)
assets map[string]*StoreAsset // tenant_id + "/" + sha256 (0022)
profiles map[string]*CompanyProfile // tenant_id → current
profRevs map[string][]CompanyProfile // tenant_id → every revision
roleSets map[string][]RoleDataset // tenant_id → every revision, oldest first (0024)
mail []*MailItem
mailID int64
prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025)
}
type apiKeyWithHash struct {
APIKey
Hash string
HashSHA256 []byte
}
// NewMemory returns a fresh in-memory store with the seed acme tenant.
func NewMemory() *Memory {
m := &Memory{
tenants: make(map[string]*Tenant),
bySlug: make(map[string]string),
products: make(map[string]map[string]*TenantProduct),
apiKeys: make(map[string]*apiKeyWithHash),
catalog: DefaultProducts(),
subs: make(map[string]*Subscription),
usageKey: make(map[string]int64),
receipts: make(map[string]time.Time),
licences: make(map[string]*Licence),
projects: make(map[string]*Project),
offers: make(map[string]*TrialOffer),
services: make(map[string]*ManagedService),
profiles: make(map[string]*CompanyProfile),
preparations: make(map[string]*Preparation),
assets: make(map[string]*StoreAsset),
profRevs: make(map[string][]CompanyProfile),
roleSets: make(map[string][]RoleDataset),
documents: make(map[string]*Document),
prodSets: make(map[string]*TenantProductSettings),
}
now := time.Now().UTC()
seed := &Tenant{
ID: "00000000-0000-0000-0000-000000000001",
Slug: "acme",
Name: "Acme Inc.",
Status: "active",
Kind: "customer",
Plan: "professional",
StatusChangedAt: now,
CreatedAt: now,
UpdatedAt: now,
}
m.tenants[seed.ID] = seed
m.bySlug[seed.Slug] = seed.ID
m.products[seed.ID] = map[string]*TenantProduct{
"pruefwerk": {TenantID: seed.ID, Product: "pruefwerk", Enabled: true, Config: map[string]interface{}{"runners": float64(1)}, CreatedAt: now, UpdatedAt: now},
"firmwerk": {TenantID: seed.ID, Product: "firmwerk", Enabled: true, Config: map[string]interface{}{}, CreatedAt: now, UpdatedAt: now},
}
return m
}
func (m *Memory) Close() {}
func (m *Memory) Ping(_ context.Context) error { return nil }
// ─── tenants ──────────────────────────────────────────────────────────────
func (m *Memory) CreateTenant(_ context.Context, in TenantCreate) (*Tenant, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, taken := m.bySlug[in.Slug]; taken {
return nil, ErrConflict
}
now := time.Now().UTC()
kind := firstNonEmpty(in.Kind, "customer")
status := "trial"
var trialEnds *time.Time
if kind == "demo" {
status = "demo"
} else {
end := now.Add(14 * 24 * time.Hour)
trialEnds = &end
}
t := &Tenant{
ID: uuid.NewString(),
Slug: in.Slug,
Name: in.Name,
Status: status,
Kind: kind,
Plan: firstNonEmpty(in.Plan, "starter"),
SalesOwner: in.SalesOwner,
AdminEmail: in.AdminEmail,
TrialEndsAt: trialEnds,
StatusChangedAt: now,
CreatedAt: now,
UpdatedAt: now,
}
m.tenants[t.ID] = t
m.bySlug[t.Slug] = t.ID
cp := *t
return &cp, nil
}
func (m *Memory) GetTenant(_ context.Context, id string) (*Tenant, error) {
m.mu.RLock()
defer m.mu.RUnlock()
t, ok := m.tenants[id]
if !ok {
return nil, ErrNotFound
}
cp := *t
return &cp, nil
}
func (m *Memory) GetTenantBySlug(_ context.Context, slug string) (*Tenant, error) {
m.mu.RLock()
defer m.mu.RUnlock()
id, ok := m.bySlug[slug]
if !ok {
return nil, ErrNotFound
}
t := m.tenants[id]
cp := *t
return &cp, nil
}
func (m *Memory) GetTenantByErpCustomerID(_ context.Context, erpCustomerID string) (*Tenant, error) {
m.mu.RLock()
defer m.mu.RUnlock()
if erpCustomerID == "" {
return nil, ErrNotFound
}
for _, t := range m.tenants {
if t.ErpCustomerID == erpCustomerID {
cp := *t
return &cp, nil
}
}
return nil, ErrNotFound
}
func (m *Memory) UpdateTenant(_ context.Context, id string, in TenantUpdate) (*Tenant, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tenants[id]
if !ok {
return nil, ErrNotFound
}
if in.Status != nil {
if *in.Status != t.Status {
t.StatusChangedAt = time.Now().UTC()
}
t.Status = *in.Status
}
if in.Plan != nil {
t.Plan = *in.Plan
}
if in.ErpCustomerID != nil {
t.ErpCustomerID = *in.ErpCustomerID
}
if in.StripeCustID != nil {
t.StripeCustID = *in.StripeCustID
}
if in.TrialEndsAt != nil {
t.TrialEndsAt = in.TrialEndsAt
}
if in.ContractStart != nil {
t.ContractStart = in.ContractStart
}
if in.ContractEnd != nil {
t.ContractEnd = in.ContractEnd
}
if in.SalesOwner != nil {
t.SalesOwner = *in.SalesOwner
}
if in.AdminEmail != nil {
t.AdminEmail = *in.AdminEmail
}
t.UpdatedAt = time.Now().UTC()
cp := *t
return &cp, nil
}
func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, string, error) {
m.mu.RLock()
defer m.mu.RUnlock()
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
cAt, cID, ok := decodeTenantCursor(f.Cursor)
if !ok {
return nil, "", ErrInvalidInput
}
all := make([]Tenant, 0, len(m.tenants))
for _, t := range m.tenants {
if f.Status != "" && t.Status != f.Status {
continue
}
if f.Kind != "" && t.Kind != f.Kind {
continue
}
if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" &&
!strings.Contains(strings.ToLower(t.Slug), q) &&
!strings.Contains(strings.ToLower(t.Name), q) &&
!strings.Contains(strings.ToLower(t.AdminEmail), q) {
continue
}
// keyset: only rows strictly after (cAt, cID)
if f.Cursor != "" && t.CreatedAt.Before(cAt) || (f.Cursor != "" && t.CreatedAt.Equal(cAt) && t.ID <= cID) {
continue
}
all = append(all, *t)
}
sort.Slice(all, func(i, j int) bool {
if all[i].CreatedAt.Equal(all[j].CreatedAt) {
return all[i].ID < all[j].ID
}
return all[i].CreatedAt.Before(all[j].CreatedAt)
})
next := ""
if len(all) > limit {
all = all[:limit]
next = encodeTenantCursor(all[len(all)-1])
}
return all, next, nil
}
func (m *Memory) TenantActivity(_ context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) {
m.mu.RLock()
defer m.mu.RUnlock()
want := map[string]bool{}
for _, id := range tenantIDs {
want[id] = true
}
out := map[string]TenantActivity{}
get := func(id string) TenantActivity {
a, ok := out[id]
if !ok {
a = TenantActivity{Usage: map[string]float64{}}
}
return a
}
for _, u := range m.usage {
if !want[u.TenantID] || u.OccurredAt.Before(since) {
continue
}
a := get(u.TenantID)
a.Usage[u.Metric] += u.Quantity
out[u.TenantID] = a
}
for _, ev := range m.audit {
if !want[ev.TenantID] {
continue
}
a := get(ev.TenantID)
if a.LastActivityAt == nil || ev.CreatedAt.After(*a.LastActivityAt) {
at := ev.CreatedAt
a.LastActivityAt = &at
}
out[ev.TenantID] = a
}
return out, nil
}
// ─── products ─────────────────────────────────────────────────────────────
func (m *Memory) ListProducts(_ context.Context, includeDisabled bool) ([]Product, error) {
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]Product, 0, len(m.catalog))
for _, p := range m.catalog {
if p.Enabled || includeDisabled {
out = append(out, p)
}
}
sort.SliceStable(out, func(i, j int) bool { return out[i].SortOrder < out[j].SortOrder })
return out, nil
}
func (m *Memory) GetProduct(_ context.Context, key string) (*Product, error) {
m.mu.RLock()
defer m.mu.RUnlock()
for _, p := range m.catalog {
if p.Key == key {
cp := p
return &cp, nil
}
}
return nil, ErrNotFound
}
// ─── entitlements ─────────────────────────────────────────────────────────
func (m *Memory) UpsertTenantProduct(_ context.Context, tp TenantProduct) (*TenantProduct, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[tp.TenantID]; !ok {
return nil, ErrNotFound
}
if _, ok := m.products[tp.TenantID]; !ok {
m.products[tp.TenantID] = map[string]*TenantProduct{}
}
now := time.Now().UTC()
stored, exists := m.products[tp.TenantID][tp.Product]
if !exists {
stored = &TenantProduct{
TenantID: tp.TenantID,
Product: tp.Product,
CreatedAt: now,
}
m.products[tp.TenantID][tp.Product] = stored
}
stored.Enabled = tp.Enabled
stored.Config = tp.Config
stored.ExpiresAt = tp.ExpiresAt
stored.Preview, stored.PreviewExpiresAt = false, nil // a real booking ends a preview
stored.UpdatedAt = now
cp := *stored
return &cp, nil
}
func (m *Memory) SetPreviewGrant(_ context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
if _, ok := m.products[tenantID]; !ok {
m.products[tenantID] = map[string]*TenantProduct{}
}
now := time.Now().UTC()
stored, exists := m.products[tenantID][product]
if exists && stored.Enabled && !stored.Preview {
return nil, ErrConflict
}
if !exists {
stored = &TenantProduct{TenantID: tenantID, Product: product, Config: map[string]interface{}{}, CreatedAt: now}
m.products[tenantID][product] = stored
}
exp := expiresAt
stored.Enabled, stored.Preview, stored.PreviewExpiresAt, stored.UpdatedAt = true, true, &exp, now
cp := *stored
return &cp, nil
}
func (m *Memory) RevokePreviewGrant(_ context.Context, tenantID, product string) error {
m.mu.Lock()
defer m.mu.Unlock()
stored, ok := m.products[tenantID][product]
if !ok || !stored.Preview {
return ErrNotFound
}
delete(m.products[tenantID], product)
return nil
}
func (m *Memory) ListTenantProducts(_ context.Context, tenantID string) ([]TenantProduct, error) {
m.mu.RLock()
defer m.mu.RUnlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
out := make([]TenantProduct, 0, len(m.products[tenantID]))
for _, p := range m.products[tenantID] {
out = append(out, *p)
}
sort.Slice(out, func(i, j int) bool { return out[i].Product < out[j].Product })
return out, nil
}
// ─── api keys ─────────────────────────────────────────────────────────────
func (m *Memory) CreateAPIKey(_ context.Context, in APIKeyCreate) (*APIKey, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[in.TenantID]; !ok {
return nil, ErrNotFound
}
for _, k := range m.apiKeys {
if k.TenantID == in.TenantID && k.Name == in.Name && k.RevokedAt == nil {
return nil, ErrConflict
}
if len(in.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, in.HashSHA256) {
return nil, ErrConflict
}
}
kind := in.Kind
if kind == "" {
kind = APIKeyKindUser
}
now := time.Now().UTC()
k := &apiKeyWithHash{
APIKey: APIKey{
ID: uuid.NewString(),
TenantID: in.TenantID,
Product: in.Product,
Name: in.Name,
Scopes: append([]string{}, in.Scopes...),
Prefix: in.Prefix,
Kind: kind,
Holder: in.Holder,
ExpiresAt: in.ExpiresAt,
CreatedBy: in.CreatedBy,
CreatedAt: now,
},
Hash: in.Hash,
HashSHA256: append([]byte(nil), in.HashSHA256...),
}
m.apiKeys[k.ID] = k
cp := k.APIKey
return &cp, nil
}
func (m *Memory) FindAPIKeyBySHA256(_ context.Context, sum []byte) (*APIKey, error) {
m.mu.RLock()
defer m.mu.RUnlock()
for _, k := range m.apiKeys {
if k.RevokedAt == nil && len(k.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, sum) {
cp := k.APIKey
return &cp, nil
}
}
return nil, ErrNotFound
}
func (m *Memory) FindAPIKeysByPrefix(_ context.Context, prefix string) ([]APIKeyCandidate, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var out []APIKeyCandidate
for _, k := range m.apiKeys {
if k.Prefix == prefix && k.RevokedAt == nil && k.Hash != "" {
out = append(out, APIKeyCandidate{APIKey: k.APIKey, Hash: k.Hash})
}
}
return out, nil
}
func (m *Memory) TouchAPIKeyUsed(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
k, ok := m.apiKeys[id]
if !ok {
return ErrNotFound
}
now := time.Now().UTC()
k.LastUsedAt = &now
return nil
}
func (m *Memory) RevokeAPIKey(_ context.Context, id, tenantID string) error {
m.mu.Lock()
defer m.mu.Unlock()
k, ok := m.apiKeys[id]
if !ok || k.RevokedAt != nil || (tenantID != "" && k.TenantID != tenantID) {
return ErrNotFound
}
now := time.Now().UTC()
k.RevokedAt = &now
return nil
}
func (m *Memory) ListAPIKeys(_ context.Context, tenantID string) ([]APIKey, error) {
m.mu.RLock()
defer m.mu.RUnlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
out := []APIKey{}
for _, k := range m.apiKeys {
if k.TenantID == tenantID {
out = append(out, k.APIKey)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) })
return out, nil
}
// ─── audit ────────────────────────────────────────────────────────────────
func (m *Memory) AppendAudit(_ context.Context, ev AuditEvent) (*AuditEvent, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.auditID++
ev.ID = m.auditID
ev.CreatedAt = time.Now().UTC()
cp := ev
m.audit = append(m.audit, &cp)
out := ev
return &out, nil
}
func (m *Memory) ListAudit(_ context.Context, f AuditFilter) ([]AuditEvent, int64, error) {
m.mu.RLock()
defer m.mu.RUnlock()
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
matches := []AuditEvent{}
for _, ev := range m.audit {
if ev.ID <= f.Cursor {
continue
}
if f.TenantID != "" && ev.TenantID != f.TenantID {
continue
}
if f.Product != "" && ev.Product != f.Product {
continue
}
if f.ActorID != "" && ev.ActorID != f.ActorID {
continue
}
if f.Action != "" && ev.Action != f.Action {
continue
}
if f.Since != nil && ev.CreatedAt.Before(*f.Since) {
continue
}
if f.Until != nil && ev.CreatedAt.After(*f.Until) {
continue
}
matches = append(matches, *ev)
if len(matches) >= limit {
break
}
}
var nextCursor int64
if len(matches) == limit && len(matches) > 0 {
nextCursor = matches[len(matches)-1].ID
}
return matches, nextCursor, nil
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}
// DeleteTenant implements Store.
func (m *Memory) DeleteTenant(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tenants[id]
if !ok {
return ErrNotFound
}
delete(m.tenants, id)
delete(m.bySlug, t.Slug)
delete(m.products, id)
for k, ps := range m.prodSets {
if ps.TenantID == id {
delete(m.prodSets, k)
}
}
for kid, k := range m.apiKeys {
if k.TenantID == id {
delete(m.apiKeys, kid)
}
}
for sid, sub := range m.subs {
if sub.TenantID == id {
delete(m.subs, sid)
}
}
for lid, l := range m.licences {
if l.TenantID == id {
delete(m.licences, lid)
}
}
for did, d := range m.documents {
if d.TenantID == id {
delete(m.documents, did)
}
}
for pid, pr := range m.projects {
if pr.TenantID == id {
delete(m.projects, pid)
}
}
for sid, ms := range m.services {
if ms.TenantID == id {
delete(m.services, sid)
}
}
usage := m.usage[:0]
for _, u := range m.usage {
if u.TenantID != id {
usage = append(usage, u)
} else {
delete(m.usageKey, u.IdempotencyKey)
}
}
m.usage = usage
outbox := m.outbox[:0]
for _, o := range m.outbox {
if o.TenantID != id {
outbox = append(outbox, o)
}
}
m.outbox = outbox
mail := m.mail[:0]
for _, mi := range m.mail {
if mi.TenantID != id {
mail = append(mail, mi)
}
}
m.mail = mail
for _, a := range m.audit {
if a.TenantID == id {
a.TenantID = ""
}
}
return nil
}