diff --git a/README.md b/README.md index 96cbbf1..fc6d47f 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Env vars (override at the shell): | Var | Default | Purpose | |---|---|---| -| `APP_ENV` | `dev` | one of `dev`, `stage`, `prod` | +| `APP_ENV` | `dev` | one of `dev`, `stage`, `prod`, `onprem` (see [On-prem](#on-prem)) | | `ADDR` | `:8090` | listen address (avoids Keycloak's :8080) | | `KEYCLOAK_ISSUER` | `http://localhost:8080/realms/breakpilot-dev` | OIDC issuer URL (the JWT signer) | | `DATABASE_URL` | empty (in-memory store fallback) | Postgres DSN; service uses Memory when empty | @@ -50,6 +50,9 @@ Env vars (override at the shell): | `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing | | `DOCUMENTS_MAX_MB` | `200` | Upload limit per document | | `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) | +| `SMTP_TLS` | `tls` on port 465, else `starttls` | `starttls`, `tls` or `none` (a plain relay inside the customer's network; refused together with `SMTP_USER`) | +| `PRODUCTS` | empty (the catalog's own enabled flags) | Comma list of the products this installation offers; a listed product is offered even if its row is disabled | +| `PRODUCT_LAUNCH_URLS` / `PRODUCT_PROVISION_URLS` | empty (the URLs seeded per environment) | `key=url,key=url` overrides; a provision URL carries `{id}`. Checked at start | | `MAIL_FROM` / `MAIL_FROM_NAME` | `noreply@breakpilot.com` / `BreakPilot` | Sender of platform mail | | `PORTAL_URL` | `https://app.breakpilot.com` | Portal origin for links in mail | | `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) | @@ -109,6 +112,16 @@ Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary: State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec. +## On-prem + +`APP_ENV=onprem` runs the registry on a customer's own node (the package in `platform/onprem`). Differences from the cloud: + +- No ERP: the outbox takes nothing, the ERP webhook is off, and `ERP_BASE_URL` / `ERP_WEBHOOK_SECRET` must be empty. +- No trial: a new workspace starts `active`, and the ladder never escalates by time (the licence is the contract). +- No sign-up and no sales requests: the trial-offer, trial-terms, catalog request, trial request and admin trial routes answer 404 `not_available`. +- Products and URLs only from `PRODUCTS` and `PRODUCT_*_URLS`. The seeded `stage`/`prod` URLs are never used, so provisioning never reaches a Breakpilot host (the test install in `platform/onprem` checks all outbound traffic). Each listed product needs a launch URL; an unknown key stops the start. The catalog offers no trials. +- No cloud defaults: the registry refuses to start without `AUTH_ENABLED=true`, `AUTHZ_RULES`, `LICENCE_SIGNING_KEY`, `DATABASE_URL`, the Keycloak admin settings, `PORTAL_URL`, `INVITE_CLIENT_ID`, `INVITE_REDIRECT_URI`, `MAIL_FROM` and `PRODUCTS`, and without `LITELLM_BASE_URL` when `LITELLM_MASTER_KEY` is set. Contract documents stay off. + ## ERP link (M-MIG-7) ERPNext is the commercial authority; the registry mirrors it and moves tenants diff --git a/cmd/server/main.go b/cmd/server/main.go index fbc5ea3..bf54457 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -82,6 +82,22 @@ func main() { 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 != "" { @@ -189,7 +205,7 @@ func main() { 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}); mc.Configured() { + 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} @@ -215,7 +231,7 @@ func main() { go app.RunModuleUserCount(ctx, 15*time.Minute) go func() { - slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s)) + 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) diff --git a/internal/config/config.go b/internal/config/config.go index d8581b4..6579c30 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "net/url" "os" "strconv" "strings" @@ -9,7 +10,7 @@ import ( ) type Config struct { - Env string // dev | stage | prod + 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) @@ -106,6 +107,23 @@ type Config struct { 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 @@ -115,10 +133,33 @@ type Config struct { func Load() (*Config, error) { env := getenv("APP_ENV", "dev") - if env != "dev" && env != "stage" && env != "prod" { + if env != "dev" && env != "stage" && env != "prod" && env != EnvOnPrem { return nil, fmt.Errorf("invalid APP_ENV %q", env) } - return &Config{ + 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"), @@ -168,7 +209,8 @@ func Load() (*Config, error) { StoreImportMaxBytes: int64(getint("STORE_IMPORT_MAX_MB", 2048)) << 20, SMTPHost: os.Getenv("SMTP_HOST"), - SMTPPort: getint("SMTP_PORT", 587), + SMTPPort: smtpPort, + SMTPTLS: smtpTLS, SMTPUser: os.Getenv("SMTP_USER"), SMTPPassword: os.Getenv("SMTP_PASSWORD"), MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"), @@ -182,7 +224,95 @@ func Load() (*Config, error) { 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), - }, nil + + 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") + } + 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 { diff --git a/internal/config/onprem_test.go b/internal/config/onprem_test.go new file mode 100644 index 0000000..0055150 --- /dev/null +++ b/internal/config/onprem_test.go @@ -0,0 +1,151 @@ +package config + +import ( + "strings" + "testing" +) + +// onPremEnv is a complete on-prem values set (test names only). +func onPremEnv(t *testing.T) { + t.Helper() + for k, v := range map[string]string{ + "APP_ENV": "onprem", + "KEYCLOAK_ISSUER": "https://auth.onprem.test/realms/breakpilot", + "KEYCLOAK_REALM": "breakpilot", + "KEYCLOAK_ADMIN_URL": "https://auth.onprem.test", + "KEYCLOAK_CLIENT_ID": "tenant-registry", + "KEYCLOAK_CLIENT_SECRET": "x", + "DATABASE_URL": "postgres://registry@postgres/registry", + "AUTH_ENABLED": "true", + "AUTHZ_RULES": "portal=*", + "LICENCE_SIGNING_KEY": "x", + "PORTAL_URL": "https://app.onprem.test", + "INVITE_REDIRECT_URI": "https://app.onprem.test/onboard", + "INVITE_CLIENT_ID": "portal", + "MAIL_FROM": "breakpilot@onprem.test", + "PRODUCTS": "pruefwerk,werkpilot", + "PRODUCT_LAUNCH_URLS": "pruefwerk=https://pruefwerk.onprem.test,werkpilot=https://docs.onprem.test/werkpilot", + "PRODUCT_PROVISION_URLS": "pruefwerk=https://pruefwerk.onprem.test/api/v1/platform/tenants/{id}/provision", + "SMTP_HOST": "mail.onprem.test", + "SMTP_PORT": "25", + "SMTP_TLS": "none", + } { + t.Setenv(k, v) + } + for _, k := range []string{"ERP_BASE_URL", "ERP_WEBHOOK_SECRET", "CONTRACT_DOCUMENTS", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL", "SMTP_USER"} { + t.Setenv(k, "") + } +} + +func TestLoad_onPremComplete(t *testing.T) { + onPremEnv(t) + c, err := Load() + if err != nil { + t.Fatal(err) + } + if !c.OnPrem() || c.CatalogEnv() != "onprem" { + t.Errorf("OnPrem=%v CatalogEnv=%q", c.OnPrem(), c.CatalogEnv()) + } + if c.SMTPTLS != "none" || c.SMTPPort != 25 { + t.Errorf("smtp = %s:%d", c.SMTPTLS, c.SMTPPort) + } + if c.ProvisionURLs["pruefwerk"] == "" || c.LaunchURLs["werkpilot"] == "" || len(c.Products) != 2 { + t.Errorf("products %v launch %v provision %v", c.Products, c.LaunchURLs, c.ProvisionURLs) + } +} + +func TestLoad_onPremRefusesCloudDefaults(t *testing.T) { + for _, c := range []struct { + name, key, value, want string + }{ + {"no portal URL", "PORTAL_URL", "", "PORTAL_URL"}, + {"no invite redirect", "INVITE_REDIRECT_URI", "", "INVITE_REDIRECT_URI"}, + {"no sender", "MAIL_FROM", "", "MAIL_FROM"}, + {"no licence key", "LICENCE_SIGNING_KEY", "", "LICENCE_SIGNING_KEY"}, + {"no authz rules", "AUTHZ_RULES", "", "AUTHZ_RULES"}, + {"no product list", "PRODUCTS", "", "PRODUCTS"}, + {"no database", "DATABASE_URL", "", "DATABASE_URL"}, + {"auth off", "AUTH_ENABLED", "false", "AUTH_ENABLED"}, + {"an ERP", "ERP_BASE_URL", "https://erp.onprem.test", "no ERP"}, + {"contract documents", "CONTRACT_DOCUMENTS", "on", "contract documents"}, + {"LLM key without gateway", "LITELLM_MASTER_KEY", "x", "LITELLM_BASE_URL"}, + {"product without tile", "PRODUCTS", "pruefwerk,firmwerk", `"firmwerk"`}, + } { + t.Run(c.name, func(t *testing.T) { + onPremEnv(t) + t.Setenv(c.key, c.value) + _, err := Load() + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("err = %v, want one naming %s", err, c.want) + } + }) + } +} + +func TestLoad_productURLsAreChecked(t *testing.T) { + for _, c := range []struct{ key, value, want string }{ + {"PRODUCT_LAUNCH_URLS", "pruefwerk", "not key=url"}, + {"PRODUCT_LAUNCH_URLS", "pruefwerk=pruefwerk.onprem.test", "absolute"}, + {"PRODUCT_LAUNCH_URLS", "pruefwerk=https://a.onprem.test,pruefwerk=https://b.onprem.test", "twice"}, + {"PRODUCT_PROVISION_URLS", "pruefwerk=https://pruefwerk.onprem.test/provision", "{id}"}, + } { + t.Run(c.value, func(t *testing.T) { + t.Setenv("APP_ENV", "stage") + t.Setenv("PRODUCT_LAUNCH_URLS", "") + t.Setenv("PRODUCT_PROVISION_URLS", "") + t.Setenv(c.key, c.value) + _, err := Load() + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("err = %v, want %q", err, c.want) + } + }) + } +} + +// The cloud binary is the same: without the new variables nothing changes. +func TestLoad_cloudUnchangedWithoutTheNewVariables(t *testing.T) { + for _, env := range []string{"stage", "prod"} { + t.Run(env, func(t *testing.T) { + t.Setenv("APP_ENV", env) + for _, k := range []string{"PRODUCTS", "PRODUCT_LAUNCH_URLS", "PRODUCT_PROVISION_URLS", "SMTP_TLS", "SMTP_PORT", "SMTP_USER", + "PORTAL_URL", "MAIL_FROM", "INVITE_REDIRECT_URI", "LITELLM_BASE_URL", "AUTH_ENABLED", "LICENCE_SIGNING_KEY"} { + t.Setenv(k, "") + } + c, err := Load() + if err != nil { + t.Fatal(err) + } + if c.OnPrem() || c.CatalogEnv() != env { + t.Errorf("OnPrem=%v CatalogEnv=%q", c.OnPrem(), c.CatalogEnv()) + } + if c.Products != nil || len(c.LaunchURLs) != 0 || len(c.ProvisionURLs) != 0 { + t.Errorf("overrides set: %v %v %v", c.Products, c.LaunchURLs, c.ProvisionURLs) + } + if c.SMTPTLS != "starttls" || c.SMTPPort != 587 { + t.Errorf("smtp = %s:%d", c.SMTPTLS, c.SMTPPort) + } + if c.PortalURL != "https://app.breakpilot.com" || c.MailFrom != "noreply@breakpilot.com" { + t.Errorf("cloud defaults changed: %s %s", c.PortalURL, c.MailFrom) + } + }) + } +} + +func TestLoad_smtpTLS(t *testing.T) { + t.Setenv("APP_ENV", "stage") + t.Setenv("SMTP_USER", "") + t.Setenv("SMTP_TLS", "") + t.Setenv("SMTP_PORT", "465") + if c, err := Load(); err != nil || c.SMTPTLS != "tls" { + t.Errorf("port 465: %v %v", c, err) + } + t.Setenv("SMTP_TLS", "ssl") + if _, err := Load(); err == nil { + t.Error("SMTP_TLS=ssl accepted") + } + t.Setenv("SMTP_TLS", "none") + t.Setenv("SMTP_USER", "relay") + if _, err := Load(); err == nil || !strings.Contains(err.Error(), "unencrypted") { + t.Errorf("none + user: %v", err) + } +} diff --git a/internal/mail/mail.go b/internal/mail/mail.go index 7fb07aa..d54ee72 100644 --- a/internal/mail/mail.go +++ b/internal/mail/mail.go @@ -50,12 +50,26 @@ type Config struct { Password string From string // noreply@breakpilot.com FromName string // BreakPilot + // TLS: "starttls", "tls" (implicit) or "none" (plain internal relay, no + // AUTH). Empty: "tls" on port 465, else "starttls". + TLS string +} + +func (c Config) tlsMode() string { + switch { + case c.TLS != "": + return c.TLS + case c.Port == 465: + return "tls" + } + return "starttls" } // Configured reports whether mail can be sent. func (c Config) Configured() bool { return c.Host != "" && c.From != "" } -// SMTP sends through a relay with STARTTLS (or implicit TLS on 465). +// SMTP sends through a relay with STARTTLS, implicit TLS, or (TLS "none", +// on-prem relays inside the customer's network) in plain text. type SMTP struct { Cfg Config Timeout time.Duration @@ -71,7 +85,8 @@ func (s *SMTP) Send(ctx context.Context, m Message) error { var conn net.Conn var err error tlsCfg := &tls.Config{ServerName: s.Cfg.Host, MinVersion: tls.VersionTLS12} - if s.Cfg.Port == 465 { + mode := s.Cfg.tlsMode() + if mode == "tls" { conn, err = tls.DialWithDialer(&d, "tcp", addr, tlsCfg) } else { conn, err = d.DialContext(ctx, "tcp", addr) @@ -86,7 +101,7 @@ func (s *SMTP) Send(ctx context.Context, m Message) error { return fmt.Errorf("mail: hello: %w", err) } defer func() { _ = c.Close() }() - if s.Cfg.Port != 465 { + if mode == "starttls" { if ok, _ := c.Extension("STARTTLS"); !ok { return errors.New("mail: relay does not offer STARTTLS") } @@ -95,6 +110,9 @@ func (s *SMTP) Send(ctx context.Context, m Message) error { } } if s.Cfg.User != "" { + if mode == "none" { + return errors.New("mail: no AUTH over an unencrypted connection") + } if err := c.Auth(smtp.PlainAuth("", s.Cfg.User, s.Cfg.Password, s.Cfg.Host)); err != nil { return fmt.Errorf("mail: auth: %w", err) } diff --git a/internal/mail/plain_test.go b/internal/mail/plain_test.go new file mode 100644 index 0000000..63e4701 --- /dev/null +++ b/internal/mail/plain_test.go @@ -0,0 +1,101 @@ +package mail + +import ( + "bufio" + "context" + "net" + "strconv" + "strings" + "testing" +) + +// plainRelay is a minimal SMTP server without STARTTLS (an internal relay on +// port 25). It records the commands it saw. +func plainRelay(t *testing.T) (host string, port int, cmds chan string) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + cmds = make(chan string, 64) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + r := bufio.NewReader(conn) + say := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) } + say("220 relay.onprem.test ESMTP") + data := false + for { + line, err := r.ReadString('\n') + if err != nil { + return + } + line = strings.TrimRight(line, "\r\n") + if data { + if line == "." { + data = false + say("250 queued") + } + continue + } + verb := strings.ToUpper(strings.SplitN(line, " ", 2)[0]) + cmds <- verb + switch verb { + case "EHLO", "HELO": + say("250-relay.onprem.test") + say("250 8BITMIME") + case "MAIL", "RCPT": + say("250 ok") + case "DATA": + data = true + say("354 go ahead") + case "QUIT": + say("221 bye") + return + default: + say("502 not implemented") + } + } + }() + h, p, _ := net.SplitHostPort(ln.Addr().String()) + port, _ = strconv.Atoi(p) + return h, port, cmds +} + +func TestSMTP_plainRelay(t *testing.T) { + host, port, cmds := plainRelay(t) + s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test", TLS: "none"}} + if err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi", HTML: "
hi
"}); err != nil { + t.Fatal(err) + } + close(cmds) + var seen []string + for c := range cmds { + seen = append(seen, c) + } + if got := strings.Join(seen, " "); got != "EHLO MAIL RCPT DATA QUIT" { + t.Errorf("commands = %s", got) + } +} + +func TestSMTP_starttlsStillRequiredByDefault(t *testing.T) { + host, port, _ := plainRelay(t) + s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test"}} + err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi"}) + if err == nil || !strings.Contains(err.Error(), "STARTTLS") { + t.Errorf("err = %v, want the STARTTLS refusal", err) + } +} + +func TestSMTP_noAuthInPlainText(t *testing.T) { + host, port, _ := plainRelay(t) + s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test", TLS: "none", User: "u", Password: "p"}} + err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi"}) + if err == nil || !strings.Contains(err.Error(), "unencrypted") { + t.Errorf("err = %v, want the plain-text AUTH refusal", err) + } +} diff --git a/internal/server/catalog.go b/internal/server/catalog.go index 8f1c79b..096bc7b 100644 --- a/internal/server/catalog.go +++ b/internal/server/catalog.go @@ -24,18 +24,31 @@ func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) { } items := make([]store.CatalogEntry, 0, len(products)) for _, p := range products { - items = append(items, p.Catalog(s.env())) + 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. "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 +76,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 +111,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 +125,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 diff --git a/internal/server/erp.go b/internal/server/erp.go index e70b7b9..34f18ac 100644 --- a/internal/server/erp.go +++ b/internal/server/erp.go @@ -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 { diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go new file mode 100644 index 0000000..5741834 --- /dev/null +++ b/internal/server/onprem_test.go @@ -0,0 +1,292 @@ +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) { + ctx := context.Background() + // Control: in the cloud a new workspace queues its ERP customer. + before, err := h.store.PendingOutbox(ctx) + if err != nil { + t.Fatal(err) + } + if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "cloud-ws", "name": "Cloud GmbH"}); resp.StatusCode != http.StatusCreated { + t.Fatalf("cloud create = %d %s", resp.StatusCode, body) + } + if n, _ := h.store.PendingOutbox(ctx); n != before+1 { + t.Fatalf("cloud outbox %d → %d, want +1", before, n) + } + onPremHarness(h, nil) + 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 +} + +// cloudURLStore serves Prüfwerk with seeded stage/prod provision URLs, as the +// migrations do on a real database. +type cloudURLStore struct { + store.Store + url string +} + +func (c cloudURLStore) seed(p *store.Product) { + if p.Key == "pruefwerk" { + p.ProvisionURLs = map[string]string{"stage": c.url + "/{id}/stage", "prod": c.url + "/{id}/prod"} + } +} + +func (c cloudURLStore) GetProduct(ctx context.Context, key string) (*store.Product, error) { + p, err := c.Store.GetProduct(ctx, key) + if err == nil { + c.seed(p) + } + return p, err +} + +func (c cloudURLStore) ListProducts(ctx context.Context, all bool) ([]store.Product, error) { + ps, err := c.Store.ListProducts(ctx, all) + for i := range ps { + c.seed(&ps[i]) + } + return ps, err +} + +// Blocker #1: the seeded cloud URLs are never called on-prem, even when the +// values file gives a product no provision URL of its own. +func TestOnPrem_seededCloudProvisionURLsAreNeverCalled(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + var mu sync.Mutex + calls := 0 + cloud := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + calls++ + mu.Unlock() + w.WriteHeader(http.StatusOK) + })) + defer cloud.Close() + seeded := cloudURLStore{Store: h.store, url: cloud.URL} + activate := func() { + t.Helper() + if resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{ + "products": []map[string]any{{"key": "pruefwerk"}}, + }); resp.StatusCode != http.StatusOK { + t.Fatalf("activate = %d %s", resp.StatusCode, body) + } + } + + // Control: in the cloud (dev reads stage) the seeded URL is called. + h.app.Store = seeded + activate() + mu.Lock() + if calls != 1 { + t.Fatalf("cloud: %d calls to the seeded URL, want 1", calls) + } + calls = 0 + mu.Unlock() + + h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30} + h.app.Store = store.WithProductOverrides(seeded, h.app.Cfg.CatalogEnv(), []string{"pruefwerk"}, + map[string]string{"pruefwerk": "https://pruefwerk.onprem.test"}, nil) + activate() + mu.Lock() + defer mu.Unlock() + if calls != 0 { + t.Errorf("on-prem: %d calls to a seeded cloud URL", calls) + } + }) +} + +func TestOnPrem_catalogOffersNoTrials(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + onPremHarness(h, nil) + _, body := h.do("GET", "/v1/catalog", nil) + out := decode[struct { + Items []store.CatalogEntry `json:"items"` + }](t, body) + for _, it := range out.Items { + if it.SupportsTrial { + t.Errorf("%s offers a trial on-prem", it.Key) + } + } + }) +} diff --git a/internal/server/outbox.go b/internal/server/outbox.go index 6d10a87..517942c 100644 --- a/internal/server/outbox.go +++ b/internal/server/outbox.go @@ -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) } diff --git a/internal/server/server.go b/internal/server/server.go index 78bd870..9a66411 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -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