feat(m-mig-5): products table, entitlement check, tenant ladder, per-client authz
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Failing after 14m36s
ci / image (pull_request) Skipped

Registry becomes the entitlement authority (ERP/02, PRODUCT_INTEGRATION_SPEC 2.0):

- migrations 0002/0003: ladder statuses warning|restricted|halted on
  tenant_status; products table replaces the hard-coded catalog, seeded with
  pruefwerk (+ werkbank add-on), werkpilot, firmwerk; compliance disabled
  until the dsms migration (M-MIG-9)
- GET /v1/tenants (keyset pagination, status/kind filters) for product
  schedulers and reconcile jobs
- POST /v1/internal/entitlements/check → {allowed, read_only, status, limits,
  expires_at, reason}; add-on limits from tenant_products.config
- POST /v1/tenants/{id}/status — the single ladder transition endpoint;
  cancel now moves to halted; activate accepts products[] with limits and
  provisions them via the catalog's per-env provision_urls
- SyncTenantStatus: coarse tenant_status attribute on every Keycloak org
  member after every status change (attributes merged, roles untouched)
- AUTHZ_RULES: per-client (JWT azp) route groups; 403 FORBIDDEN_CLIENT
- INVITE_CLIENT_ID / INVITE_REDIRECT_URI replace the hard-coded dev-portal
  invite parameters
- catalog entries carry type, launch_url (per APP_ENV), skus, addons,
  trial_days; openapi.yaml + README updated

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
Sharang ParnerkarandClaude Fable 5.1 committed 2026-09-11 16:29:44 +02:00
1 parent 6b82c14573
commit 62335a9be3
31 files changed
+1476 -97

No files matched your search

