- 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>
267 lines
10 KiB
Go
267 lines
10 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/buildinfo"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/product"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/secretbox"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
|
|
"git.breakpilot.com/platform/tenant-registry/migrations"
|
|
)
|
|
|
|
func main() {
|
|
logger := slog.New(telemetry.NewLogHandler(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})))
|
|
slog.SetDefault(logger)
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
slog.Error("config load failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
// The committed contract documents are served byte for byte: a PDF that
|
|
// does not match its pinned SHA-256 stops the start.
|
|
if err := contractdocs.Check(); err != nil {
|
|
slog.Error("contract documents do not match their pins", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("contract documents", "released", len(contractdocs.Default().All()), "gate_on", cfg.ContractDocuments)
|
|
|
|
// Traces to SigNoz when OTEL_EXPORTER_OTLP_ENDPOINT is set; every outbound
|
|
// client without its own transport (Keycloak, ERP, LiteLLM, OIDC) goes
|
|
// through the traced default transport.
|
|
shutdownTelemetry, err := telemetry.Setup(context.Background(), telemetry.Info{
|
|
Service: "tenant-registry", Version: buildinfo.Version, Commit: buildinfo.Commit, Env: cfg.Env,
|
|
})
|
|
if err != nil {
|
|
slog.Error("telemetry setup failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
http.DefaultTransport = telemetry.Transport(http.DefaultTransport)
|
|
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
|
|
slog.Info("tracing enabled", "endpoint", os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"))
|
|
}
|
|
|
|
bootCtx, cancelBoot := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancelBoot()
|
|
|
|
var s store.Store
|
|
if cfg.DatabaseURL == "" {
|
|
slog.Warn("DATABASE_URL not set — running with in-memory store (dev only)")
|
|
s = store.NewMemory()
|
|
} else {
|
|
if os.Getenv("MIGRATE_ON_START") == "true" {
|
|
if err := migrations.Up(bootCtx, cfg.DatabaseURL); err != nil {
|
|
slog.Error("MIGRATE_ON_START failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
pg, err := store.NewPostgres(bootCtx, cfg.DatabaseURL)
|
|
if err != nil {
|
|
slog.Error("postgres connect failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
s = pg
|
|
}
|
|
defer s.Close()
|
|
kind := storeKind(s)
|
|
// PRODUCTS / PRODUCT_*_URLS (on-prem: the only source of product URLs).
|
|
if err := store.CheckProductKeys(bootCtx, s, cfg.Products, cfg.LaunchURLs, cfg.ProvisionURLs); err != nil {
|
|
slog.Error("product overrides invalid", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
s = store.WithProductOverrides(s, cfg.CatalogEnv(), cfg.Products, cfg.LaunchURLs, cfg.ProvisionURLs)
|
|
if cfg.OnPrem() {
|
|
var noProvision []string
|
|
for _, k := range cfg.Products {
|
|
if cfg.ProvisionURLs[k] == "" {
|
|
noProvision = append(noProvision, k)
|
|
}
|
|
}
|
|
slog.Info("on-prem mode: no ERP, no trial ladder, no sign-up", "products", cfg.Products, "without_provisioning", noProvision)
|
|
}
|
|
|
|
var kc keycloak.Adapter
|
|
if cfg.KeycloakAdminURL != "" && cfg.KeycloakClientID != "" {
|
|
kc = keycloak.NewHTTPAdapter(keycloak.HTTPConfig{
|
|
BaseURL: cfg.KeycloakAdminURL,
|
|
Realm: cfg.KeycloakRealm,
|
|
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)
|
|
} else {
|
|
slog.Warn("KEYCLOAK_ADMIN_URL not set — using mock adapter (dev only; no real KC writes)")
|
|
kc = keycloak.NewMock()
|
|
}
|
|
|
|
var av *authn.Verifier
|
|
if cfg.AuthEnabled {
|
|
av, err = authn.New(bootCtx, cfg.KeycloakIssuer, cfg.AuthAudience)
|
|
if err != nil {
|
|
// Fail closed: never start an "authenticated" server that
|
|
// cannot actually verify tokens.
|
|
slog.Error("AUTH_CONFIG_INCOMPLETE — AUTH_ENABLED=true but verifier init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("api auth enabled", "issuer", cfg.KeycloakIssuer, "audience", cfg.AuthAudience)
|
|
} else {
|
|
slog.Warn("AUTH_ENABLED=false — API is unauthenticated (dev only)")
|
|
}
|
|
|
|
// Downstream product provisioning. Wired only when PRODUCT_API_URL is set;
|
|
// otherwise a no-op so an unconfigured deployment still creates tenants.
|
|
// The product's gate is not yet enforcing, so no token is attached today —
|
|
// AuthHeaderFunc is the seam for when it is.
|
|
var pv product.Provisioner = product.NoopProvisioner{}
|
|
if cfg.ProductAPIURL != "" {
|
|
pv = product.NewHTTPProvisioner(cfg.ProductAPIURL, cfg.ProductAPIPath, nil, cfg.ProductTimeout)
|
|
slog.Info("product provisioner configured", "url", cfg.ProductAPIURL, "path", cfg.ProductAPIPath)
|
|
} else {
|
|
slog.Warn("PRODUCT_API_URL not set — product tenant provisioning disabled (anchors may diverge)")
|
|
}
|
|
|
|
authz := server.ParseAuthzRules(cfg.AuthzRules)
|
|
server.LogAuthz(logger, authz)
|
|
|
|
// ERP link (M-MIG-7). Staging: erpnext-mock-stage; prod: erp.breakpilot.com.
|
|
erpClient := erp.New(erp.Config{BaseURL: cfg.ErpBaseURL, APIKey: cfg.ErpAPIKey, APISecret: cfg.ErpAPISecret, LeadDoctype: cfg.ErpLeadDoctype})
|
|
if erpClient.Enabled() {
|
|
slog.Info("erp client configured", "url", cfg.ErpBaseURL, "lead_doctype", cfg.ErpLeadDoctype)
|
|
} else {
|
|
slog.Warn("ERP_BASE_URL not set — ERP outbox idle, reconcile runs ladder steps only")
|
|
}
|
|
if cfg.ErpWebhookSecret == "" {
|
|
slog.Warn("ERP_WEBHOOK_SECRET not set — POST /v1/internal/erp/webhook is disabled")
|
|
}
|
|
signer, err := licence.NewSigner(cfg.LicenceSigningKey, cfg.LicenceIssuer)
|
|
if err != nil {
|
|
slog.Error("licence signer init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
if signer.Ephemeral {
|
|
slog.Warn("LICENCE_SIGNING_KEY not set — ephemeral licence key (dev only; licences die with the process)", "kid", signer.KID())
|
|
} else {
|
|
slog.Info("licence signer configured", "kid", signer.KID(), "issuer", signer.Issuer())
|
|
}
|
|
|
|
secrets, err := secretbox.New(cfg.SecretsEncryptionKey)
|
|
if err != nil {
|
|
slog.Error("secrets encryption key invalid", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
if !secrets.Enabled() {
|
|
slog.Warn("SECRETS_ENCRYPTION_KEY not set — a reused Werkpilot CI licence cannot hand out its LiteLLM key again, and Managed Git users are not counted (no admin tokens)")
|
|
}
|
|
|
|
// LiteLLM virtual keys for Werkpilot licences (D6).
|
|
llmKeys := llmkeys.New(llmkeys.Config{BaseURL: cfg.LiteLLMBaseURL, MasterKey: cfg.LiteLLMMasterKey, Models: cfg.LiteLLMModels,
|
|
BudgetTrial: cfg.LiteLLMBudgetTrial, BudgetDefault: cfg.LiteLLMBudgetDefault})
|
|
if llmKeys.Enabled() {
|
|
slog.Info("litellm key provisioning configured", "url", llmKeys.BaseURL(), "models", llmKeys.Models(),
|
|
"budget_trial_usd", llmKeys.Budget(true), "budget_default_usd", llmKeys.Budget(false), "budget_duration", llmKeys.BudgetDuration())
|
|
} else {
|
|
slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key")
|
|
}
|
|
|
|
var objects storage.Objects
|
|
docCfg := storage.Config{Endpoint: cfg.DocumentsS3Endpoint, Region: cfg.DocumentsS3Region, Bucket: cfg.DocumentsS3Bucket,
|
|
AccessKey: cfg.DocumentsS3AccessKey, SecretKey: cfg.DocumentsS3SecretKey}
|
|
if docCfg.Configured() {
|
|
sctx, scancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
s3, serr := storage.NewS3(sctx, docCfg)
|
|
scancel()
|
|
if serr != nil {
|
|
// Documents are one feature; the registry keeps serving everything else.
|
|
logger.Error("document storage unavailable; document routes answer 503", "err", serr)
|
|
} else {
|
|
objects = s3
|
|
logger.Info("document storage ready", "bucket", docCfg.Bucket)
|
|
}
|
|
} else {
|
|
logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503")
|
|
}
|
|
var mailer mail.Sender
|
|
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName, TLS: cfg.SMTPTLS}); mc.Configured() {
|
|
mailer = &mail.SMTP{Cfg: mc}
|
|
}
|
|
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Secrets: secrets, Objects: objects, Mail: mailer}
|
|
handler := server.NewRouter(app)
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: handler,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
// Above orca-proxy's upstream pool idle timeout (90 s): with a shorter
|
|
// value the proxy reuses connections the server is closing and answers
|
|
// 502 "connection closed before message completed".
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
go app.RunOutbox(ctx, cfg.ErpOutboxInterval)
|
|
go app.RunReconcile(ctx, cfg.ErpReconcileEvery)
|
|
go app.RunMail(ctx, 20*time.Second)
|
|
// Module users (t81): once per Europe/Berlin day.
|
|
go app.RunModuleUserCount(ctx, 15*time.Minute)
|
|
|
|
go func() {
|
|
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", kind)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
slog.Error("server crashed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
slog.Info("shutdown requested")
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
slog.Error("shutdown failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
flushCtx, cancelFlush := context.WithTimeout(context.Background(), telemetry.ShutdownTimeout)
|
|
defer cancelFlush()
|
|
if err := shutdownTelemetry(flushCtx); err != nil {
|
|
slog.Warn("telemetry flush failed", "err", err)
|
|
}
|
|
slog.Info("bye")
|
|
}
|
|
|
|
func storeKind(s store.Store) string {
|
|
switch s.(type) {
|
|
case *store.Memory:
|
|
return "memory"
|
|
case *store.Postgres:
|
|
return "postgres"
|
|
default:
|
|
return "unknown"
|
|
}
|
|
}
|