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

280 lines
15 KiB
Go

// Package store hides the persistence layer behind a Store interface.
// Two implementations: Memory (dev convenience, used when DATABASE_URL is
// empty) and Postgres (production via pgx). Handlers depend on the
// interface — never on a concrete type.
package store
import (
"context"
"errors"
"time"
)
// Sentinel errors.
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrInvalidInput = errors.New("invalid input")
// ErrHasChildren: a project with sub-projects cannot be deleted (0020).
ErrHasChildren = errors.New("has children")
)
// TenantCreate is the input shape for Store.CreateTenant.
type TenantCreate struct {
Slug string
Name string
Plan string // optional, defaults to "starter"
Kind string // optional, defaults to "customer"
SalesOwner string // optional
AdminEmail string // optional — the first admin invited at creation
}
// TenantUpdate captures partial mutations. Nil fields are left untouched.
type TenantUpdate struct {
Status *string
Plan *string
ErpCustomerID *string
StripeCustID *string
TrialEndsAt *time.Time
ContractStart *time.Time
ContractEnd *time.Time
SalesOwner *string
AdminEmail *string
}
// APIKeyCreate is the input shape for Store.CreateAPIKey.
type APIKeyCreate struct {
TenantID string
Product string // empty = applies to all products
Name string
Scopes []string
Prefix string
Hash string // argon2id encoded; keys created before migration 0015 only
HashSHA256 []byte // sha256 of the plaintext; every new key
Kind string // user | ci | integration; empty = user
Holder string // integration keys only
ExpiresAt *time.Time
CreatedBy string
}
// APIKeyCandidate is an active key found by its display prefix, with the
// stored argon2id hash the caller must check.
type APIKeyCandidate struct {
APIKey
Hash string
}
// AuditFilter narrows /v1/audit GET results.
type AuditFilter struct {
TenantID string
Product string
ActorID string
Action string
Since *time.Time
Until *time.Time
Limit int
Cursor int64 // id > Cursor (ascending) is the next page anchor
}
// Store is the persistence contract. Implementations:
// - Memory — in-process, used when DATABASE_URL is empty (dev convenience).
// - Postgres — pgxpool-backed, used in stage + prod.
type Store interface {
// Tenants
CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, error)
GetTenant(ctx context.Context, id string) (*Tenant, error)
GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error)
GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error)
UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error)
ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) // rows + next cursor ("" = none)
// TenantActivity returns usage totals since `since` and the latest audit
// time for each of the given tenants (tenants without either are absent).
TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error)
// Products (catalog)
ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error)
GetProduct(ctx context.Context, key string) (*Product, error)
// Entitlements
UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error)
ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error)
// SetPreviewGrant grants (or extends) a preview of product until
// expiresAt; ErrConflict when the tenant has really booked it.
SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error)
// RevokePreviewGrant removes a preview grant; ErrNotFound when there is
// none (a real booking is never removed this way).
RevokePreviewGrant(ctx context.Context, tenantID, product string) error
// API keys
CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error)
// FindAPIKeyBySHA256 returns the active (not revoked) key with this hash.
FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error)
// FindAPIKeysByPrefix returns every active argon2id key with this prefix;
// prefixes are not unique, the caller checks each hash.
FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error)
TouchAPIKeyUsed(ctx context.Context, id string) error
// RevokeAPIKey revokes key id; a non-empty tenantID must own it, else ErrNotFound.
RevokeAPIKey(ctx context.Context, id, tenantID string) error
ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error)
// Audit
AppendAudit(ctx context.Context, ev AuditEvent) (*AuditEvent, error)
ListAudit(ctx context.Context, f AuditFilter) ([]AuditEvent, int64, error) // returns rows + next cursor (0 = none)
// Subscriptions (M-MIG-7, mirrored from ERPNext Sales Orders)
UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) // key (tenant_id, sku, erp_sales_order)
ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error)
// Usage events (§9.2). Inserted reports false when the idempotency key
// was already stored (the existing row is returned).
InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error)
ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error)
MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error
// ERP outbox. ClaimOutbox returns due rows (next_attempt_at <= now) and
// pushes their next_attempt_at by lease so a second worker skips them.
EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error)
ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error)
CompleteOutbox(ctx context.Context, id int64, at time.Time) error
FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error
// DeadLetterOutbox gives up on an item: done, with the reason kept in
// last_error (prefixed "dead letter: ") so it can be found and re-queued.
DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error
PendingOutbox(ctx context.Context) (int, error)
// Webhook idempotency: true when eventID was not seen before.
RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error)
// Licences
CreateLicence(ctx context.Context, l Licence) (*Licence, error)
GetLicence(ctx context.Context, id string) (*Licence, error)
ListLicences(ctx context.Context, tenantID string) ([]Licence, error)
// FindReusableLicence returns the newest licence for (tenant, product,
// subject, device) created at or after since that is neither revoked
// nor expired at now; ErrNotFound otherwise. CI licences are reused
// per key, device and UTC day instead of one row per job.
FindReusableLicence(ctx context.Context, tenantID, product, subject, device string, since, now time.Time) (*Licence, error)
RevokeLicence(ctx context.Context, id string, at time.Time) error
TouchLicence(ctx context.Context, id string, at time.Time) error
// SetLicenceLLMKey records (or clears, with "") the LiteLLM key id.
SetLicenceLLMKey(ctx context.Context, id string, keyID string) error
// SetLicenceLLMSecret stores the sealed LiteLLM secret of a CI licence.
SetLicenceLLMSecret(ctx context.Context, id string, sealed []byte) error
// Documents (0008). ID and ObjectKey are chosen by the caller (the object
// is stored before the row). ListDocuments with publishedOnly hides drafts.
CreateDocument(ctx context.Context, d Document) (*Document, error)
GetDocument(ctx context.Context, id string) (*Document, error)
ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error)
// DeleteTenant removes the tenant and everything that belongs to it
// (entitlements, keys, subscriptions, usage, licences, outbox, documents,
// projects, managed services, mail). Audit events stay, with the tenant reference cleared.
// ErrNotFound when there is no such tenant.
DeleteTenant(ctx context.Context, id string) error
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
DeleteDocument(ctx context.Context, id string) error
// SetDocumentProjects replaces a document's projects; every project must
// belong to the document's tenant (ErrInvalidInput otherwise).
SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error)
SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error)
// Dokumentenablage (0022, 0023). ListDocuments returns every document of
// the tenant; ListStoreDocuments the published ones as the store shows
// them: by area (BreakPilot's deliveries, no area, last), legal folder and
// title. GetDocumentByExternalID
// finds a document by the Factory's id (ErrNotFound when none).
ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error)
GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error)
SetDocumentProcessing(ctx context.Context, docID, status, errMsg string) (*Document, error)
// SaveDocumentPreparation stores the delivered parts (a chunk part and/or a
// consent part; a part left empty keeps what is stored) and marks the
// document ready when it has a chunk part.
SaveDocumentPreparation(ctx context.Context, p Preparation) (*Preparation, error)
// GetDocumentPreparation is ErrNotFound when nothing was delivered.
GetDocumentPreparation(ctx context.Context, docID string) (*Preparation, error)
// ListDocumentPreparations maps document id → preparation for a tenant.
ListDocumentPreparations(ctx context.Context, tenantID string) (map[string]Preparation, error)
// PutStoreAsset is idempotent on (tenant, sha256); GetStoreAsset is
// ErrNotFound for an asset the tenant does not hold.
PutStoreAsset(ctx context.Context, a StoreAsset) (*StoreAsset, error)
GetStoreAsset(ctx context.Context, tenantID, sha256 string) (*StoreAsset, error)
// Trial offers (0011, portal#64). Only the state moves; the snapshot is
// written by CreateTrialOffer and never changed.
CreateTrialOffer(ctx context.Context, o TrialOffer) (*TrialOffer, error)
GetTrialOffer(ctx context.Context, id string) (*TrialOffer, error)
GetTrialOfferByToken(ctx context.Context, tokenHash string) (*TrialOffer, error)
GetTrialOfferByTenant(ctx context.Context, tenantID string) (*TrialOffer, error)
// LatestTrialOffer is the newest offer for the address (case-insensitive).
LatestTrialOffer(ctx context.Context, email string) (*TrialOffer, error)
// SetTrialOfferToken replaces the confirmation token of a pending offer
// (ErrConflict once it is verified).
SetTrialOfferToken(ctx context.Context, id, tokenHash string, expires time.Time) (*TrialOffer, error)
// VerifyTrialOffer moves a pending offer to verified (ErrConflict when it
// is not pending), so only one confirmation click activates.
VerifyTrialOffer(ctx context.Context, id string, at time.Time) (*TrialOffer, error)
// ActivateTrialOffer records the acceptance: tenant, contract and trial
// times; only from verified (ErrConflict otherwise).
ActivateTrialOffer(ctx context.Context, id, tenantID string, acceptedAt, expiresAt time.Time) (*TrialOffer, error)
// MarkTrialOfferMail sets receipt_mail_sent_at ("receipt") or
// activation_mail_sent_at ("activation").
MarkTrialOfferMail(ctx context.Context, id, which string, at time.Time) error
// Projects (0010). Names are unique per tenant, case-insensitively
// (ErrConflict). Deleting a project removes it from its documents.
ListProjects(ctx context.Context, tenantID string) ([]Project, error)
GetProject(ctx context.Context, id string) (*Project, error)
CreateProject(ctx context.Context, p Project) (*Project, error)
UpdateProject(ctx context.Context, p Project) (*Project, error)
DeleteProject(ctx context.Context, id string) error
// Company profile (0021): one per tenant. GetCompanyProfile is
// ErrNotFound when the tenant has none. SaveCompanyProfile writes a new
// revision unless data and schema version are unchanged (changed=false);
// the status stays as it was. SubmitCompanyProfile marks the current
// state submitted as a new revision. Both return a *RevisionConflict
// (matches ErrConflict) when the expected revision is not the stored one.
GetCompanyProfile(ctx context.Context, tenantID string) (*CompanyProfile, error)
SaveCompanyProfile(ctx context.Context, w CompanyProfileWrite) (profile *CompanyProfile, changed bool, err error)
SubmitCompanyProfile(ctx context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error)
// Role and authority dataset (0024): one per tenant, versioned like the
// company profile. GetRoleDataset is ErrNotFound when the tenant has
// none; SaveRoleDataset writes a new revision unless data and catalogue
// version are unchanged (changed=false) and returns a *RevisionConflict
// when the expected revision is not the stored one.
// GetRoleDatasetRevision returns one stored revision (ErrNotFound).
GetRoleDataset(ctx context.Context, tenantID string) (*RoleDataset, error)
SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (dataset *RoleDataset, changed bool, err error)
GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error)
// Product settings (0025): the workspace's own choices per product,
// untouched by the ERP recompute. GetTenantProductSettings is
// ErrNotFound when none were saved; PutTenantProductSettings replaces
// the document (ErrNotFound for an unknown tenant, ErrInvalidInput when
// settings is not a JSON object).
GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error)
PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error)
// Managed services (0012, portal#77), listed by created_at. One row per
// (tenant, kind, url): ErrConflict otherwise.
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
GetManagedService(ctx context.Context, id string) (*ManagedService, error)
CreateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
// UpdateManagedService writes name, url, sku, status, instance_id, notes.
UpdateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
DeleteManagedService(ctx context.Context, id string) error
// Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey
// (false when the key existed). ClaimMail leases due unsent rows.
EnqueueMail(ctx context.Context, m MailItem) (bool, error)
ClaimMail(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]MailItem, error)
CompleteMail(ctx context.Context, id int64, at time.Time) error
FailMail(ctx context.Context, id int64, errMsg string, next time.Time) error
// Lifecycle
Close()
Ping(ctx context.Context) error
}