package server import ( "context" "errors" "net/http" "regexp" "strconv" "strings" "time" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/product" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // slug validation mirrors the schema CHECK in 0001_init.up.sql so we reject // at the API boundary rather than waiting for the DB to do it. var slugRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$`) // reservedSlugs are paths the portal or the platform serves itself // (app.breakpilot.com/): a tenant with one of these names would be // unreachable or would shadow a route. Mirrors the portal's src/lib/signup.ts, // except "demo", which the sales demo tenant itself uses. var reservedSlugs = map[string]bool{ "admin": true, "api": true, "app": true, "auth": true, "billing": true, "docs": true, "help": true, "install": true, "login": true, "logout": true, "portal": true, "signin": true, "signout": true, "signup": true, "start": true, "static": true, "status": true, "support": true, "www": true, "breakpilot": true, "datenschutz": true, "privacy": true, "impressum": true, "testbedingungen": true, } // staffOnlySlugs are reserved for everyone but Breakpilot staff: the company's own // workspace is app.breakpilot.com/breakpilot (Sharang's decision, 12.11.2026), while no // customer and no trial offer may take the name (the trial's freeSlug still skips it). var staffOnlySlugs = map[string]bool{"breakpilot": true} type createTenantReq struct { Slug string `json:"slug"` Name string `json:"name"` Plan string `json:"plan,omitempty"` Kind string `json:"kind,omitempty"` SalesOwner string `json:"sales_owner,omitempty"` // AdminEmail is optional. When set, the Keycloak adapter provisions // an organization + invites this user as IT_ADMIN. Omitted for // sales-led flows that invite the admin later via the portal. AdminEmail string `json:"admin_email,omitempty"` AdminName string `json:"admin_name,omitempty"` // Set only by the trial activation (portal#64), never from JSON: the // admin's name parts and an already confirmed e-mail address. adminFirst, adminLast string emailVerified bool } // createTenantResp wraps the tenant with the optional KC invite URL so // dev testers can use it without waiting for the email. type createTenantResp struct { Tenant *store.Tenant `json:"tenant"` InviteURL string `json:"invite_url,omitempty"` } func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { var in createTenantReq if !decodeJSON(w, r, &in) { return } if !slugRE.MatchString(in.Slug) { writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$") return } if reservedSlugs[in.Slug] { if _, _, staff := s.staffActor(r); !staff || !staffOnlySlugs[in.Slug] { writeError(w, http.StatusBadRequest, "reserved_slug", "this slug is reserved for a platform path") return } } if in.Name == "" || len(in.Name) > 255 { writeError(w, http.StatusBadRequest, "invalid_name", "name must be 1..255 chars") return } if in.Kind != "" && in.Kind != "customer" && in.Kind != "demo" { writeError(w, http.StatusBadRequest, "invalid_kind", "kind must be 'customer' or 'demo'") return } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() t, invite, aerr := s.createTenantCore(ctx, r, in) if aerr != nil { writeError(w, aerr.status, aerr.code, aerr.msg) return } writeJSON(w, http.StatusCreated, createTenantResp{Tenant: t, InviteURL: invite.URL}) } // apiError is a handler-independent error answer. type apiError struct { status int code, msg string } // createTenantCore creates the tenant and provisions Keycloak, the products // and the ERP customer (each best effort, audited). Shared by POST // /v1/tenants and the trial activation. func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in createTenantReq) (*store.Tenant, kcInvite, *apiError) { // An address with an account already belongs to a workspace (or to // staff): reject before anything is created, so no admin-less tenant and // no orphan organization are left behind. A lookup failure falls through // to the best-effort provisioning below. if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil { if taken, err := s.Keycloak.UserExists(ctx, email); err == nil && taken { return nil, kcInvite{}, &apiError{http.StatusConflict, "email_taken", "an account with this email already exists"} } else if err != nil { s.Log.Warn("keycloak user lookup failed", "err", err) } } t, err := s.Store.CreateTenant(ctx, store.TenantCreate{ Slug: in.Slug, Name: in.Name, Plan: in.Plan, Kind: in.Kind, SalesOwner: in.SalesOwner, AdminEmail: strings.ToLower(strings.TrimSpace(in.AdminEmail)), }) if err != nil { switch { case errors.Is(err, store.ErrConflict): return nil, kcInvite{}, &apiError{http.StatusConflict, "conflict", "resource already exists"} case errors.Is(err, store.ErrInvalidInput): return nil, kcInvite{}, &apiError{http.StatusBadRequest, "invalid_input", "input failed validation"} } s.Log.Error("create tenant failed", "err", err) return nil, kcInvite{}, &apiError{http.StatusInternalServerError, "internal", "create failed"} } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "tenant.created", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug, Metadata: map[string]interface{}{"plan": t.Plan, "kind": t.Kind}, }) // Best-effort Keycloak provisioning. A failure here doesn't roll the // tenant back — the operator can resend the invite via the KC admin UI. // We emit an audit event regardless so the failure is traceable. invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, }) if kcErr != nil { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.provision_failed", TargetID: t.ID, TargetType: "tenant", Metadata: map[string]interface{}{"err": kcErr.Error(), "admin_email": in.AdminEmail}, }) } else if invite.MailErr != nil { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.invite_mail_failed", TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, Metadata: map[string]interface{}{"err": invite.MailErr.Error()}, }) } else if in.AdminEmail != "" { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.invite_sent", TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, Metadata: map[string]interface{}{"role": "IT_ADMIN"}, }) } // Best-effort product provisioning, same contract as Keycloak above: the // registry is the authority for tenant identity, so the product gets a row // keyed by OUR uuid. A failure must not roll the tenant back — it is // recorded as an audit event so the divergence is traceable and fixable. // Without this the anchors drift and the product's gate rejects every // request from the tenant because it cannot resolve the org slug. if perr := s.productProvisioner().ProvisionTenant(ctx, product.Tenant{ ID: t.ID, Name: t.Name, Slug: t.Slug, }); perr != nil { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "product.provision_failed", TargetID: t.ID, TargetType: "tenant", Metadata: map[string]interface{}{"err": perr.Error()}, }) } else { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "product.tenant_provisioned", TargetID: t.ID, TargetType: "tenant", }) } // ERP link: create the Customer through the outbox (retried until ERP // answers); erp_customer_id is written back by the worker. if in.Kind != "demo" { s.EnqueueCustomerUpsert(ctx, t) } return t, invite, nil } func (s *Server) getTenant(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() t, err := s.Store.GetTenant(ctx, r.PathValue("id")) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } writeJSON(w, http.StatusOK, t) } func (s *Server) getTenantBySlug(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() t, err := s.Store.GetTenantBySlug(ctx, r.PathValue("slug")) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } 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"` Products []activateProduct `json:"products,omitempty"` } func (s *Server) activateTenant(w http.ResponseWriter, r *http.Request) { var in activateReq if !decodeJSON(w, r, &in) { return } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() upd := store.TenantUpdate{Status: ptrStr("active")} if in.Plan != "" { upd.Plan = &in.Plan } if in.ErpCustomerID != "" { upd.ErpCustomerID = &in.ErpCustomerID } if cs, err := parseDate(in.ContractStart); err == nil && cs != nil { upd.ContractStart = cs } else if err != nil { writeError(w, http.StatusBadRequest, "invalid_contract_start", "must be YYYY-MM-DD") return } if ce, err := parseDate(in.ContractEnd); err == nil && ce != nil { upd.ContractEnd = ce } else if err != nil { writeError(w, http.StatusBadRequest, "invalid_contract_end", "must be YYYY-MM-DD") 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) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "tenant.activated", TargetID: t.ID, TargetType: "tenant", 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 } // Setting the status a tenant already has changes nothing: no write, no // audit entry, no Keycloak sync. Repeating a call stays harmless. if before.Status == in.Status { writeJSON(w, http.StatusOK, before) 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", } auth := func(ctx context.Context) (string, error) { tok, err := s.Keycloak.ServiceToken(ctx) if err != nil || tok == "" { return "", err } return "Bearer " + tok, nil } if err := product.ProvisionAt(ctx, url, payload, auth, 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 flip to 'halted' (Angehalten) // immediately — the ERP link (M-MIG-7) owns period-end semantics. AtPeriodEnd bool `json:"at_period_end,omitempty"` } func (s *Server) cancelTenant(w http.ResponseWriter, r *http.Request) { var in cancelReq if r.ContentLength > 0 { if !decodeJSON(w, r, &in) { return } } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() t, err := s.Store.UpdateTenant(ctx, r.PathValue("id"), store.TenantUpdate{ Status: ptrStr(store.StatusHalted), }) 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.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) } func (s *Server) listTenantProducts(w http.ResponseWriter, r *http.Request) { tenantID := r.URL.Query().Get("tenant_id") if tenantID == "" { writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required") return } ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() list, err := s.Store.ListTenantProducts(ctx, tenantID) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"items": list}) } // ─── helpers (internal to this file) ────────────────────────────────────── func ptrStr(s string) *string { return &s } func parseDate(p *string) (*time.Time, error) { if p == nil || *p == "" { return nil, nil } t, err := time.Parse("2006-01-02", *p) if err != nil { return nil, errors.New("invalid date") } return &t, nil } // emitAudit is a fire-and-forget audit emit. Failures are logged but not // returned to the caller — the actual user-facing operation already succeeded. func (s *Server) emitAudit(ctx context.Context, r *http.Request, ev store.AuditEvent) { if r != nil { ev.SourceIP = clientIP(r) ev.UserAgent = r.UserAgent() // A change made from the staff admin area is attributed to the person. if sub, email, ok := s.staffActor(r); ok { ev.ActorID, ev.ActorName, ev.ActorType = sub, email, "staff" } } else if ev.ActorType == "" { ev.ActorType = "system" } if _, err := s.Store.AppendAudit(ctx, ev); err != nil { s.Log.Warn("audit emit failed", "err", err, "action", ev.Action) } }