Files
Sharang ParnerkarandClaude Opus 5.5 3e42b1ceb8
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Failing after 1m54s
ci / image (pull_request) Skipped
feat(onprem): refuse unknown product keys, no trials in the catalog, tighter tests
- Start fails when PRODUCTS or a URL override names no catalog product.
- The on-prem catalog sets supports_trial=false (the portal hides the button).
- Test that seeded cloud provision URLs are never called on-prem, with a
  cloud control; the outbox test gets its cloud control too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:39:22 +01:00

198 lines
6.4 KiB
Go

package server
import (
"context"
"errors"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"net/http"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// 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 {
e := p.Catalog(s.env())
if s.onPrem() {
e.SupportsTrial = false // no trials on a customer's node: the portal hides the button
}
items = append(items, e)
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// env is the environment key used for per-env product URLs (see
// config.CatalogEnv). On-prem the catalog has no seeded URLs; they come from
// PRODUCT_*_URLS through store.ProductOverrides.
func (s *Server) env() string { return s.Cfg.CatalogEnv() }
// onPrem reports a registry on a customer's node (APP_ENV=onprem).
func (s *Server) onPrem() bool { return s.Cfg.OnPrem() }
// notOnPrem answers 404 for a feature that does not exist on-prem (sign-up,
// trial offers, sales requests, the ERP) and reports whether it did.
func (s *Server) notOnPrem(w http.ResponseWriter) bool {
if !s.onPrem() {
return false
}
writeError(w, http.StatusNotFound, "not_available", "not available in this installation")
return true
}
// 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 {
TenantID string `json:"tenant_id"`
Product string `json:"product"`
}
// 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) {
if s.notOnPrem(w) {
return
}
var in catalogRequestReq
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(), 5*time.Second)
defer cancel()
if !s.knownProduct(ctx, in.Product) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
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},
})
// CRM lead through the ERP outbox (M-MIG-7).
email := ""
if p, _ := authn.PrincipalFrom(r.Context()); p != nil {
email = p.Email
}
if _, err := s.enqueueERP(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
Payload: map[string]interface{}{"lead_name": t.Name, "company_name": t.Name, "email": email, "product": in.Product,
"notes": "Requested " + in.Product + " from the platform catalog"}}); err != nil {
s.Log.Error("enqueue lead failed", "tenant_id", in.TenantID, "err", err)
}
writeJSON(w, http.StatusAccepted, map[string]string{
"status": "accepted",
"message": "request recorded; sales will be in touch",
})
}
// 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) {
if s.notOnPrem(w) {
return
}
var in catalogRequestReq
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(), 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
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
days := entry.TrialDays
if days <= 0 {
days = 14
}
expiresAt := productTrialEnd(t, time.Now().UTC(), days)
tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
TenantID: in.TenantID, Product: in.Product, Enabled: true,
Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &expiresAt,
})
if err != nil {
if mapStoreError(w, err) {
return
}
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)
}
// productTrialEnd is when a product trial started now ends. In a workspace on
// trial it ends with the workspace's trial, which staff set or extended for
// the customer; a product of its own default length would end before or
// after what was agreed. Otherwise (a paying workspace trying another
// product) it runs `days` days.
func productTrialEnd(t *store.Tenant, now time.Time, days int) time.Time {
if t != nil && t.Status == store.StatusTrial && t.TrialEndsAt != nil && t.TrialEndsAt.After(now) {
return t.TrialEndsAt.UTC()
}
return now.Add(time.Duration(days) * 24 * time.Hour)
}