+7 -1
View File
@@ -44,6 +44,9 @@ Env vars (override at the shell):
| `KEYCLOAK_REALM` | `breakpilot-dev` | Realm name for Admin API calls |
| `KEYCLOAK_CLIENT_ID` | empty | Service-account client id (Admin) |
| `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret |
| `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route |
| `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` |
| `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) |
## Endpoints
@@ -53,11 +56,14 @@ Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary:
|---|---|---|
| GET | `/healthz` | Liveness |
| GET | `/readyz` | Pings the store |
| GET | `/v1/tenants` | List tenants (service-only, keyset paginated) |
| POST | `/v1/tenants` | Create a tenant |
| GET | `/v1/tenants/{id}` | Read by id |
| GET | `/v1/tenants/by-slug/{slug}` | Read by slug (portal middleware uses this) |
| POST | `/v1/tenants/{id}/activate` | trial → active |
| POST | `/v1/tenants/{id}/cancel` | active → frozen |
| POST | `/v1/tenants/{id}/status` | Ladder transition (active/warning/restricted/halted/archived), syncs Keycloak |
| POST | `/v1/tenants/{id}/cancel` | active → halted |
| POST | `/v1/internal/entitlements/check` | Authoritative entitlement answer for products (cache ≤ 60 s) |
| GET | `/v1/entitlements?tenant_id={id}` | List product entitlements |
| GET | `/v1/catalog` | List requestable products |
| POST | `/v1/catalog/request` | Customer requests a product (sales follow-up) |
+7 -1
View File
@@ -53,6 +53,9 @@ func main() {
ClientID: cfg.KeycloakClientID,
ClientSecret: cfg.KeycloakClientSecret,
Timeout: cfg.KeycloakTimeout,
InviteClientID: cfg.InviteClientID,
InviteRedirectURI: cfg.InviteRedirectURI,
})
slog.Info("keycloak adapter configured",
"url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID)
@@ -87,7 +90,10 @@ func main() {
slog.Warn("PRODUCT_API_URL not set — product tenant provisioning disabled (anchors may diverge)")
}
handler := server.NewRouter(&server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Product: pv})
authz := server.ParseAuthzRules(cfg.AuthzRules)
server.LogAuthz(logger, authz)
handler := server.NewRouter(&server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv})
srv := &http.Server{
Addr: cfg.Addr,
Handler: handler,
+12
View File
@@ -34,6 +34,14 @@ type Config struct {
ProductAPIURL string
ProductAPIPath string
ProductTimeout time.Duration
// Invite e-mail (execute-actions) client + redirect; per environment.
InviteClientID string
InviteRedirectURI string
// Per-client authorization rules (see server.ParseAuthzRules). Empty ⇒
// every authenticated client may call every route (dev only).
AuthzRules string
}
func Load() (*Config, error) {
@@ -60,6 +68,10 @@ func Load() (*Config, error) {
ProductAPIURL: os.Getenv("PRODUCT_API_URL"),
ProductAPIPath: getenv("PRODUCT_API_TENANTS_PATH", "/sdk/v1/tenants"),
ProductTimeout: 10 * time.Second,
InviteClientID: getenv("INVITE_CLIENT_ID", "dev-portal"),
InviteRedirectURI: getenv("INVITE_REDIRECT_URI", "https://breakpilot.com/onboard"),
AuthzRules: os.Getenv("AUTHZ_RULES"),
}, nil
}
+5
View File
@@ -83,6 +83,11 @@ type Adapter interface {
// Returns ErrUserNotFound for an unknown user id.
Memberships(ctx context.Context, userID string) ([]Claims, error)
// SyncTenantStatus writes the coarse tenant_status attribute on every
// member of the organization whose alias is slug (ERP/02: Keycloak
// carries only the coarse flag; entitlements stay in the registry).
SyncTenantStatus(ctx context.Context, slug, status string) error
// Health pings the admin endpoint. Used by readyz and the cluster cold-
// start sequence (INFRASTRUCTURE.md §10 scenario F).
Health(ctx context.Context) error
+12
View File
@@ -35,12 +35,24 @@ type HTTPConfig struct {
ClientSecret string // service account client secret
AdminEmail string // platform admin email — used to gate the BREAKPILOT_ADMIN realm role check
Timeout time.Duration
// Invite mail: which client + redirect the execute-actions email uses.
// Defaults keep the dev realm working; stage/prod set portal-{env} and
// the portal's public URL.
InviteClientID string
InviteRedirectURI string
}
func NewHTTPAdapter(cfg HTTPConfig) *HTTPAdapter {
if cfg.Timeout == 0 {
cfg.Timeout = 10 * time.Second
}
if cfg.InviteClientID == "" {
cfg.InviteClientID = "dev-portal"
}
if cfg.InviteRedirectURI == "" {
cfg.InviteRedirectURI = "https://breakpilot.com/onboard"
}
return &HTTPAdapter{cfg: cfg, hc: &http.Client{Timeout: cfg.Timeout}}
}
+14
View File
@@ -14,6 +14,7 @@ type Mock struct {
Orgs map[string]string // tenantID → orgID
Users map[string]string // email → userID
Claims map[string]Claims // userID → last synced
Status map[string]string // tenant slug → last synced tenant_status
FailNext error // set to force the next call to fail
}
@@ -22,9 +23,22 @@ func NewMock() *Mock {
Orgs: map[string]string{},
Users: map[string]string{},
Claims: map[string]Claims{},
Status: map[string]string{},
}
}
func (m *Mock) SyncTenantStatus(_ context.Context, slug, status string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.FailNext != nil {
err := m.FailNext
m.FailNext = nil
return err
}
m.Status[slug] = status
return nil
}
func (m *Mock) Health(_ context.Context) error { return nil }
func (m *Mock) CreateOrgAndInvite(_ context.Context, in InviteInput) (*InviteResult, error) {
+60 -2
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
)
@@ -154,7 +155,7 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (*
// the caller so they can hit it directly.
inviteURL, err := a.executeActionsEmail(ctx, userID,
[]string{"VERIFY_EMAIL", "UPDATE_PASSWORD"},
"https://breakpilot.com/onboard")
a.cfg.InviteRedirectURI)
if err != nil {
// Non-fatal — admin can resend from the KC UI.
return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: ""}, nil
@@ -238,7 +239,7 @@ func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string
func (a *HTTPAdapter) executeActionsEmail(ctx context.Context, userID string, actions []string, redirectURI string) (string, error) {
resp, err := a.adminCall(ctx, http.MethodPut,
fmt.Sprintf("/users/%s/execute-actions-email?client_id=dev-portal&redirect_uri=%s", userID, redirectURI),
fmt.Sprintf("/users/%s/execute-actions-email?client_id=%s&redirect_uri=%s", userID, url.QueryEscape(a.cfg.InviteClientID), url.QueryEscape(redirectURI)),
actions, nil)
if err != nil {
return "", err
@@ -271,3 +272,60 @@ func splitName(full string) (first, last string) {
}
return parts[0], strings.Join(parts[1:], " ")
}
// SyncTenantStatus finds the organization by alias, lists its members and
// rewrites only the tenant_status attribute on each (attributes are merged,
// never replaced wholesale). Other member attributes and org_roles are left
// untouched — roles stay Keycloak-owned.
func (a *HTTPAdapter) SyncTenantStatus(ctx context.Context, slug, status string) error {
orgID, err := a.findOrgByAlias(ctx, slug)
if err != nil {
return fmt.Errorf("sync status: %w", err)
}
var members []struct {
ID string `json:"id"`
}
resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/organizations/%s/members?max=500", orgID), nil, &members)
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
_ = resp.Body.Close()
return fmt.Errorf("sync status: list members %d", resp.StatusCode)
}
var firstErr error
for _, m := range members {
var u userRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u)
if err != nil || resp.StatusCode/100 != 2 {
if err == nil {
_ = resp.Body.Close()
err = fmt.Errorf("get user %s: %d", m.ID, resp.StatusCode)
}
if firstErr == nil {
firstErr = err
}
continue
}
attrs := u.Attributes
if attrs == nil {
attrs = map[string][]string{}
}
attrs["tenant_status"] = []string{status}
resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+m.ID, map[string]any{"attributes": attrs}, nil)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
if resp.StatusCode/100 != 2 {
body, _ := io.ReadAll(resp.Body)
if firstErr == nil {
firstErr = fmt.Errorf("update user %s: %d %s", m.ID, resp.StatusCode, body)
}
}
_ = resp.Body.Close()
}
return firstErr
}
+33
View File
@@ -104,3 +104,36 @@ func (p *HTTPProvisioner) ProvisionTenant(ctx context.Context, t Tenant) error {
return fmt.Errorf("%w: %d %s", ErrUnavailable, resp.StatusCode, b)
}
}
// ProvisionAt POSTs payload to an absolute URL (a product's per-environment
// provisioning endpoint from the catalog). 2xx and 409 are success.
func ProvisionAt(ctx context.Context, url string, payload any, auth AuthHeaderFunc, timeout time.Duration) error {
body, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if auth != nil {
h, aerr := auth(ctx)
if aerr != nil {
return fmt.Errorf("%w: %v", ErrUnavailable, aerr)
}
if h != "" {
req.Header.Set("Authorization", h)
}
}
resp, err := (&http.Client{Timeout: timeout}).Do(req)
if err != nil {
return fmt.Errorf("%w: %v", ErrUnavailable, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusConflict || resp.StatusCode/100 == 2 {
return nil
}
b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("%w: %d %s", ErrUnavailable, resp.StatusCode, b)
}
+3 -4
View File
@@ -56,14 +56,13 @@ func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid_name", "name too long")
return
}
if in.Product != "" && !isKnownProduct(in.Product) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if in.Product != "" && !s.knownProduct(ctx, in.Product) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
plain, err := generateAPIKey()
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "key generation failed")
+3 -3
View File
@@ -10,7 +10,7 @@ import (
func TestCreateAPIKey_then_verify(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
resp, body := h.do("POST", "/v1/api-keys", map[string]any{
"tenant_id": h.tenant.ID, "name": "ci-bot", "product": "certifai",
"tenant_id": h.tenant.ID, "name": "ci-bot", "product": "pruefwerk",
"scopes": []string{"certifai:read", "certifai:write"},
})
if resp.StatusCode != http.StatusCreated {
@@ -23,7 +23,7 @@ func TestCreateAPIKey_then_verify(t *testing.T) {
if len(created.Plaintext) < 30 || created.Plaintext[:3] != "bp_" {
t.Fatalf("bad plaintext: %q", created.Plaintext)
}
if len(created.APIKey.Scopes) != 2 || created.APIKey.Product != "certifai" {
if len(created.APIKey.Scopes) != 2 || created.APIKey.Product != "pruefwerk" {
t.Errorf("unexpected key: %+v", created.APIKey)
}
@@ -40,7 +40,7 @@ func TestCreateAPIKey_then_verify(t *testing.T) {
Product string `json:"product"`
Scopes []string `json:"scopes"`
}](t, body)
if !v.Valid || v.TenantID != h.tenant.ID || v.Product != "certifai" || len(v.Scopes) != 2 {
if !v.Valid || v.TenantID != h.tenant.ID || v.Product != "pruefwerk" || len(v.Scopes) != 2 {
t.Errorf("verify returned %+v", v)
}
+139
View File
@@ -0,0 +1,139 @@
package server
import (
"log/slog"
"net/http"
"strings"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
)
// Per-client authorization (PLATFORM_ARCHITECTURE §5c): each Keycloak service
// client (JWT azp) may only call the route groups it is mapped to.
//
// AUTHZ_RULES = "portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write;erp-svc:erp"
// A group of "*" allows everything. With AUTHZ_RULES unset every
// authenticated client may call every route (dev; logged at startup).
type Authz struct {
rules map[string]map[string]bool // azp → group → allowed
}
// ParseAuthzRules parses the AUTHZ_RULES syntax. Empty ⇒ nil (allow all).
func ParseAuthzRules(raw string) *Authz {
raw = strings.TrimSpace(raw)
if raw == "" {
return nil
}
a := &Authz{rules: map[string]map[string]bool{}}
for _, entry := range strings.Split(raw, ";") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
azp, groups, ok := strings.Cut(entry, ":")
if !ok {
continue
}
set := map[string]bool{}
for _, g := range strings.Split(groups, ",") {
if g = strings.TrimSpace(g); g != "" {
set[g] = true
}
}
a.rules[strings.TrimSpace(azp)] = set
}
return a
}
// Allowed reports whether client azp may call the given route group. A group
// "x.read" is also satisfied by the wider "x" grant.
func (a *Authz) Allowed(azp, group string) bool {
if a == nil {
return true
}
set, ok := a.rules[azp]
if !ok {
return false
}
if set["*"] || set[group] {
return true
}
if base, _, hasSub := strings.Cut(group, "."); hasSub && set[base] {
return true
}
return false
}
// routeGroup classifies a request. Keep in sync with NewRouter.
func routeGroup(method, path string) string {
switch {
case strings.HasPrefix(path, "/v1/internal/entitlements/"):
return "entitlements"
case strings.HasPrefix(path, "/v1/internal/api-keys/verify"):
return "api-keys.verify"
case strings.HasPrefix(path, "/v1/internal/keycloak/"):
return "keycloak"
case strings.HasPrefix(path, "/v1/internal/erp/"):
return "erp"
case strings.HasPrefix(path, "/v1/entitlements"):
return "entitlements"
case strings.HasPrefix(path, "/v1/catalog"):
return "catalog"
case strings.HasPrefix(path, "/v1/api-keys"):
return "api-keys"
case strings.HasPrefix(path, "/v1/audit"):
if method == http.MethodGet {
return "audit.read"
}
return "audit.write"
case strings.HasPrefix(path, "/v1/users/"):
return "users"
case strings.HasPrefix(path, "/v1/usage"):
return "usage"
case strings.HasPrefix(path, "/v1/licences"):
return "licences"
case strings.HasPrefix(path, "/v1/tenants"):
if method == http.MethodGet {
return "tenants.read"
}
return "tenants.write"
}
return "other"
}
// requireAuthz sits behind requireAuth. Without a principal (AUTH_ENABLED=false)
// or without rules it passes through.
func (s *Server) requireAuthz(next http.Handler) http.Handler {
if s.Authz == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, ok := authn.PrincipalFrom(r.Context())
if !ok {
next.ServeHTTP(w, r) // auth disabled: nothing to authorize against
return
}
group := routeGroup(r.Method, r.URL.Path)
if !s.Authz.Allowed(p.ClientID, group) {
s.Log.Warn("client not authorized for route group", "azp", p.ClientID, "group", group, "path", r.URL.Path)
writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not call "+group)
return
}
next.ServeHTTP(w, r)
})
}
// LogAuthz emits the startup line so an open registry is never silent.
func LogAuthz(log *slog.Logger, a *Authz) {
if a == nil {
log.Warn("AUTHZ_RULES not set — every authenticated client may call every route (dev only)")
return
}
for azp, groups := range a.rules {
keys := make([]string, 0, len(groups))
for g := range groups {
keys = append(keys, g)
}
log.Info("authz rule", "azp", azp, "groups", keys)
}
}
+32
View File
@@ -0,0 +1,32 @@
package server
import "testing"
func TestAuthzRules(t *testing.T) {
a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write; root:* ;broken")
cases := []struct {
azp, method, path string
want bool
}{
{"portal-svc", "POST", "/v1/tenants", true},
{"portal-svc", "GET", "/v1/tenants/by-slug/acme", true},
{"portal-svc", "POST", "/v1/internal/entitlements/check", false},
{"pruefwerk-svc", "POST", "/v1/internal/entitlements/check", true},
{"pruefwerk-svc", "GET", "/v1/tenants", true},
{"pruefwerk-svc", "POST", "/v1/tenants", false},
{"pruefwerk-svc", "POST", "/v1/internal/api-keys/verify", true},
{"pruefwerk-svc", "POST", "/v1/api-keys", false},
{"pruefwerk-svc", "POST", "/v1/audit", true},
{"pruefwerk-svc", "GET", "/v1/audit", false},
{"root", "DELETE", "/v1/api-keys/x", true},
{"unknown", "GET", "/v1/catalog", false},
}
for _, c := range cases {
if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want {
t.Errorf("%s %s %s: got %v want %v", c.azp, c.method, c.path, got, c.want)
}
}
if ParseAuthzRules("") != nil || !(*Authz)(nil).Allowed("anyone", "tenants.write") {
t.Errorf("empty rules must allow everything")
}
}
+66 -57
View File
@@ -2,32 +2,56 @@ package server
import (
"context"
"errors"
"net/http"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// catalog is hard-coded for now. PRODUCT_INTEGRATION_SPEC.md §10 has products
// publish a manifest to `cdn.breakpilot.com`; this list will be sourced
// from those manifests once M6.3 / M7.2 wire it up.
var catalog = []store.CatalogEntry{
{
Key: "certifai", Name: "CERTifAI",
Description: "Self-hosted GDPR-compliant AI dashboard.",
PlansRequired: []string{"professional", "enterprise"},
SupportsTrial: true,
},
{
Key: "compliance", Name: "Compliance",
Description: "DSFA / TOM / VVT generation; evidence capture.",
PlansRequired: []string{"starter", "professional", "enterprise"},
SupportsTrial: true,
},
// The catalog lives in the products table (migration 0003) since M-MIG-5.
// Launch URLs are resolved for this registry's environment (APP_ENV) so the
// portal can link straight to the product host.
func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
products, err := s.Store.ListProducts(ctx, false)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
items := make([]store.CatalogEntry, 0, len(products))
for _, p := range products {
items = append(items, p.Catalog(s.env()))
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
func (s *Server) getCatalog(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"items": catalog})
// env is the environment key used for per-env product URLs. "dev" reads the
// stage URLs so a laptop portal links somewhere real.
func (s *Server) env() string {
if s.Cfg == nil || s.Cfg.Env == "" || s.Cfg.Env == "dev" {
return "stage"
}
return s.Cfg.Env
}
// product returns an enabled catalog product or ErrNotFound.
func (s *Server) product(ctx context.Context, key string) (*store.Product, error) {
p, err := s.Store.GetProduct(ctx, key)
if err != nil {
return nil, err
}
if !p.Enabled {
return nil, store.ErrNotFound
}
return p, nil
}
func (s *Server) knownProduct(ctx context.Context, key string) bool {
_, err := s.product(ctx, key)
return err == nil
}
type catalogRequestReq struct {
@@ -35,9 +59,8 @@ type catalogRequestReq struct {
Product string `json:"product"`
}
// catalogRequest — customer requests a non-subscribed product. Today this
// just emits an audit event tagged so the eventual ERPNext-Lead step
// (M11.1) can pick it up.
// catalogRequest — customer requests a non-subscribed product. Emits an
// audit event; the ERP outbox (M-MIG-7) turns it into a CRM Lead.
func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
var in catalogRequestReq
if !decodeJSON(w, r, &in) {
@@ -47,14 +70,12 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
return
}
if !isKnownProduct(in.Product) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if !s.knownProduct(ctx, in.Product) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if _, err := s.Store.GetTenant(ctx, in.TenantID); err != nil {
if mapStoreError(w, err) {
return
@@ -62,22 +83,19 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: in.TenantID, Action: "catalog.requested",
TargetID: in.Product, TargetType: "product",
Metadata: map[string]interface{}{"product": in.Product},
})
writeJSON(w, http.StatusAccepted, map[string]string{
"status": "accepted",
"message": "request recorded; sales will be in touch",
})
}
// catalogTrialRequest — customer self-serves a 14-day trial of a product
// that supports trial. Provisions the entitlement immediately so the
// product can be used right away.
// catalogTrialRequest — self-serve trial of a product that supports it.
// Provisions the entitlement immediately (trial_days from the catalog).
func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
var in catalogRequestReq
if !decodeJSON(w, r, &in) {
@@ -87,28 +105,34 @@ func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
return
}
entry, ok := lookupCatalogEntry(in.Product)
if !ok {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
entry, err := s.product(ctx, in.Product)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if !entry.SupportsTrial {
writeError(w, http.StatusBadRequest, "trial_unavailable", "product does not support self-serve trial")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if _, err := s.Store.GetTenant(ctx, in.TenantID); err != nil {
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
expiresAt := time.Now().UTC().Add(14 * 24 * time.Hour)
days := entry.TrialDays
if days <= 0 {
days = 14
}
expiresAt := time.Now().UTC().Add(time.Duration(days) * 24 * time.Hour)
tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
TenantID: in.TenantID, Product: in.Product, Enabled: true,
Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &expiresAt,
@@ -120,26 +144,11 @@ func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: in.TenantID, Action: "catalog.trial_started",
TargetID: in.Product, TargetType: "product",
Metadata: map[string]interface{}{"product": in.Product, "expires_at": expiresAt.Format(time.RFC3339)},
})
s.provisionProduct(ctx, r, t, entry, tp)
writeJSON(w, http.StatusCreated, tp)
}
func isKnownProduct(key string) bool {
_, ok := lookupCatalogEntry(key)
return ok
}
func lookupCatalogEntry(key string) (store.CatalogEntry, bool) {
for _, e := range catalog {
if e.Key == key {
return e, true
}
}
return store.CatalogEntry{}, false
}
+4 -4
View File
@@ -25,7 +25,7 @@ func TestGetCatalog(t *testing.T) {
func TestCatalogRequest(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
resp, body := h.do("POST", "/v1/catalog/request", map[string]any{
"tenant_id": h.tenant.ID, "product": "certifai",
"tenant_id": h.tenant.ID, "product": "pruefwerk",
})
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d, body=%s", resp.StatusCode, body)
@@ -56,13 +56,13 @@ func TestCatalogTrialRequest(t *testing.T) {
fresh := freshWrap.Tenant
resp, body := h.do("POST", "/v1/catalog/trial-request", map[string]any{
"tenant_id": fresh.ID, "product": "compliance",
"tenant_id": fresh.ID, "product": "firmwerk",
})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("status = %d, body=%s", resp.StatusCode, body)
}
got := decode[store.TenantProduct](t, body)
if got.Product != "compliance" || !got.Enabled || got.ExpiresAt == nil {
if got.Product != "firmwerk" || !got.Enabled || got.ExpiresAt == nil {
t.Errorf("unexpected: %+v", got)
}
@@ -74,7 +74,7 @@ func TestCatalogTrialRequest(t *testing.T) {
listed := decode[struct {
Items []store.TenantProduct `json:"items"`
}](t, body)
if len(listed.Items) != 1 || listed.Items[0].Product != "compliance" {
if len(listed.Items) != 1 || listed.Items[0].Product != "firmwerk" {
t.Errorf("list returned %+v", listed.Items)
}
})
+139
View File
@@ -0,0 +1,139 @@
package server
import (
"context"
"errors"
"net/http"
"time"
"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"`
}
// 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"`
}
// 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
}
writeJSON(w, http.StatusOK, res)
}
func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq) (EntitlementCheck, error) {
prod, err := s.product(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.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
out.ExpiresAt = tp.ExpiresAt
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
}
+183
View File
@@ -0,0 +1,183 @@
package server_test
import (
"net/http"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/server"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func check(t *testing.T, h *testHarness, body map[string]any) server.EntitlementCheck {
t.Helper()
resp, raw := h.do("POST", "/v1/internal/entitlements/check", body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d body=%s", resp.StatusCode, raw)
}
return decode[server.EntitlementCheck](t, raw)
}
func TestEntitlementCheck_ladder(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
// fresh tenant, trial of pruefwerk
_, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": "ent-co", "name": "Ent Co"})
tn := decode[struct {
Tenant *store.Tenant `json:"tenant"`
}](t, raw).Tenant
got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if got.Allowed || got.Reason != "not_entitled" {
t.Fatalf("before trial: %+v", got)
}
if resp, _ := h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); resp.StatusCode != 201 {
t.Fatalf("trial: %d", resp.StatusCode)
}
got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if !got.Allowed || got.ReadOnly || got.Status != "trial" || got.ExpiresAt == nil {
t.Fatalf("trial: %+v", got)
}
// add-on not purchased
got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk", "addon": "werkbank"})
if got.Allowed || got.Reason != "addon_not_purchased" {
t.Fatalf("addon: %+v", got)
}
// activation grants the add-on limit
if resp, raw := h.do("POST", "/v1/tenants/"+tn.ID+"/activate", map[string]any{
"plan": "business", "products": []map[string]any{{"key": "pruefwerk", "config": map[string]any{"runners": 2, "targets": 25}}},
}); resp.StatusCode != 200 {
t.Fatalf("activate: %d %s", resp.StatusCode, raw)
}
got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk", "addon": "werkbank"})
if !got.Allowed || got.Status != "active" || toF(got.Limits["runners"]) != 2 {
t.Fatalf("after activate: %+v", got)
}
if h.kcMock.Status["ent-co"] != "active" {
t.Fatalf("keycloak status not synced: %q", h.kcMock.Status["ent-co"])
}
// ladder: restricted → read-only; halted → denied; archived → denied
for _, tc := range []struct {
status string
allowed, ro bool
reason string
}{
{"warning", true, false, ""},
{"restricted", true, true, ""},
{"halted", false, false, "tenant_halted"},
{"archived", false, false, "tenant_archived"},
} {
if resp, raw := h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": tc.status, "source": "test"}); resp.StatusCode != 200 {
t.Fatalf("status %s: %d %s", tc.status, resp.StatusCode, raw)
}
got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if got.Allowed != tc.allowed || got.ReadOnly != tc.ro || got.Reason != tc.reason || got.Status != tc.status {
t.Fatalf("status %s: %+v", tc.status, got)
}
if h.kcMock.Status["ent-co"] != tc.status {
t.Fatalf("status %s not synced to keycloak", tc.status)
}
}
// unknown product / tenant
if got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "nope"}); got.Allowed || got.Reason != "unknown_product" {
t.Fatalf("unknown product: %+v", got)
}
if got = check(t, h, map[string]any{"tenant_id": "00000000-0000-0000-0000-00000000dead", "product": "pruefwerk"}); got.Allowed || got.Reason != "tenant_not_found" {
t.Fatalf("unknown tenant: %+v", got)
}
})
}
func TestSetStatus_rejectsBogus(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
for _, bad := range []string{"frozen", "paid", ""} {
resp, _ := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/status", map[string]any{"status": bad})
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("status %q: got %d", bad, resp.StatusCode)
}
}
})
}
func TestListTenants_pagination(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
for _, s := range []string{"p-one", "p-two", "p-three"} {
if resp, _ := h.do("POST", "/v1/tenants", map[string]any{"slug": s, "name": s}); resp.StatusCode != 201 {
t.Fatalf("create %s: %d", s, resp.StatusCode)
}
}
seen := map[string]bool{}
cursor := ""
for pages := 0; pages < 10; pages++ {
path := "/v1/tenants?limit=2"
if cursor != "" {
path += "&cursor=" + cursor
}
resp, raw := h.do("GET", path, nil)
if resp.StatusCode != 200 {
t.Fatalf("list: %d %s", resp.StatusCode, raw)
}
page := decode[struct {
Items []store.Tenant `json:"items"`
NextCursor string `json:"next_cursor"`
}](t, raw)
for _, it := range page.Items {
if seen[it.Slug] {
t.Fatalf("duplicate %s across pages", it.Slug)
}
seen[it.Slug] = true
}
if page.NextCursor == "" {
break
}
cursor = page.NextCursor
}
for _, s := range []string{"acme", "p-one", "p-two", "p-three"} {
if !seen[s] {
t.Errorf("missing %s", s)
}
}
// the three new tenants are trial; the seeded acme is active on the
// memory store and trial on the postgres harness.
want := 3
if h.tenant.Status == "trial" {
want = 4
}
resp, raw := h.do("GET", "/v1/tenants?status=trial", nil)
got := decode[struct {
Items []store.Tenant `json:"items"`
}](t, raw)
if resp.StatusCode != 200 || len(got.Items) != want {
t.Fatalf("status filter: %d got %d want %d", resp.StatusCode, len(got.Items), want)
}
if resp, _ := h.do("GET", "/v1/tenants?status=bogus", nil); resp.StatusCode != 400 {
t.Errorf("bogus status: %d", resp.StatusCode)
}
})
}
func TestCatalog_isStoreBacked(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
_, raw := h.do("GET", "/v1/catalog", nil)
out := decode[struct {
Items []store.CatalogEntry `json:"items"`
}](t, raw)
keys := map[string]store.CatalogEntry{}
for _, it := range out.Items {
keys[it.Key] = it
}
if _, ok := keys["compliance"]; ok {
t.Errorf("disabled product listed")
}
pw, ok := keys["pruefwerk"]
if !ok || pw.Type != "standalone" || pw.LaunchURL == "" || len(pw.Addons) != 1 || pw.Addons[0].ID != "werkbank" {
t.Fatalf("pruefwerk entry: %+v", pw)
}
if wp := keys["werkpilot"]; wp.Type != "cli" {
t.Errorf("werkpilot type: %+v", wp)
}
})
}
func toF(v interface{}) float64 {
f, _ := v.(float64)
return f
}
+3
View File
@@ -45,6 +45,9 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"GET", "/v1/catalog"},
{"GET", "/v1/audit?limit=10"},
{"POST", "/v1/internal/keycloak/claims"},
{"GET", "/v1/tenants?limit=10"},
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"},
{"POST", "/v1/internal/entitlements/check"},
}
for _, c := range cases {
req := newRequest(t, c.method, c.path)
+5 -1
View File
@@ -23,6 +23,7 @@ type Server struct {
Store store.Store
Keycloak keycloak.Adapter // never nil — main wires Mock when KC env is unset
Auth *authn.Verifier // nil ⇒ AUTH_ENABLED=false, API is open (dev only)
Authz *Authz // nil ⇒ AUTHZ_RULES unset, every client may call every route
Product product.Provisioner // never nil — main wires Noop when PRODUCT_API_URL is unset
}
@@ -54,13 +55,16 @@ func NewRouter(s *Server) http.Handler {
// tenants
mux.HandleFunc("POST /v1/tenants", s.createTenant)
mux.HandleFunc("GET /v1/tenants", s.listTenants)
mux.HandleFunc("GET /v1/tenants/{id}", s.getTenant)
mux.HandleFunc("GET /v1/tenants/by-slug/{slug}", s.getTenantBySlug)
mux.HandleFunc("POST /v1/tenants/{id}/activate", s.activateTenant)
mux.HandleFunc("POST /v1/tenants/{id}/cancel", s.cancelTenant)
mux.HandleFunc("POST /v1/tenants/{id}/status", s.setTenantStatus)
// entitlements
mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts)
mux.HandleFunc("POST /v1/internal/entitlements/check", s.checkEntitlement)
// catalog
mux.HandleFunc("GET /v1/catalog", s.getCatalog)
@@ -87,7 +91,7 @@ func NewRouter(s *Server) http.Handler {
// JWT subject belong to, with which org_roles and entitlements.
mux.HandleFunc("GET /v1/users/{id}/memberships", s.getUserMemberships)
root.Handle("/", s.requireAuth(mux))
root.Handle("/", s.requireAuth(s.requireAuthz(mux)))
return logRequest(s.Log)(root)
}
+186 -7
View File
@@ -5,6 +5,8 @@ import (
"errors"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/product"
@@ -146,11 +148,21 @@ func (s *Server) getTenantBySlug(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, t)
}
// activateProduct grants (or updates) one entitlement as part of activation.
// Config carries the purchased limits (seats, targets, runners, …) keyed by
// the catalog's limit keys.
type activateProduct struct {
Key string `json:"key"`
Config map[string]interface{} `json:"config,omitempty"`
ExpiresAt *string `json:"expires_at,omitempty"` // RFC3339
}
type activateReq struct {
Plan string `json:"plan,omitempty"`
ContractStart *string `json:"contract_start,omitempty"` // YYYY-MM-DD
ContractEnd *string `json:"contract_end,omitempty"`
ErpCustomerID string `json:"erp_customer_id,omitempty"`
Plan string `json:"plan,omitempty"`
ContractStart *string `json:"contract_start,omitempty"` // YYYY-MM-DD
ContractEnd *string `json:"contract_end,omitempty"`
ErpCustomerID string `json:"erp_customer_id,omitempty"`
Products []activateProduct `json:"products,omitempty"`
}
func (s *Server) activateTenant(w http.ResponseWriter, r *http.Request) {
@@ -181,6 +193,27 @@ func (s *Server) activateTenant(w http.ResponseWriter, r *http.Request) {
return
}
// Validate the product list before touching the tenant so a typo cannot
// leave a half-activated tenant behind.
granted := []grantedProduct{}
for _, ap := range in.Products {
prod, err := s.product(ctx, ap.Key)
if err != nil {
writeError(w, http.StatusBadRequest, "unknown_product", "product "+ap.Key+" is not in the catalog")
return
}
var exp *time.Time
if ap.ExpiresAt != nil && *ap.ExpiresAt != "" {
parsed, perr := time.Parse(time.RFC3339, *ap.ExpiresAt)
if perr != nil {
writeError(w, http.StatusBadRequest, "invalid_expires_at", "must be RFC3339")
return
}
exp = &parsed
}
granted = append(granted, grantedProduct{product: prod, config: ap.Config, expiresAt: exp})
}
t, err := s.Store.UpdateTenant(ctx, r.PathValue("id"), upd)
if err != nil {
if mapStoreError(w, err) {
@@ -195,13 +228,158 @@ func (s *Server) activateTenant(w http.ResponseWriter, r *http.Request) {
Metadata: map[string]interface{}{"plan": t.Plan, "erp_customer_id": t.ErpCustomerID},
})
for _, g := range granted {
cfg := g.config
if cfg == nil {
cfg = map[string]interface{}{}
}
cfg["source"] = "activation"
tp, uerr := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
TenantID: t.ID, Product: g.product.Key, Enabled: true, Config: cfg, ExpiresAt: g.expiresAt,
})
if uerr != nil {
s.Log.Error("grant entitlement failed", "tenant_id", t.ID, "product", g.product.Key, "err", uerr)
continue
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "entitlement.granted", TargetID: g.product.Key, TargetType: "product",
Metadata: map[string]interface{}{"config": cfg},
})
s.provisionProduct(ctx, r, t, g.product, tp)
}
s.syncTenantStatus(ctx, r, t)
writeJSON(w, http.StatusOK, t)
}
type grantedProduct struct {
product *store.Product
config map[string]interface{}
expiresAt *time.Time
}
// listTenants is GET /v1/tenants — service-only enumeration (product
// schedulers, reconcile jobs). Keyset-paginated; ?status= and ?kind= filter.
func (s *Server) listTenants(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
f := store.TenantFilter{Status: q.Get("status"), Kind: q.Get("kind"), Cursor: q.Get("cursor")}
if f.Status != "" && !store.ValidStatus(f.Status) {
writeError(w, http.StatusBadRequest, "invalid_status", "unknown status")
return
}
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n <= 0 || n > 500 {
writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..500")
return
}
f.Limit = n
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
items, next, err := s.Store.ListTenants(ctx, f)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
out := map[string]any{"items": items}
if next != "" {
out["next_cursor"] = next
}
writeJSON(w, http.StatusOK, out)
}
type setStatusReq struct {
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
Source string `json:"source,omitempty"` // erp | backstage | system
}
// setTenantStatus is POST /v1/tenants/{id}/status — the ladder transition
// used by the ERP link (M-MIG-7 webhooks + reconcile) and Backstage. It is
// the single place a status changes outside activate/cancel, so the Keycloak
// claim sync and the audit trail always follow.
func (s *Server) setTenantStatus(w http.ResponseWriter, r *http.Request) {
var in setStatusReq
if !decodeJSON(w, r, &in) {
return
}
if !store.ValidStatus(in.Status) || in.Status == store.StatusFrozen {
writeError(w, http.StatusBadRequest, "invalid_status", "status must be one of demo, trial, active, warning, restricted, halted, archived")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
before, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
t, err := s.Store.UpdateTenant(ctx, before.ID, store.TenantUpdate{Status: ptrStr(in.Status)})
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: "tenant.status_changed", TargetID: t.ID, TargetType: "tenant",
Metadata: map[string]interface{}{"from": before.Status, "to": t.Status, "reason": in.Reason, "source": in.Source},
})
s.syncTenantStatus(ctx, r, t)
writeJSON(w, http.StatusOK, t)
}
// syncTenantStatus pushes the coarse tenant_status claim to every member of
// the tenant's Keycloak organization (ERP/02: Keycloak carries only the
// coarse flag). Best-effort; failures are audited, never returned.
func (s *Server) syncTenantStatus(ctx context.Context, r *http.Request, t *store.Tenant) {
if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil {
s.Log.Warn("keycloak status sync failed", "tenant_id", t.ID, "status", t.Status, "err", err)
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "keycloak.status_sync_failed", TargetID: t.ID, TargetType: "tenant",
Metadata: map[string]interface{}{"status": t.Status, "err": err.Error()},
})
}
}
// provisionProduct calls the product's provisioning endpoint for this
// environment (PRODUCT_INTEGRATION_SPEC 2.0 §4.1 /v1/tenants/{id}/provision)
// when the catalog declares one. Best-effort with an audit trail; the ERP
// outbox (M-MIG-7) adds retries.
func (s *Server) provisionProduct(ctx context.Context, r *http.Request, t *store.Tenant, p *store.Product, tp *store.TenantProduct) {
url := p.ProvisionURLs[s.env()]
if url == "" {
return
}
url = strings.ReplaceAll(url, "{id}", t.ID)
payload := map[string]any{
"id": t.ID, "name": t.Name, "slug": t.Slug, "plan": t.Plan,
"product": p.Key, "config": tp.Config, "expires_at": tp.ExpiresAt, "contract_version": "2.0",
}
if err := product.ProvisionAt(ctx, url, payload, nil, 10*time.Second); err != nil {
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "product.provision_failed", TargetID: p.Key, TargetType: "product",
Metadata: map[string]interface{}{"url": url, "err": err.Error()},
})
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "product.tenant_provisioned", TargetID: p.Key, TargetType: "product",
})
}
type cancelReq struct {
Reason string `json:"reason,omitempty"`
// AtPeriodEnd is a hint to billing; we always flip to 'frozen' immediately
// since billing is out of scope here.
// AtPeriodEnd is a hint to billing; we flip to 'halted' (Angehalten)
// immediately — the ERP link (M-MIG-7) owns period-end semantics.
AtPeriodEnd bool `json:"at_period_end,omitempty"`
}
@@ -215,7 +393,7 @@ func (s *Server) cancelTenant(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
t, err := s.Store.UpdateTenant(ctx, r.PathValue("id"), store.TenantUpdate{
Status: ptrStr("frozen"),
Status: ptrStr(store.StatusHalted),
})
if err != nil {
if mapStoreError(w, err) {
@@ -228,6 +406,7 @@ func (s *Server) cancelTenant(w http.ResponseWriter, r *http.Request) {
TenantID: t.ID, Action: "tenant.canceled", TargetID: t.ID, TargetType: "tenant",
Metadata: map[string]interface{}{"reason": in.Reason, "at_period_end": in.AtPeriodEnd},
})
s.syncTenantStatus(ctx, r, t)
writeJSON(w, http.StatusOK, t)
}
+1 -1
View File
@@ -115,7 +115,7 @@ func TestCancelTenant(t *testing.T) {
t.Fatalf("status = %d, body=%s", resp.StatusCode, body)
}
got := decode[store.Tenant](t, body)
if got.Status != "frozen" {
if got.Status != "halted" {
t.Errorf("status = %q", got.Status)
}
})
+69 -2
View File
@@ -21,6 +21,7 @@ type Memory struct {
byPrefix map[string]string // prefix → id
audit []*AuditEvent
auditID int64
catalog []Product
}
type apiKeyWithHash struct {
@@ -36,6 +37,7 @@ func NewMemory() *Memory {
products: make(map[string]map[string]*TenantProduct),
apiKeys: make(map[string]*apiKeyWithHash),
byPrefix: make(map[string]string),
catalog: DefaultProducts(),
}
now := time.Now().UTC()
seed := &Tenant{
@@ -51,8 +53,8 @@ func NewMemory() *Memory {
m.tenants[seed.ID] = seed
m.bySlug[seed.Slug] = seed.ID
m.products[seed.ID] = map[string]*TenantProduct{
"certifai": {TenantID: seed.ID, Product: "certifai", Enabled: true, Config: map[string]interface{}{}, CreatedAt: now, UpdatedAt: now},
"compliance": {TenantID: seed.ID, Product: "compliance", Enabled: true, Config: map[string]interface{}{}, CreatedAt: now, UpdatedAt: now},
"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
}
@@ -155,6 +157,71 @@ func (m *Memory) UpdateTenant(_ context.Context, id string, in TenantUpdate) (*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 f.Cursor != "" && !(t.CreatedAt.After(cAt) || (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
}
// ─── 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) {
+118
View File
@@ -487,3 +487,121 @@ func nullableTime(p *time.Time) any {
}
return *p
}
// ─── tenant listing ───────────────────────────────────────────────────────
func (p *Postgres) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) {
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
cAt, cID, ok := decodeTenantCursor(f.Cursor)
if !ok {
return nil, "", ErrInvalidInput
}
where := []string{"TRUE"}
args := []any{}
add := func(clause string, v any) {
args = append(args, v)
where = append(where, fmt.Sprintf(clause, len(args)))
}
if f.Status != "" {
add("status = $%d::tenant_status", f.Status)
}
if f.Kind != "" {
add("kind = $%d::tenant_kind", f.Kind)
}
if f.Cursor != "" {
args = append(args, cAt, cID)
where = append(where, fmt.Sprintf("(created_at, id::text) > ($%d, $%d)", len(args)-1, len(args)))
}
args = append(args, limit+1)
rows, err := p.pool.Query(ctx, tenantSelect+`WHERE `+strings.Join(where, " AND ")+
` ORDER BY created_at, id LIMIT $`+fmt.Sprintf("%d", len(args)), args...)
if err != nil {
return nil, "", err
}
defer rows.Close()
out := []Tenant{}
for rows.Next() {
t, err := scanTenant(rows)
if err != nil {
return nil, "", err
}
out = append(out, *t)
}
if err := rows.Err(); err != nil {
return nil, "", err
}
next := ""
if len(out) > limit {
out = out[:limit]
next = encodeTenantCursor(out[len(out)-1])
}
return out, next, nil
}
// ─── products ─────────────────────────────────────────────────────────────
const productSelect = `
SELECT key, name, description, type, launch_urls, provision_urls, skus, addons,
plans_required, supports_trial, trial_days, enabled, sort_order, created_at, updated_at
FROM products `
func scanProduct(row pgx.Row) (*Product, error) {
var pr Product
var launch, prov, skus, addons []byte
err := row.Scan(&pr.Key, &pr.Name, &pr.Description, &pr.Type, &launch, &prov, &skus, &addons,
&pr.PlansRequired, &pr.SupportsTrial, &pr.TrialDays, &pr.Enabled, &pr.SortOrder, &pr.CreatedAt, &pr.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
_ = json.Unmarshal(launch, &pr.LaunchURLs)
_ = json.Unmarshal(prov, &pr.ProvisionURLs)
_ = json.Unmarshal(skus, &pr.SKUs)
_ = json.Unmarshal(addons, &pr.Addons)
if pr.LaunchURLs == nil {
pr.LaunchURLs = map[string]string{}
}
if pr.ProvisionURLs == nil {
pr.ProvisionURLs = map[string]string{}
}
if pr.SKUs == nil {
pr.SKUs = []string{}
}
if pr.Addons == nil {
pr.Addons = []ProductAddon{}
}
if pr.PlansRequired == nil {
pr.PlansRequired = []string{}
}
return &pr, nil
}
func (p *Postgres) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) {
q := productSelect
if !includeDisabled {
q += `WHERE enabled `
}
rows, err := p.pool.Query(ctx, q+`ORDER BY sort_order, key`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Product{}
for rows.Next() {
pr, err := scanProduct(rows)
if err != nil {
return nil, err
}
out = append(out, *pr)
}
return out, rows.Err()
}
func (p *Postgres) GetProduct(ctx context.Context, key string) (*Product, error) {
return scanProduct(p.pool.QueryRow(ctx, productSelect+`WHERE key = $1`, key))
}
+97
View File
@@ -0,0 +1,97 @@
package store
import (
"fmt"
"strconv"
"strings"
"time"
)
// DefaultProducts mirrors the seed rows of migrations/0003_products.up.sql
// for the Memory store. Keep the two in sync.
func DefaultProducts() []Product {
now := time.Now().UTC()
plans := []string{"standard", "business", "enterprise"}
return []Product{
{
Key: "pruefwerk", Name: "Prüfwerk", Type: "standalone",
Description: "Compliance scanner for CRA / IEC 62443 style assessments: SBOM, DAST, pentest orchestration, PLC provisioning tests.",
LaunchURLs: map[string]string{"stage": "https://pruefwerk-stage.breakpilot.com", "prod": "https://pruefwerk.breakpilot.com"},
ProvisionURLs: map[string]string{},
SKUs: []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN"},
Addons: []ProductAddon{{ID: "werkbank", Name: "Werkbank runner", LimitKey: "runners", SKUs: []string{"CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT"}}},
PlansRequired: plans, SupportsTrial: true, TrialDays: 14, Enabled: true, SortOrder: 10, CreatedAt: now, UpdatedAt: now,
},
{
Key: "werkpilot", Name: "Werkpilot", Type: "cli",
Description: "On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to llm.breakpilot.com.",
LaunchURLs: map[string]string{"stage": "https://git.breakpilot.com/platform/werkpilot/releases", "prod": "https://git.breakpilot.com/platform/werkpilot/releases"},
ProvisionURLs: map[string]string{},
SKUs: []string{"DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT"},
Addons: []ProductAddon{},
PlansRequired: plans, SupportsTrial: true, TrialDays: 14, Enabled: true, SortOrder: 20, CreatedAt: now, UpdatedAt: now,
},
{
Key: "firmwerk", Name: "Firmwerk", Type: "cli",
Description: "Reproducible firmware builds with SBOM / VEX / attestation (CLI + cloud control plane).",
LaunchURLs: map[string]string{"stage": "https://firmwerk-stage.breakpilot.com", "prod": "https://firmwerk.breakpilot.com"},
ProvisionURLs: map[string]string{},
SKUs: []string{"DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT"},
Addons: []ProductAddon{},
PlansRequired: plans, SupportsTrial: true, TrialDays: 14, Enabled: true, SortOrder: 30, CreatedAt: now, UpdatedAt: now,
},
{
Key: "compliance", Name: "Compliance", Type: "standalone",
Description: "DSFA / TOM / VVT generation; evidence capture.",
LaunchURLs: map[string]string{}, ProvisionURLs: map[string]string{},
SKUs: []string{}, Addons: []ProductAddon{},
PlansRequired: plans, SupportsTrial: true, TrialDays: 14, Enabled: false, SortOrder: 90, CreatedAt: now, UpdatedAt: now,
},
}
}
// Catalog projects a Product onto the /v1/catalog shape for one environment.
func (p Product) Catalog(env string) CatalogEntry {
return CatalogEntry{
Key: p.Key, Name: p.Name, Description: p.Description, Type: p.Type,
LaunchURL: p.LaunchURLs[env], SKUs: nonNil(p.SKUs), Addons: p.Addons,
PlansRequired: nonNil(p.PlansRequired), SupportsTrial: p.SupportsTrial, TrialDays: p.TrialDays,
}
}
// HasAddon reports whether the product sells the named add-on.
func (p Product) HasAddon(id string) bool {
for _, a := range p.Addons {
if a.ID == id {
return true
}
}
return false
}
func nonNil(s []string) []string {
if s == nil {
return []string{}
}
return s
}
// tenant list cursor: "<unix-nanos>_<id>" — keyset on (created_at, id).
func encodeTenantCursor(t Tenant) string {
return fmt.Sprintf("%d_%s", t.CreatedAt.UnixNano(), t.ID)
}
func decodeTenantCursor(c string) (time.Time, string, bool) {
if c == "" {
return time.Time{}, "", true
}
i := strings.IndexByte(c, '_')
if i <= 0 {
return time.Time{}, "", false
}
n, err := strconv.ParseInt(c[:i], 10, 64)
if err != nil {
return time.Time{}, "", false
}
return time.Unix(0, n).UTC(), c[i+1:], true
}
+5
View File
@@ -70,6 +70,11 @@ type Store interface {
GetTenant(ctx context.Context, id string) (*Tenant, error)
GetTenantBySlug(ctx context.Context, slug 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)
// 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)
+72 -7
View File
@@ -71,12 +71,77 @@ type AuditEvent struct {
CreatedAt time.Time `json:"created_at"`
}
// CatalogEntry — what /v1/catalog returns per available product.
// CatalogEntry — what /v1/catalog returns per available product. LaunchURL is
// already resolved for the registry's own environment.
type CatalogEntry struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
PlansRequired []string `json:"plans_required"`
DemoURL string `json:"demo_url,omitempty"`
SupportsTrial bool `json:"supports_trial"`
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
LaunchURL string `json:"launch_url,omitempty"`
SKUs []string `json:"skus"`
Addons []ProductAddon `json:"addons"`
PlansRequired []string `json:"plans_required"`
DemoURL string `json:"demo_url,omitempty"`
SupportsTrial bool `json:"supports_trial"`
TrialDays int `json:"trial_days"`
}
// ProductAddon — an add-on entitlement sold on top of a product (e.g. Werkbank
// runners on Prüfwerk). LimitKey is the config key in tenant_products.config
// that carries the purchased quantity.
type ProductAddon struct {
ID string `json:"id"`
Name string `json:"name"`
LimitKey string `json:"limit_key,omitempty"`
SKUs []string `json:"skus,omitempty"`
}
// Product — a catalog row (PRODUCT_INTEGRATION_SPEC 2.0 §10 subset). URL maps
// are keyed by environment (stage | prod).
type Product struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"` // standalone | headless | cli
LaunchURLs map[string]string `json:"launch_urls"`
ProvisionURLs map[string]string `json:"provision_urls,omitempty"`
SKUs []string `json:"skus"`
Addons []ProductAddon `json:"addons"`
PlansRequired []string `json:"plans_required"`
SupportsTrial bool `json:"supports_trial"`
TrialDays int `json:"trial_days"`
Enabled bool `json:"enabled"`
SortOrder int `json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TenantFilter narrows Store.ListTenants. Cursor is opaque (from a previous page).
type TenantFilter struct {
Status string
Kind string
Limit int
Cursor string
}
// Tenant status ladder (migration 0002; ERP/02). 'frozen' is legacy = restricted.
const (
StatusDemo = "demo"
StatusTrial = "trial"
StatusActive = "active"
StatusWarning = "warning"
StatusRestricted = "restricted"
StatusFrozen = "frozen"
StatusHalted = "halted"
StatusArchived = "archived"
)
// ValidStatus reports whether s is a known tenant status.
func ValidStatus(s string) bool {
switch s {
case StatusDemo, StatusTrial, StatusActive, StatusWarning, StatusRestricted, StatusFrozen, StatusHalted, StatusArchived:
return true
}
return false
}
+2
View File
@@ -0,0 +1,2 @@
-- Enum values cannot be dropped in PostgreSQL; forward-only (IMPLEMENTATION_PLAN §1.7).
SELECT 1;
+8
View File
@@ -0,0 +1,8 @@
-- M-MIG-5 — tenant status ladder (ERP/02): active = Betriebsbereit,
-- warning = Warnung, restricted = Eingeschränkt, halted = Angehalten.
-- 'frozen' is kept for existing rows and treated like 'restricted'.
-- (ADD VALUE is its own migration: new enum values cannot be used in the
-- transaction that adds them.)
ALTER TYPE tenant_status ADD VALUE IF NOT EXISTS 'warning';
ALTER TYPE tenant_status ADD VALUE IF NOT EXISTS 'restricted';
ALTER TYPE tenant_status ADD VALUE IF NOT EXISTS 'halted';
+1
View File
@@ -0,0 +1 @@
DROP TABLE IF EXISTS products;
+49
View File
@@ -0,0 +1,49 @@
-- M-MIG-5 — product catalog moves from code into the registry.
-- launch_urls / provision_urls are keyed by environment (stage | prod).
CREATE TABLE products (
key TEXT PRIMARY KEY CHECK (key ~ '^[a-z][a-z0-9-]{1,38}$'),
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
type TEXT NOT NULL CHECK (type IN ('standalone', 'headless', 'cli')),
launch_urls JSONB NOT NULL DEFAULT '{}'::jsonb,
provision_urls JSONB NOT NULL DEFAULT '{}'::jsonb,
skus JSONB NOT NULL DEFAULT '[]'::jsonb,
addons JSONB NOT NULL DEFAULT '[]'::jsonb,
plans_required TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
supports_trial BOOLEAN NOT NULL DEFAULT TRUE,
trial_days INT NOT NULL DEFAULT 14,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
sort_order INT NOT NULL DEFAULT 100,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TRIGGER products_touch_updated_at
BEFORE UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
-- First-line products (PLATFORM_ARCHITECTURE §2). URLs per environment.
INSERT INTO products (key, name, description, type, launch_urls, skus, addons, plans_required, supports_trial, trial_days, enabled, sort_order) VALUES
('pruefwerk', 'Prüfwerk',
'Compliance scanner for CRA / IEC 62443 style assessments: SBOM, DAST, pentest orchestration, PLC provisioning tests.',
'standalone',
'{"stage": "https://pruefwerk-stage.breakpilot.com", "prod": "https://pruefwerk.breakpilot.com"}',
'["CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN"]',
'[{"id": "werkbank", "name": "Werkbank runner", "limit_key": "runners", "skus": ["CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT"]}]',
ARRAY['standard', 'business', 'enterprise'], TRUE, 14, TRUE, 10),
('werkpilot', 'Werkpilot',
'On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to llm.breakpilot.com.',
'cli',
'{"stage": "https://git.breakpilot.com/platform/werkpilot/releases", "prod": "https://git.breakpilot.com/platform/werkpilot/releases"}',
'["DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT"]',
'[]', ARRAY['standard', 'business', 'enterprise'], TRUE, 14, TRUE, 20),
('firmwerk', 'Firmwerk',
'Reproducible firmware builds with SBOM / VEX / attestation (CLI + cloud control plane).',
'cli',
'{"stage": "https://firmwerk-stage.breakpilot.com", "prod": "https://firmwerk.breakpilot.com"}',
'["DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT"]',
'[]', ARRAY['standard', 'business', 'enterprise'], TRUE, 14, TRUE, 30),
-- breakpilot-compliance (dsms) is re-enabled when it migrates to the platform cluster (M-MIG-9).
('compliance', 'Compliance',
'DSFA / TOM / VVT generation; evidence capture.',
'standalone', '{}', '[]', '[]', ARRAY['standard', 'business', 'enterprise'], TRUE, 14, FALSE, 90);
+3 -1
View File
@@ -98,6 +98,7 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
"tenant_idp_config",
"api_keys",
"audit_log",
"products",
}
for _, table := range wantTables {
var exists bool
@@ -115,7 +116,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
// Enum assertions.
wantEnums := map[string][]string{
"tenant_status": {"demo", "trial", "active", "frozen", "archived"},
// 0002 appends the ladder values; enum values are never removed (down is a no-op).
"tenant_status": {"demo", "trial", "active", "frozen", "archived", "warning", "restricted", "halted"},
"tenant_kind": {"customer", "demo"},
"idp_kind": {"oidc", "saml"},
"tenant_project_status": {"active", "archived"},
+138 -6
View File
@@ -12,6 +12,14 @@ info:
/healthz and /readyz requires a Keycloak-issued bearer token whose
audience contains AUTH_EXPECTED_AUDIENCE (INTERNAL_SERVICE_ONLY
posture). With AUTH_ENABLED=false (dev default) the API is open.
Per-client authorization (M-MIG-5): AUTHZ_RULES maps each client
(JWT azp) to route groups — tenants(.read|.write), catalog,
entitlements, api-keys(.verify), audit(.read|.write), users,
keycloak, erp, usage, licences. Unlisted clients get 403.
Tenant status ladder (ERP/02): demo, trial, active (Betriebsbereit),
warning (Warnung), restricted (Eingeschränkt, read-only), halted
(Angehalten), archived. 'frozen' is legacy = restricted.
contact:
email: oncall@breakpilot.com
license:
@@ -19,9 +27,9 @@ info:
servers:
- url: http://localhost:8090
description: Local dev
- url: https://tenant-registry.stage.breakpilot.com
- url: https://registry-stage.breakpilot.com
description: Stage
- url: https://tenant-registry.breakpilot.com
- url: https://registry.breakpilot.com
description: Production
paths:
@@ -49,6 +57,34 @@ paths:
application/json: { schema: { $ref: "#/components/schemas/Error" } }
/v1/tenants:
get:
summary: List tenants (service-only; keyset paginated).
parameters:
- in: query
name: status
schema: { $ref: "#/components/schemas/TenantStatus" }
- in: query
name: kind
schema: { type: string, enum: [customer, demo] }
- in: query
name: limit
schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
- in: query
name: cursor
schema: { type: string, description: "next_cursor from the previous page" }
responses:
"200":
description: Page of tenants; next_cursor omitted on the last page.
content:
application/json:
schema:
type: object
properties:
items:
type: array
items: { $ref: "#/components/schemas/Tenant" }
next_cursor: { type: string }
"400": { $ref: "#/components/responses/BadRequest" }
post:
summary: Create a tenant.
description: |
@@ -120,9 +156,40 @@ paths:
"400": { $ref: "#/components/responses/BadRequest" }
"404": { $ref: "#/components/responses/NotFound" }
/v1/tenants/{id}/status:
post:
summary: Move a tenant along the status ladder (ERP link, Backstage).
description: |
The one transition endpoint outside activate/cancel. Syncs the coarse
`tenant_status` claim to every Keycloak member of the tenant's
organization and writes a `tenant.status_changed` audit event.
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [status]
properties:
status: { $ref: "#/components/schemas/TenantStatus" }
reason: { type: string }
source: { type: string, enum: [erp, backstage, system, test] }
responses:
"200":
description: Updated.
content:
application/json: { schema: { $ref: "#/components/schemas/Tenant" } }
"400": { $ref: "#/components/responses/BadRequest" }
"404": { $ref: "#/components/responses/NotFound" }
/v1/tenants/{id}/cancel:
post:
summary: Move tenant to status=frozen.
summary: Move tenant to status=halted (Angehalten).
parameters:
- in: path
name: id
@@ -161,6 +228,32 @@ paths:
"400": { $ref: "#/components/responses/BadRequest" }
"404": { $ref: "#/components/responses/NotFound" }
/v1/internal/entitlements/check:
post:
summary: Is this tenant entitled to this product (and add-on) right now?
description: |
The authoritative entitlement answer (PRODUCT_INTEGRATION_SPEC 2.0
§4.4). Products cache it for ≤ 60 s and fail closed when the
registry is unreachable. `read_only` reflects the ladder
(restricted); `halted` and `archived` are never allowed.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [tenant_id, product]
properties:
tenant_id: { type: string, format: uuid }
product: { type: string }
addon: { type: string, description: "add-on id from the catalog, e.g. werkbank" }
responses:
"200":
description: Decision.
content:
application/json: { schema: { $ref: "#/components/schemas/EntitlementCheck" } }
"400": { $ref: "#/components/responses/BadRequest" }
/v1/catalog:
get:
summary: List the products available for any tenant to request.
@@ -426,6 +519,30 @@ components:
application/json: { schema: { $ref: "#/components/schemas/Error" } }
schemas:
TenantStatus:
type: string
enum: [demo, trial, active, warning, restricted, frozen, halted, archived]
EntitlementCheck:
type: object
required: [allowed, read_only]
properties:
allowed: { type: boolean }
read_only: { type: boolean }
status: { $ref: "#/components/schemas/TenantStatus" }
limits: { type: object, additionalProperties: true, description: "tenant_products.config — purchased limits" }
expires_at: { type: string, format: date-time, nullable: true }
reason: { type: string, enum: [unknown_product, unknown_addon, tenant_not_found, tenant_archived, tenant_halted, entitlement_disabled, entitlement_expired, addon_not_purchased, not_entitled] }
ProductAddon:
type: object
required: [id, name]
properties:
id: { type: string }
name: { type: string }
limit_key: { type: string }
skus: { type: array, items: { type: string } }
Claims:
type: object
required: [tenant_id, tenant_slug, plan, tenant_status]
@@ -435,7 +552,7 @@ components:
org_roles: { type: array, items: { type: string } }
products: { type: array, items: { type: string } }
plan: { type: string }
tenant_status: { type: string, enum: [demo, trial, active, frozen, archived] }
tenant_status: { $ref: "#/components/schemas/TenantStatus" }
Error:
type: object
@@ -451,7 +568,7 @@ components:
id: { type: string, format: uuid }
slug: { type: string }
name: { type: string }
status: { type: string, enum: [demo, trial, active, frozen, archived] }
status: { $ref: "#/components/schemas/TenantStatus" }
kind: { type: string, enum: [customer, demo] }
plan: { type: string }
erp_customer_id: { type: string }
@@ -489,6 +606,16 @@ components:
contract_start: { type: string, format: date }
contract_end: { type: string, format: date }
erp_customer_id: { type: string }
products:
type: array
description: Entitlements granted with the activation (SKU limits in config).
items:
type: object
required: [key]
properties:
key: { type: string }
config: { type: object, additionalProperties: true }
expires_at: { type: string, format: date-time }
TenantCancel:
type: object
@@ -510,14 +637,19 @@ components:
CatalogEntry:
type: object
required: [key, name, description, plans_required, supports_trial]
required: [key, name, description, type, plans_required, supports_trial]
properties:
key: { type: string }
name: { type: string }
description: { type: string }
type: { type: string, enum: [standalone, headless, cli] }
launch_url: { type: string, description: "product host for this environment (standalone) or download page (cli)" }
skus: { type: array, items: { type: string } }
addons: { type: array, items: { $ref: "#/components/schemas/ProductAddon" } }
plans_required: { type: array, items: { type: string } }
demo_url: { type: string }
supports_trial: { type: boolean }
trial_days: { type: integer }
CatalogRequest:
type: object