Files
tenant-registry/internal/config/config.go
sharang 69c15be333
ci / shared (push) Successful in 12s
ci / test (push) Successful in 9m8s
ci / image (push) Successful in 36s
feat(onprem): APP_ENV=onprem with directory users and installation mail (#146)
2026-11-20 16:31:11 +00:00

385 lines
14 KiB
Go

package config
import (
"fmt"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Env string // dev | stage | prod | onprem
Addr string // listen address, e.g. ":8090"
KeycloakIssuer string // e.g. http://localhost:8080/realms/breakpilot-dev
DatabaseURL string // postgres DSN (unused in skeleton; in-memory store)
// Keycloak Admin API — only used if KeycloakAdminURL is set. Empty
// values disable the adapter and tenant-registry falls back to the
// Mock (dev convenience).
KeycloakAdminURL string
KeycloakRealm string
KeycloakClientID string
KeycloakClientSecret string
KeycloakTimeout time.Duration
// Inbound API auth (RBAC Phase 1). With AuthEnabled the server refuses
// to start unless OIDC discovery against KeycloakIssuer succeeds, and
// every non-health route requires a bearer token whose audience
// contains AuthAudience.
AuthEnabled bool
AuthAudience string
// Downstream product provisioning. When ProductAPIURL is set, tenant
// creation also provisions the tenant in the product's own database with
// the SAME registry UUID, so both anchors agree. Empty ⇒ no-op adapter.
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
// ERP link (M-MIG-7). ErpBaseURL empty ⇒ outbox accumulates, reconcile
// idle (dev). Staging points at erpnext-mock-stage.
ErpBaseURL string
ErpAPIKey string
ErpAPISecret string
ErpLeadDoctype string
ErpWebhookSecret string // HMAC for POST /v1/internal/erp/webhook; empty ⇒ receiver disabled
ErpOutboxInterval time.Duration
ErpReconcileEvery time.Duration
// Ladder timing (days). Non-payment counts from the Mahnung (ERPNext
// Dunning), not the due date (AGB § 10): restricted RestrictAfterDays
// after the Mahnung, halted HaltAfterDays-RestrictAfterDays after the
// restriction (so HaltAfterDays after a Mahnung seen on time). An
// expired trial is read-only for the same spacing, then halted. Halted →
// archived after ExportWindowDays.
RestrictAfterDays int
HaltAfterDays int
ExportWindowDays int
// CLI licences (decision 13). Empty key ⇒ ephemeral (dev only, logged).
LicenceSigningKey string
// SecretsEncryptionKey — base64, 32 bytes; seals secrets the registry
// hands out again (CI licences' LiteLLM keys). Empty ⇒ not stored.
SecretsEncryptionKey string
LicenceIssuer string
LicenceTTLDays int
// LiteLLM virtual keys for Werkpilot licences (D6). Empty master key ⇒
// feature off, grants carry no LLM key. Budgets are USD per 30 days.
// Tenant documents (F2): S3-compatible bucket. Unset ⇒ document routes 503.
DocumentsS3Endpoint string
DocumentsS3Region string
DocumentsS3Bucket string
DocumentsS3AccessKey string
DocumentsS3SecretKey string
// DocumentsMaxBytes caps one upload (default 200 MiB).
DocumentsMaxBytes int64
// StoreImportMaxBytes caps one document-store bundle import (default 2 GiB).
StoreImportMaxBytes int64
// ContractDocuments (CONTRACT_DOCUMENTS "on"/"off", default off) releases
// the contract documents (AGB, AVV, TOM, Leistungsbeschreibungen) in the
// Vertragsunterlagen. Off: the overview lists none and their PDF routes
// answer 404.
ContractDocuments bool
// Platform mail (F3). SMTPHost empty ⇒ notifications queue up unsent.
SMTPHost string
SMTPPort int
SMTPUser string
SMTPPassword string
MailFrom string
MailFromName string
// Legal pages and whom to ask, under every mail. Cloud: empty means our
// imprint and privacy notice (mail.CloudImprint/CloudPrivacy). On-prem:
// the customer's own pages, each left out when empty; MailContact names
// their IT (on-prem only, the cloud signature carries our contact).
LegalImprintURL string
LegalPrivacyURL string
MailContact string
// PortalURL is the portal's public origin, for links in mail.
PortalURL string
// PruefwerkPlatformURL / PruefwerkURL override where the registry reads a
// project's Prüfwerk objects (…/api/v1/platform) and links them (the
// dashboard). Unset: derived from the catalog for this environment.
PruefwerkPlatformURL string
PruefwerkURL string
// SMTPTLS is how the relay connection is secured: "starttls", "tls"
// (implicit, port 465) or "none" (a plain internal relay; no AUTH then).
// Unset: "tls" on port 465, else "starttls".
SMTPTLS string
// Products (PRODUCTS, comma list) limits the catalog to these keys; a
// listed product is offered even if its row is disabled. Unset: the
// catalog's own enabled flags. Required on-prem: the package decides
// what ships.
Products []string
// LaunchURLs / ProvisionURLs (PRODUCT_LAUNCH_URLS, PRODUCT_PROVISION_URLS,
// "key=url,key=url") override the per-environment URLs seeded in the
// catalog. On-prem has no seeded URLs, so a product's tile and its
// provisioning come only from here. A provision URL carries "{id}".
LaunchURLs map[string]string
ProvisionURLs map[string]string
LiteLLMBaseURL string
LiteLLMMasterKey string
LiteLLMModels []string
LiteLLMBudgetTrial float64
LiteLLMBudgetDefault float64
}
func Load() (*Config, error) {
env := getenv("APP_ENV", "dev")
if env != "dev" && env != "stage" && env != "prod" && env != EnvOnPrem {
return nil, fmt.Errorf("invalid APP_ENV %q", env)
}
launch, err := geturlmap("PRODUCT_LAUNCH_URLS", false)
if err != nil {
return nil, err
}
provision, err := geturlmap("PRODUCT_PROVISION_URLS", true)
if err != nil {
return nil, err
}
smtpPort := getint("SMTP_PORT", 587)
smtpTLS := strings.ToLower(os.Getenv("SMTP_TLS"))
switch smtpTLS {
case "":
smtpTLS = "starttls"
if smtpPort == 465 {
smtpTLS = "tls"
}
case "starttls", "tls", "none":
default:
return nil, fmt.Errorf("invalid SMTP_TLS %q (starttls, tls or none)", smtpTLS)
}
if smtpTLS == "none" && os.Getenv("SMTP_USER") != "" {
return nil, fmt.Errorf("SMTP_TLS=none with SMTP_USER set: credentials are never sent unencrypted")
}
c := &Config{
Env: env,
// :8090 — Keycloak owns :8080 in the dev stack.
Addr: getenv("ADDR", ":8090"),
KeycloakIssuer: getenv("KEYCLOAK_ISSUER", "http://localhost:8080/realms/breakpilot-dev"),
DatabaseURL: os.Getenv("DATABASE_URL"),
KeycloakAdminURL: os.Getenv("KEYCLOAK_ADMIN_URL"),
KeycloakRealm: getenv("KEYCLOAK_REALM", "breakpilot-dev"),
KeycloakClientID: os.Getenv("KEYCLOAK_CLIENT_ID"),
KeycloakClientSecret: os.Getenv("KEYCLOAK_CLIENT_SECRET"),
KeycloakTimeout: 10 * time.Second,
AuthEnabled: getenv("AUTH_ENABLED", "false") == "true",
AuthAudience: getenv("AUTH_EXPECTED_AUDIENCE", "tenant-registry"),
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"),
ErpBaseURL: os.Getenv("ERP_BASE_URL"),
ErpAPIKey: os.Getenv("ERP_API_KEY"),
ErpAPISecret: os.Getenv("ERP_API_SECRET"),
ErpLeadDoctype: getenv("ERP_LEAD_DOCTYPE", "Lead"),
ErpWebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"),
ErpOutboxInterval: getduration("ERP_OUTBOX_INTERVAL", 15*time.Second),
ErpReconcileEvery: getduration("ERP_RECONCILE_INTERVAL", 15*time.Minute),
RestrictAfterDays: getint("ERP_RESTRICT_AFTER_DAYS", 14),
HaltAfterDays: getint("ERP_HALT_AFTER_DAYS", 28),
ExportWindowDays: getint("ERP_EXPORT_WINDOW_DAYS", 30),
LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"),
SecretsEncryptionKey: os.Getenv("SECRETS_ENCRYPTION_KEY"),
LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"),
LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30),
DocumentsS3Endpoint: os.Getenv("DOCUMENTS_S3_ENDPOINT"),
DocumentsS3Region: getenv("DOCUMENTS_S3_REGION", "nbg1"),
DocumentsS3Bucket: os.Getenv("DOCUMENTS_S3_BUCKET"),
DocumentsS3AccessKey: os.Getenv("DOCUMENTS_S3_ACCESS_KEY"),
DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"),
DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20,
ContractDocuments: getenv("CONTRACT_DOCUMENTS", "off") == "on",
StoreImportMaxBytes: int64(getint("STORE_IMPORT_MAX_MB", 2048)) << 20,
SMTPHost: os.Getenv("SMTP_HOST"),
SMTPPort: smtpPort,
SMTPTLS: smtpTLS,
SMTPUser: os.Getenv("SMTP_USER"),
SMTPPassword: os.Getenv("SMTP_PASSWORD"),
MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"),
MailFromName: getenv("MAIL_FROM_NAME", "Breakpilot"),
LegalImprintURL: os.Getenv("LEGAL_IMPRINT_URL"),
LegalPrivacyURL: os.Getenv("LEGAL_PRIVACY_URL"),
MailContact: os.Getenv("MAIL_CONTACT"),
PortalURL: getenv("PORTAL_URL", "https://app.breakpilot.com"),
PruefwerkPlatformURL: os.Getenv("PRUEFWERK_PLATFORM_URL"),
PruefwerkURL: os.Getenv("PRUEFWERK_URL"),
LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"),
LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"),
LiteLLMModels: getlist("LITELLM_MODELS", []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b", "Qwen3.8-27B"}),
LiteLLMBudgetTrial: getfloat("LITELLM_BUDGET_TRIAL", 5),
LiteLLMBudgetDefault: getfloat("LITELLM_BUDGET_DEFAULT", 50),
Products: getlist("PRODUCTS", nil),
LaunchURLs: launch,
ProvisionURLs: provision,
}
if env == EnvOnPrem {
if err := c.checkOnPrem(); err != nil {
return nil, err
}
}
return c, nil
}
// EnvOnPrem is a registry on a customer's own node: no ERP, no trial ladder,
// no sign-up, and no default that points at a Breakpilot host.
const EnvOnPrem = "onprem"
// CatalogEnv is the key of the catalog's per-environment URLs. "dev" reads
// the stage URLs so a laptop portal links somewhere real.
func (c *Config) CatalogEnv() string {
if c == nil || c.Env == "" || c.Env == "dev" {
return "stage"
}
return c.Env
}
// OnPrem reports whether this registry runs on a customer's node.
func (c *Config) OnPrem() bool { return c != nil && c.Env == EnvOnPrem }
// checkOnPrem refuses to start an on-prem registry whose values file leaves
// something to a cloud or dev default: an open API, a licence key that dies
// with the process, or a link, sender or gateway on a Breakpilot host.
func (c *Config) checkOnPrem() error {
var missing []string
need := func(key string) {
if os.Getenv(key) == "" {
missing = append(missing, key)
}
}
for _, k := range []string{"KEYCLOAK_ISSUER", "KEYCLOAK_REALM", "KEYCLOAK_ADMIN_URL", "KEYCLOAK_CLIENT_ID", "KEYCLOAK_CLIENT_SECRET", "DATABASE_URL", "AUTHZ_RULES",
"LICENCE_SIGNING_KEY", "PORTAL_URL", "INVITE_REDIRECT_URI", "INVITE_CLIENT_ID", "MAIL_FROM", "PRODUCTS"} {
need(k)
}
if c.LiteLLMMasterKey != "" {
need("LITELLM_BASE_URL")
}
if len(missing) > 0 {
return fmt.Errorf("APP_ENV=onprem needs %s", strings.Join(missing, ", "))
}
if !c.AuthEnabled {
return fmt.Errorf("APP_ENV=onprem needs AUTH_ENABLED=true")
}
if c.ErpBaseURL != "" || c.ErpWebhookSecret != "" {
return fmt.Errorf("APP_ENV=onprem has no ERP: unset ERP_BASE_URL and ERP_WEBHOOK_SECRET")
}
if c.ContractDocuments {
return fmt.Errorf("APP_ENV=onprem has no contract documents: unset CONTRACT_DOCUMENTS")
}
// Links and the sender in mail and invitations are the customer's.
for _, k := range []string{"MAIL_FROM", "PORTAL_URL", "INVITE_REDIRECT_URI", "LEGAL_IMPRINT_URL", "LEGAL_PRIVACY_URL"} {
if strings.Contains(strings.ToLower(os.Getenv(k)), "breakpilot.com") {
return fmt.Errorf("APP_ENV=onprem: %s points at breakpilot.com; use the installation's own", k)
}
}
for _, k := range c.Products {
if c.LaunchURLs[k] == "" {
return fmt.Errorf("APP_ENV=onprem: product %q has no entry in PRODUCT_LAUNCH_URLS", k)
}
}
return nil
}
// geturlmap parses "key=url,key=url". Each URL must be absolute http(s);
// with needID it must also contain the "{id}" placeholder.
func geturlmap(key string, needID bool) (map[string]string, error) {
out := map[string]string{}
for _, part := range getlist(key, nil) {
k, v, ok := strings.Cut(part, "=")
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
if !ok || k == "" || v == "" {
return nil, fmt.Errorf("%s: %q is not key=url", key, part)
}
u, err := url.Parse(v)
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
return nil, fmt.Errorf("%s: %s: not an absolute http(s) URL", key, k)
}
if needID && !strings.Contains(v, "{id}") {
return nil, fmt.Errorf("%s: %s: the URL needs the {id} placeholder", key, k)
}
if _, dup := out[k]; dup {
return nil, fmt.Errorf("%s: %s given twice", key, k)
}
out[k] = v
}
return out, nil
}
func getfloat(key string, fallback float64) float64 {
if v := os.Getenv(key); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
}
return fallback
}
// getlist parses a comma-separated list, trimming blanks; empty ⇒ fallback.
func getlist(key string, fallback []string) []string {
v := os.Getenv(key)
if v == "" {
return fallback
}
var out []string
for _, s := range strings.Split(v, ",") {
if s = strings.TrimSpace(s); s != "" {
out = append(out, s)
}
}
if len(out) == 0 {
return fallback
}
return out
}
func getint(key string, fallback int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return fallback
}
func getduration(key string, fallback time.Duration) time.Duration {
if v := os.Getenv(key); v != "" {
if d, err := time.ParseDuration(v); err == nil {
return d
}
}
return fallback
}
func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}