feat(onprem): APP_ENV=onprem for a customer's own node
ci / shared (pull_request) Successful in 11s
ci / test (pull_request) Failing after 38s
ci / image (pull_request) Skipped

The registry on a customer's node must never reach a Breakpilot host and
must not run the cloud's commercial machinery.

- APP_ENV=onprem: no ERP (nothing queued, webhook off), no trial (new
  workspaces start active, the ladder never escalates by time), and the
  trial-offer, trial-terms, catalog/trial request and admin trial routes
  answer 404 not_available.
- PRODUCTS, PRODUCT_LAUNCH_URLS, PRODUCT_PROVISION_URLS: one store
  decorator applies the product list and URLs to every catalog read
  (catalog, activation, provisioning, entitlement checks). On-prem has no
  seeded URLs, so provisioning goes only to the local products. Checked at
  start ({id} in provision URLs, absolute http(s)).
- On-prem start fails when the values leave something to a cloud or dev
  default (auth off, no authz rules, ephemeral licence key, portal, invite,
  sender, LLM gateway) or set an ERP or contract documents.
- SMTP_TLS=starttls|tls|none: a plain relay inside the customer's network;
  no AUTH without encryption.
- Migration 0032: the Werkpilot text no longer names our LLM host.

Cloud behaviour is unchanged without the new variables (tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-19 17:35:53 +01:00
1 parent 768c195854
commit 2f6fa5f3e8
18 files changed
+786 -30

No files matched your search

+22 -7
View File
@@ -29,13 +29,22 @@ func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// 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"
// 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
}
return s.Cfg.Env
writeError(w, http.StatusNotFound, "not_available", "not available in this installation")
return true
}
// product returns an enabled catalog product or ErrNotFound.
@@ -63,6 +72,9 @@ type catalogRequestReq struct {
// 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
@@ -95,7 +107,7 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
if p, _ := authn.PrincipalFrom(r.Context()); p != nil {
email = p.Email
}
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
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)
@@ -109,6 +121,9 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
// 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
+5
View File
@@ -697,6 +697,11 @@ func (s *Server) Reconcile(ctx context.Context) ReconcileReport {
// escalation returns the time-based next rung for t at `now` ("" = none).
func (s *Server) escalation(t *store.Tenant, now time.Time) (string, string) {
if s.onPrem() {
// The licence is the contract with the customer, not a trial or an
// invoice: nothing escalates by time on a customer's own node.
return "", ""
}
day := 24 * time.Hour
age := now.Sub(t.StatusChangedAt)
switch t.Status {
+192
View File
@@ -0,0 +1,192 @@
package server_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/config"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// onPremHarness turns a harness into an on-prem registry: Prüfwerk and
// Werkmeister ship (Werkmeister's row is disabled in the seed), with local URLs.
func onPremHarness(h *testHarness, provision map[string]string) {
h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30}
h.app.Store = store.WithProductOverrides(h.store, h.app.Cfg.CatalogEnv(),
[]string{"pruefwerk", "werkmeister"},
map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"},
provision)
}
func TestOnPrem_catalogListsOnlyShippedProductsWithLocalURLs(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
resp, body := h.do("GET", "/v1/catalog", nil)
if resp.StatusCode != 200 {
t.Fatalf("status = %d", resp.StatusCode)
}
out := decode[struct {
Items []store.CatalogEntry `json:"items"`
}](t, body)
got := map[string]string{}
for _, it := range out.Items {
got[it.Key] = it.LaunchURL
}
want := map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"}
if len(got) != len(want) {
t.Fatalf("catalog = %v, want %v", got, want)
}
for k, v := range want {
if got[k] != v {
t.Errorf("%s launch URL = %q, want %q", k, got[k], v)
}
}
if strings.Contains(string(body), "breakpilot.com") {
t.Errorf("on-prem catalog names a Breakpilot host: %s", body)
}
})
}
func TestOnPrem_cloudOnlyRoutesAnswer404(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
for _, c := range []struct{ method, path string }{
{"POST", "/v1/catalog/request"},
{"POST", "/v1/catalog/trial-request"},
{"POST", "/v1/trial-offers"},
{"POST", "/v1/trial-offers/verify"},
{"GET", "/v1/trial-offers/x"},
{"POST", "/v1/trial-offers/x/resend"},
{"GET", "/v1/legal/trial-terms"},
{"POST", "/v1/internal/erp/webhook"},
{"POST", "/v1/admin/tenants/" + h.tenant.ID + "/trial"},
{"GET", "/v1/tenants/" + h.tenant.ID + "/contracts/trial/terms.pdf"},
} {
resp, body := h.do(c.method, c.path, map[string]any{"tenant_id": h.tenant.ID, "product": "pruefwerk"})
if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_available") {
t.Errorf("%s %s = %d %s, want 404 not_available", c.method, c.path, resp.StatusCode, body)
}
}
})
}
func TestOnPrem_newWorkspaceIsActiveAndQueuesNothingForTheERP(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
ctx := context.Background()
before, err := h.store.PendingOutbox(ctx)
if err != nil {
t.Fatal(err)
}
resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create = %d %s", resp.StatusCode, body)
}
out := decode[struct {
Tenant *store.Tenant `json:"tenant"`
}](t, body)
if out.Tenant.Status != store.StatusActive {
t.Errorf("status = %q, want active", out.Tenant.Status)
}
after, err := h.store.PendingOutbox(ctx)
if err != nil {
t.Fatal(err)
}
if after != before {
t.Errorf("outbox grew from %d to %d on-prem", before, after)
}
})
}
func TestOnPrem_nothingEscalatesByTime(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
trial := newTrial(t, h)
onPremHarness(h, nil)
// A year later the cloud would have restricted it.
h.app.Now = func() time.Time { return time.Now().AddDate(1, 0, 0) }
rep := h.app.Reconcile(ctx)
if len(rep.Escalated) != 0 {
t.Errorf("escalated on-prem: %v", rep.Escalated)
}
got, err := h.store.GetTenant(ctx, trial.ID)
if err != nil {
t.Fatal(err)
}
if got.Status != store.StatusTrial {
t.Errorf("status trial → %q", got.Status)
}
})
}
func TestOnPrem_activationProvisionsAtTheLocalURL(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
var mu sync.Mutex
var paths []string
local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
mu.Lock()
paths = append(paths, r.Method+" "+r.URL.Path)
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer local.Close()
onPremHarness(h, map[string]string{"pruefwerk": local.URL + "/api/v1/platform/tenants/{id}/provision"})
resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{
"products": []map[string]any{{"key": "pruefwerk"}},
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("activate = %d %s", resp.StatusCode, body)
}
mu.Lock()
defer mu.Unlock()
want := "POST /api/v1/platform/tenants/" + h.tenant.ID + "/provision"
if len(paths) != 1 || paths[0] != want {
t.Errorf("provision calls = %v, want [%s]", paths, want)
}
})
}
func TestOnPrem_unshippedProductCannotBeActivated(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{
"products": []map[string]any{{"key": "firmwerk"}},
})
if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "unknown_product") {
t.Errorf("activate firmwerk = %d %s, want 400 unknown_product", resp.StatusCode, body)
}
})
}
// The same year-old trial does escalate in the cloud (the control for the test above).
func TestCloud_trialStillEscalatesByTime(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
trial := newTrial(t, h)
h.app.Now = func() time.Time { return time.Now().AddDate(1, 0, 0) }
rep := h.app.Reconcile(context.Background())
if !slices.Contains(rep.Escalated, trial.Slug+"→"+store.StatusRestricted) {
t.Errorf("escalated = %v, want %s restricted", rep.Escalated, trial.Slug)
}
})
}
func newTrial(t *testing.T, h *testHarness) *store.Tenant {
t.Helper()
tr, err := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "trial-ws", Name: "Trial Workspace"})
if err != nil {
t.Fatal(err)
}
if tr.Status != store.StatusTrial || tr.TrialEndsAt == nil {
t.Fatalf("new tenant is %q (trial end %v), want a trial", tr.Status, tr.TrialEndsAt)
}
return tr
}
+10 -1
View File
@@ -25,9 +25,18 @@ var outboxBackoff = []time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minu
// keeps its payload so it can be re-queued (done_at = NULL, attempts = 0).
const maxOutboxAttempts = 170
// enqueueERP queues a write for the ERP. On-prem there is no ERP: nothing is
// queued, so the outbox never fills with items no worker will drain.
func (s *Server) enqueueERP(ctx context.Context, it store.OutboxItem) (*store.OutboxItem, error) {
if s.onPrem() {
return nil, nil
}
return s.Store.EnqueueOutbox(ctx, it)
}
// EnqueueCustomerUpsert is called on tenant creation.
func (s *Server) EnqueueCustomerUpsert(ctx context.Context, t *store.Tenant) {
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxCustomerUpsert, TenantID: t.ID,
if _, err := s.enqueueERP(ctx, store.OutboxItem{Kind: store.OutboxCustomerUpsert, TenantID: t.ID,
Payload: map[string]interface{}{"name": t.Name, "slug": t.Slug}}); err != nil {
s.Log.Error("enqueue customer upsert failed", "tenant_id", t.ID, "err", err)
}
+20 -9
View File
@@ -64,6 +64,17 @@ func (s *Server) now() time.Time {
return time.Now().UTC()
}
// cloudOnly wraps a handler of a feature that exists only in our cloud
// (sign-up, trial offers and terms, the ERP): 404 on-prem.
func (s *Server) cloudOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.notOnPrem(w) {
return
}
h(w, r)
}
}
func (s *Server) cfg() *config.Config {
if s.Cfg == nil {
return &config.Config{}
@@ -99,14 +110,14 @@ func NewRouter(s *Server) http.Handler {
root.HandleFunc("GET /version", s.version)
// PUBLIC_EXPLICIT: ERPNext webhooks carry no Keycloak token — the body
// is HMAC-signed with ERP_WEBHOOK_SECRET (receiver refuses without it).
root.HandleFunc("POST /v1/internal/erp/webhook", s.erpWebhook)
root.HandleFunc("POST /v1/internal/erp/webhook", s.cloudOnly(s.erpWebhook))
// PUBLIC_EXPLICIT: licence verification keys + heartbeat. The heartbeat
// is authenticated by the licence JWT it carries (offline CLIs hold no
// Keycloak session).
root.HandleFunc("GET /.well-known/licence-keys.json", s.licenceKeys)
// Trial terms (portal#64): public, the same bytes before and after the offer.
root.HandleFunc("GET /v1/legal/trial-terms", s.legalTrialTerms)
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.legalTrialTermsFile)
root.HandleFunc("GET /v1/legal/trial-terms", s.cloudOnly(s.legalTrialTerms))
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.cloudOnly(s.legalTrialTermsFile))
root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat)
// PUBLIC_EXPLICIT: CI licences are authenticated by the tenant API key in
// the Authorization header (scope <product>:licence), checked in the handler.
@@ -145,11 +156,11 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("DELETE /v1/tenants/{id}/capability-requests/{rid}", s.deleteCapabilityRequest)
// Trial signup (portal#64): offer, confirmation/activation, new link; the
// contract documents of a tenant.
mux.HandleFunc("POST /v1/trial-offers", s.createTrialOffer)
mux.HandleFunc("POST /v1/trial-offers/verify", s.verifyTrialOffer)
mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.resendTrialOffer)
mux.HandleFunc("GET /v1/trial-offers/{id}", s.trialOfferStatus)
mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.tenantTrialTermsPDF)
mux.HandleFunc("POST /v1/trial-offers", s.cloudOnly(s.createTrialOffer))
mux.HandleFunc("POST /v1/trial-offers/verify", s.cloudOnly(s.verifyTrialOffer))
mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.cloudOnly(s.resendTrialOffer))
mux.HandleFunc("GET /v1/trial-offers/{id}", s.cloudOnly(s.trialOfferStatus))
mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.cloudOnly(s.tenantTrialTermsPDF))
// Contract documents (AGB, AVV, TOM, Leistungsbeschreibungen): "<doc>.pdf".
mux.HandleFunc("GET /v1/tenants/{id}/contracts/documents/{file}", s.tenantContractDocumentPDF)
// Projekte (0010): the list is a {sub} of tenantSubresource.
@@ -229,7 +240,7 @@ func NewRouter(s *Server) http.Handler {
// Staff administration (portal /admin; group "admin").
mux.HandleFunc("GET /v1/admin/tenants", s.adminListTenants)
mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant)
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.cloudOnly(s.adminExtendTrial))
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/members/{uid}", s.adminPatchMember)
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/members/{uid}", s.adminDeleteMember)
+9
View File
@@ -129,6 +129,15 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat
s.Log.Error("create tenant failed", "err", err)
return nil, kcInvite{}, &apiError{http.StatusInternalServerError, "internal", "create failed"}
}
if s.onPrem() && t.Status == store.StatusTrial {
// No trial on a customer's own node: the workspace starts active.
// (trial_ends_at keeps the store's default; nothing reads it here.)
if t2, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{Status: ptrStr(store.StatusActive)}); err != nil {
s.Log.Error("on-prem: activate new tenant failed", "tenant_id", t.ID, "err", err)
} else {
t = t2
}
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID,
+1 -1
View File
@@ -134,7 +134,7 @@ func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
if preview {
continue
}
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{
if _, err := s.enqueueERP(ctx, store.OutboxItem{
Kind: store.OutboxUsageRecord, TenantID: ev.TenantID,
Payload: map[string]interface{}{"usage_event_id": ev.ID, "idempotency_key": ev.IdempotencyKey, "product": ev.Product,
"metric": ev.Metric, "quantity": ev.Quantity, "occurred_at": ev.OccurredAt.Format(time.RFC3339)},