Files
tenant-registry/internal/server/entitlements.go
T
Sharang ParnerkarandClaude Opus 5.5 3f5319ea9b
ci / shared (pull_request) Successful in 15s
ci / test (pull_request) Successful in 26m38s
ci / image (pull_request) Skipped
feat(entitlements): Prüfwerk plan limits and Prüftag cap setting (t72)
The entitlement check now always sends included_targets,
monthly_pruefungen and prueftag_cap for Prüfwerk, from one plan table
(Standard 5/100, Business 25/500, Enterprise null) resolved from the
CRA-CSA-CLD-STD/-BUS/-ENT SKUs, highest wins; no plan SKU counts as
Standard. The limits are a copy: the stored config is left as it is.

The workspace's monthly Prüftag cap lives in the new
tenant_product_settings table (0025), so recomputeEntitlements cannot
reset it. GET/PUT /v1/tenants/{id}/products/pruefwerk/settings takes
{"prueftag_cap": 0..10000 | null}; user tokens need IT_ADMIN, OWNER or
FINANCE, service clients their route group. A change is audited
(product_settings.changed, old/new). On Enterprise the cap is stored but
the check sends null.

prueftag.booked and target.extra go through POST /v1/usage/events as
they are; a test pins the dedup by idempotency key. No invoicing yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:58:06 +01:00

183 lines
5.2 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
type entitlementCheckReq struct {
TenantID string `json:"tenant_id"`
Product string `json:"product"`
Addon string `json:"addon,omitempty"`
// UserID (optional): the Keycloak user acting. A member blocked in the
// tenant is not allowed (portal#74), whatever the tenant is entitled to.
UserID string `json:"user_id,omitempty"`
}
// EntitlementCheck is the answer products cache for ≤ 60 s
// (PRODUCT_INTEGRATION_SPEC 2.0 §4.4). ReadOnly mirrors the ladder: warning
// keeps full access, restricted/halted/frozen block writes.
type EntitlementCheck struct {
Allowed bool `json:"allowed"`
ReadOnly bool `json:"read_only"`
Status string `json:"status,omitempty"`
Limits map[string]interface{} `json:"limits,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Reason string `json:"reason,omitempty"`
// Preview: allowed through a staff preview grant (product not for sale
// yet). Products may show it; usage under it is not invoiced.
Preview bool `json:"preview,omitempty"`
}
// checkEntitlement is POST /v1/internal/entitlements/check.
func (s *Server) checkEntitlement(w http.ResponseWriter, r *http.Request) {
var in entitlementCheckReq
if !decodeJSON(w, r, &in) {
return
}
if in.TenantID == "" || in.Product == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
res, err := s.evaluateEntitlement(ctx, in)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if in.UserID != "" && res.Allowed {
blocked, berr := s.memberBlocked(ctx, in.UserID, in.TenantID)
switch {
case errors.Is(berr, keycloak.ErrUserNotFound):
res = EntitlementCheck{Status: res.Status, Reason: "user_unknown"}
case berr != nil:
s.Log.Warn("member block check failed; allowing", "user_id", in.UserID, "tenant_id", in.TenantID, "err", berr)
case blocked:
res = EntitlementCheck{Status: res.Status, Reason: "member_blocked"}
}
}
writeJSON(w, http.StatusOK, res)
}
func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq) (EntitlementCheck, error) {
// Disabled products (not for sale yet) are reachable only through a
// staff preview grant, checked below.
prod, err := s.Store.GetProduct(ctx, in.Product)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return EntitlementCheck{Allowed: false, Reason: "unknown_product"}, nil
}
return EntitlementCheck{}, err
}
if in.Addon != "" && !prod.HasAddon(in.Addon) {
return EntitlementCheck{Allowed: false, Reason: "unknown_addon"}, nil
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return EntitlementCheck{Allowed: false, Reason: "tenant_not_found"}, nil
}
return EntitlementCheck{}, err
}
out := EntitlementCheck{Status: t.Status}
switch t.Status {
case store.StatusArchived:
out.Reason = "tenant_archived"
return out, nil
case store.StatusHalted:
out.Reason = "tenant_halted"
return out, nil
case store.StatusRestricted, store.StatusFrozen:
out.ReadOnly = true
}
tps, err := s.Store.ListTenantProducts(ctx, t.ID)
if err != nil {
return EntitlementCheck{}, err
}
now := time.Now().UTC()
for _, tp := range tps {
if tp.Product != prod.Key {
continue
}
if tp.Preview {
if !tp.PreviewActive(now) {
out.Reason = "preview_expired"
out.ExpiresAt = tp.PreviewExpiresAt
return out, nil
}
out.Preview = true
} else if !prod.Enabled {
break // a leftover row of a product not for sale: unknown_product
}
if !tp.Enabled {
out.Reason = "entitlement_disabled"
return out, nil
}
if tp.ExpiresAt != nil && tp.ExpiresAt.Before(now) {
out.Reason = "entitlement_expired"
out.ExpiresAt = tp.ExpiresAt
return out, nil
}
if in.Addon != "" {
key := addonLimitKey(prod, in.Addon)
if v, ok := tp.Config[key]; !ok || toFloat(v) <= 0 {
out.Reason = "addon_not_purchased"
return out, nil
}
}
out.Allowed = true
out.Limits = tp.Config
if prod.Key == pruefwerkProduct {
// Plan limits and the workspace's Prüftag cap, always sent (null:
// unlimited / no cap), on a copy of the stored config.
set, _, err := s.loadPruefwerkSettings(ctx, t.ID)
if err != nil {
return EntitlementCheck{}, err
}
out.Limits = pruefwerkLimits(tp.Config, set.PrueftagCap)
}
out.ExpiresAt = tp.ExpiresAt
return out, nil
}
if !prod.Enabled {
out.Reason = "unknown_product"
return out, nil
}
out.Reason = "not_entitled"
return out, nil
}
func addonLimitKey(p *store.Product, addon string) string {
for _, a := range p.Addons {
if a.ID == addon {
if a.LimitKey != "" {
return a.LimitKey
}
return addon
}
}
return addon
}
func toFloat(v interface{}) float64 {
switch n := v.(type) {
case float64:
return n
case int:
return float64(n)
case int64:
return float64(n)
case bool:
if n {
return 1
}
}
return 0
}