446 lines
15 KiB
Go
446 lines
15 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/authz"
|
|
"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). limitExtraTargets is sent only by a plan without
|
|
// extra targets (0: Prüfwerk refuses a new target beyond included_targets
|
|
// with 409 target_limit); missing, Prüfwerk allows extras and bills them.
|
|
const (
|
|
limitIncludedTargets = "included_targets"
|
|
limitMonthlyPruefungen = "monthly_pruefungen"
|
|
limitPrueftagCap = "prueftag_cap"
|
|
limitExtraTargets = "extra_targets"
|
|
)
|
|
|
|
// 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. NoPrueftage:
|
|
// the Prüftag cap is always 0, whatever the workspace saved. NoExtraTargets:
|
|
// no target beyond the included ones (extra_targets 0).
|
|
type pruefwerkPlan struct {
|
|
Name string
|
|
SKU string
|
|
IncludedTargets int
|
|
MonthlyPruefungen int
|
|
Unlimited bool
|
|
NoPrueftage bool
|
|
NoExtraTargets bool
|
|
}
|
|
|
|
// capApplies reports whether the workspace's saved Prüftag cap is the one
|
|
// sent: not on Enterprise (no cap) and not on Monitor or the entry plan
|
|
// (always 0).
|
|
func (p pruefwerkPlan) capApplies() bool { return !p.Unlimited && !p.NoPrueftage }
|
|
|
|
// pruefwerkPlans, lowest first: a tenant holding several plan SKUs gets the
|
|
// highest, one without any (trial, preview grant, SCAN-only order) Standard.
|
|
// Monitor and the entry plan sit below them and outside this list, so that
|
|
// no-SKU default stays Standard.
|
|
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},
|
|
}
|
|
|
|
// Monitor (CRA-CSA-CLD-MON, €149 per product per month, paid through
|
|
// Stripe and booked in ERPNext as a subscription): one product watched for
|
|
// new vulnerabilities. One included target, no extra targets, no Prüftage
|
|
// and 10 counted Prüfungen a month (an updated bill of materials, say); the
|
|
// daily re-match of known vulnerabilities runs on every plan. A Monitor
|
|
// order arrives from the ERP like any subscription; any of Standard,
|
|
// Business or Enterprise wins over it, and it wins over the entry plan.
|
|
const monitorPlanSKU = "CRA-CSA-CLD-MON"
|
|
|
|
var pruefwerkMonitorPlan = pruefwerkPlan{Name: "monitor", SKU: monitorPlanSKU, IncludedTargets: 1, MonthlyPruefungen: 10,
|
|
NoPrueftage: true, NoExtraTargets: true}
|
|
|
|
// Entry offers (CRA-Check, SBOM-Erstellung, CVE-Scan; LB Einstiegsangebote):
|
|
// one-off orders paid by card or SEPA at booking, delivered by Breakpilot in
|
|
// the customer's workspace, which stays open 90 days after delivery. Staff
|
|
// grant the plan with POST /v1/admin/tenants/{id}/entry-offer; it is not a
|
|
// subscription and never comes from the ERP.
|
|
//
|
|
// The plan has no monthly quota, no Prüftage and no extra targets, so
|
|
// nothing beyond the order can be used or billed: the scans staff start for the delivery are
|
|
// support scans, which never count; change-driven scans of the included
|
|
// targets do not count either. The included targets are the order's
|
|
// (entryTargetsMax at most), set per grant in config["included_targets"].
|
|
const (
|
|
entryPlanSKU = "CRA-CSA-CLD-EIN"
|
|
entrySource = "entry"
|
|
entryTargetsMax = 10
|
|
entryTargetsKey = "included_targets"
|
|
entryOrderRefKey = "order_ref"
|
|
// An entry offer to a Monitor subscriber adds its targets to the
|
|
// subscription's grant until entry_until (pruefwerkEntryAddOn).
|
|
entryAddOnTargetsKey = "entry_targets"
|
|
entryAddOnUntilKey = "entry_until"
|
|
entryMaxDuration = 200 * 24 * time.Hour
|
|
)
|
|
|
|
// pruefwerkEntryPlan is the entry plan with one included target; the grant's
|
|
// config sets the order's number (pruefwerkPlanOfConfig).
|
|
var pruefwerkEntryPlan = pruefwerkPlan{Name: "einstieg", SKU: entryPlanSKU, IncludedTargets: 1, MonthlyPruefungen: 0, NoPrueftage: true, NoExtraTargets: true}
|
|
|
|
// pruefwerkPlanFor resolves the plan from tenant_products.config["skus"]:
|
|
// []string as recomputeEntitlements writes it, []interface{} once it has
|
|
// been through JSONB. Standard, Business and Enterprise win over Monitor,
|
|
// and any subscription plan over the entry plan; no plan SKU at all (trial,
|
|
// preview grant, SCAN-only order) is Standard.
|
|
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, monitor, entry := -1, false, false
|
|
for _, sku := range list {
|
|
switch sku {
|
|
case monitorPlanSKU:
|
|
monitor = true
|
|
case entryPlanSKU:
|
|
entry = true
|
|
}
|
|
for i, p := range pruefwerkPlans {
|
|
if p.SKU == sku && i > best {
|
|
best = i
|
|
}
|
|
}
|
|
}
|
|
switch {
|
|
case best >= 0:
|
|
return pruefwerkPlans[best]
|
|
case monitor:
|
|
return pruefwerkMonitorPlan
|
|
case entry:
|
|
return pruefwerkEntryPlan
|
|
}
|
|
return pruefwerkStandard()
|
|
}
|
|
|
|
// pruefwerkStandard is the plan without any plan SKU (the first of
|
|
// pruefwerkPlans; Monitor and the entry plan are kept out of the list).
|
|
func pruefwerkStandard() pruefwerkPlan { return pruefwerkPlans[0] }
|
|
|
|
// pruefwerkPlanOfConfig is the plan of a stored Prüfwerk entitlement: by
|
|
// its SKUs, and on the entry plan with the order's included targets
|
|
// (1..entryTargetsMax; anything else is 1).
|
|
func pruefwerkPlanOfConfig(cfg map[string]interface{}) pruefwerkPlan {
|
|
plan := pruefwerkPlanFor(cfg["skus"])
|
|
if plan.Name == pruefwerkEntryPlan.Name {
|
|
if n, ok := entryTargets(cfg[entryTargetsKey]); ok {
|
|
plan.IncludedTargets = n
|
|
}
|
|
}
|
|
return plan
|
|
}
|
|
|
|
// entryTargets reads an included-targets value as Go or JSONB gives it.
|
|
func entryTargets(v interface{}) (int, bool) {
|
|
var n int
|
|
switch x := v.(type) {
|
|
case int:
|
|
n = x
|
|
case float64:
|
|
if x != float64(int(x)) {
|
|
return 0, false
|
|
}
|
|
n = int(x)
|
|
case json.Number:
|
|
i, err := x.Int64()
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
n = int(i)
|
|
default:
|
|
return 0, false
|
|
}
|
|
return n, n >= 1 && n <= entryTargetsMax
|
|
}
|
|
|
|
// pruefwerkEntryAddOn is the number of targets a running entry offer adds to
|
|
// a Monitor grant at now: entry_targets (1..entryTargetsMax) while
|
|
// entry_until is ahead, else 0.
|
|
func pruefwerkEntryAddOn(cfg map[string]interface{}, now time.Time) int {
|
|
n, ok := entryTargets(cfg[entryAddOnTargetsKey])
|
|
if !ok {
|
|
return 0
|
|
}
|
|
s, _ := cfg[entryAddOnUntilKey].(string)
|
|
until, err := time.Parse(time.RFC3339, s)
|
|
if err != nil || !until.After(now) {
|
|
return 0
|
|
}
|
|
return n
|
|
}
|
|
|
|
// 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. On
|
|
// Monitor, a running entry offer adds its targets (pruefwerkEntryAddOn).
|
|
func pruefwerkLimits(cfg map[string]interface{}, prueftagCap *int, now time.Time) map[string]interface{} {
|
|
out := make(map[string]interface{}, len(cfg)+3)
|
|
for k, v := range cfg {
|
|
out[k] = v
|
|
}
|
|
plan := pruefwerkPlanOfConfig(cfg)
|
|
// The plan decides, not a key left in the grant's config.
|
|
delete(out, limitExtraTargets)
|
|
if plan.Unlimited {
|
|
out[limitIncludedTargets], out[limitMonthlyPruefungen], out[limitPrueftagCap] = nil, nil, nil
|
|
return out
|
|
}
|
|
out[limitIncludedTargets] = plan.IncludedTargets
|
|
if plan.Name == pruefwerkMonitorPlan.Name {
|
|
out[limitIncludedTargets] = plan.IncludedTargets + pruefwerkEntryAddOn(cfg, now)
|
|
}
|
|
out[limitMonthlyPruefungen] = plan.MonthlyPruefungen
|
|
if plan.NoExtraTargets {
|
|
out[limitExtraTargets] = 0
|
|
}
|
|
if plan.NoPrueftage {
|
|
out[limitPrueftagCap] = 0
|
|
} else {
|
|
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 pruefwerkPlanOfConfig(tp.Config), nil
|
|
}
|
|
}
|
|
return pruefwerkStandard(), nil
|
|
}
|
|
|
|
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 and on the entry plan, where a saved cap is kept but not
|
|
// applied (Enterprise sends none, the entry plan always 0).
|
|
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.capApplies(),
|
|
}
|
|
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() && !authz.AnyGrants(p.OrgRoles, capPruefwerkSettings) {
|
|
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "Prüfwerk settings require the registry:pruefwerk.settings right")
|
|
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.capApplies(),
|
|
},
|
|
})
|
|
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
|
|
}
|