From a4fb318773bcbf400c0ea779a295e410e7ccd2c1 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:35:53 +0100 Subject: [PATCH 1/8] feat(onprem): APP_ENV=onprem for a customer's own node 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 (cherry picked from commit 2f6fa5f3e84e767a537d7fe4729938f3a0ae1c8f) --- README.md | 15 +- cmd/server/main.go | 10 +- internal/config/config.go | 140 ++++++++++++- internal/config/onprem_test.go | 151 ++++++++++++++ internal/mail/mail.go | 24 ++- internal/mail/plain_test.go | 101 +++++++++ internal/server/catalog.go | 29 ++- internal/server/erp.go | 5 + internal/server/onprem_test.go | 192 ++++++++++++++++++ internal/server/outbox.go | 11 +- internal/server/server.go | 29 ++- internal/server/tenants.go | 9 + internal/server/usage.go | 2 +- internal/store/product_overrides.go | 79 +++++++ internal/store/products.go | 2 +- .../0032_werkpilot_description.down.sql | 4 + migrations/0032_werkpilot_description.up.sql | 6 + openapi.yaml | 7 + 18 files changed, 786 insertions(+), 30 deletions(-) create mode 100644 internal/config/onprem_test.go create mode 100644 internal/mail/plain_test.go create mode 100644 internal/server/onprem_test.go create mode 100644 internal/store/product_overrides.go create mode 100644 migrations/0032_werkpilot_description.down.sql create mode 100644 migrations/0032_werkpilot_description.up.sql diff --git a/README.md b/README.md index 96cbbf1..593403d 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 nothing is sent to a Breakpilot host. Each listed product needs a launch URL. +- 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..165e21c 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -82,6 +82,12 @@ func main() { s = pg } defer s.Close() + kind := storeKind(s) + // PRODUCTS / PRODUCT_*_URLS (on-prem: the only source of product URLs). + s = store.WithProductOverrides(s, cfg.CatalogEnv(), cfg.Products, cfg.LaunchURLs, cfg.ProvisionURLs) + if cfg.OnPrem() { + slog.Info("on-prem mode: no ERP, no trial ladder, no sign-up", "products", cfg.Products) + } var kc keycloak.Adapter if cfg.KeycloakAdminURL != "" && cfg.KeycloakClientID != "" { @@ -189,7 +195,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 +221,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..ddb09eb 100644 --- a/internal/server/catalog.go +++ b/internal/server/catalog.go @@ -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 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..49fc5ef --- /dev/null +++ b/internal/server/onprem_test.go @@ -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 +} 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 52b87be..1bff94b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -65,6 +65,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{} @@ -100,14 +111,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 :licence), checked in the handler. @@ -146,11 +157,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): ".pdf". mux.HandleFunc("GET /v1/tenants/{id}/contracts/documents/{file}", s.tenantContractDocumentPDF) // Projekte (0010): the list is a {sub} of tenantSubresource. @@ -239,7 +250,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) diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 0a5ee4a..2267430 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -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, diff --git a/internal/server/usage.go b/internal/server/usage.go index 22af72a..ae3924b 100644 --- a/internal/server/usage.go +++ b/internal/server/usage.go @@ -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)}, diff --git a/internal/store/product_overrides.go b/internal/store/product_overrides.go new file mode 100644 index 0000000..ee5474c --- /dev/null +++ b/internal/store/product_overrides.go @@ -0,0 +1,79 @@ +package store + +import "context" + +// ProductOverrides decorates a Store's catalog reads with the deployment's +// own product list and URLs (PRODUCTS, PRODUCT_LAUNCH_URLS, +// PRODUCT_PROVISION_URLS). Every caller that reads a product (catalog, +// activation, provisioning, entitlement checks) sees the same answer. +// +// With Only set, a product is enabled exactly when it is listed, whatever +// its row says. Launch and Provision replace the URL under Env. +type ProductOverrides struct { + Store + Env string + Only []string + Launch map[string]string + Provision map[string]string +} + +// WithProductOverrides wraps s, or returns it unchanged when nothing is set. +func WithProductOverrides(s Store, env string, only []string, launch, provision map[string]string) Store { + if len(only) == 0 && len(launch) == 0 && len(provision) == 0 { + return s + } + return &ProductOverrides{Store: s, Env: env, Only: only, Launch: launch, Provision: provision} +} + +func (o *ProductOverrides) apply(p Product) Product { + if len(o.Only) > 0 { + p.Enabled = false + for _, k := range o.Only { + if k == p.Key { + p.Enabled = true + break + } + } + } + if u, ok := o.Launch[p.Key]; ok { + p.LaunchURLs = withURL(p.LaunchURLs, o.Env, u) + } + if u, ok := o.Provision[p.Key]; ok { + p.ProvisionURLs = withURL(p.ProvisionURLs, o.Env, u) + } + return p +} + +// withURL copies m (the store's map must not be shared) and sets env. +func withURL(m map[string]string, env, u string) map[string]string { + out := make(map[string]string, len(m)+1) + for k, v := range m { + out[k] = v + } + out[env] = u + return out +} + +func (o *ProductOverrides) GetProduct(ctx context.Context, key string) (*Product, error) { + p, err := o.Store.GetProduct(ctx, key) + if err != nil { + return nil, err + } + q := o.apply(*p) + return &q, nil +} + +func (o *ProductOverrides) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) { + // The row's flag is not the answer when Only is set: read them all. + all, err := o.Store.ListProducts(ctx, includeDisabled || len(o.Only) > 0) + if err != nil { + return nil, err + } + out := make([]Product, 0, len(all)) + for _, p := range all { + if p = o.apply(p); includeDisabled || p.Enabled { + out = append(out, p) + } + } + return out, nil +} diff --git a/internal/store/products.go b/internal/store/products.go index d5eb3f7..fb1b319 100644 --- a/internal/store/products.go +++ b/internal/store/products.go @@ -26,7 +26,7 @@ func DefaultProducts() []Product { }, { Key: "werkpilot", Name: "Werkpilot", Type: "cli", - Description: "On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to llm.breakpilot.com.", + Description: "On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to the platform's language-model gateway.", LaunchURLs: map[string]string{"stage": "https://git.breakpilot.com/platform/werkpilot/releases", "prod": "https://git.breakpilot.com/platform/werkpilot/releases"}, ProvisionURLs: map[string]string{}, SKUs: []string{"DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT"}, diff --git a/migrations/0032_werkpilot_description.down.sql b/migrations/0032_werkpilot_description.down.sql new file mode 100644 index 0000000..f70ef81 --- /dev/null +++ b/migrations/0032_werkpilot_description.down.sql @@ -0,0 +1,4 @@ +UPDATE products + SET description = 'On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to llm.breakpilot.com.' + WHERE key = 'werkpilot' + AND description = 'On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to the platform''s language-model gateway.'; diff --git a/migrations/0032_werkpilot_description.up.sql b/migrations/0032_werkpilot_description.up.sql new file mode 100644 index 0000000..ec40f80 --- /dev/null +++ b/migrations/0032_werkpilot_description.up.sql @@ -0,0 +1,6 @@ +-- The Werkpilot text named our cloud gateway; on-prem it talks to the +-- customer's own. Neutral wording for every installation. +UPDATE products + SET description = 'On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to the platform''s language-model gateway.' + WHERE key = 'werkpilot' + AND description = 'On-prem AI coding agent for machine and plant manufacturers (CLI). Licensed per named user; talks to llm.breakpilot.com.'; diff --git a/openapi.yaml b/openapi.yaml index fb804a3..a6d7759 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -20,6 +20,13 @@ info: Tenant status ladder (ERP/02): demo, trial, active (Betriebsbereit), warning (Warnung), restricted (Eingeschränkt, read-only), halted (Angehalten), archived. 'frozen' is legacy = restricted. + + On-prem (APP_ENV=onprem, a customer's own node): there is no ERP, no + trial and no sign-up. New workspaces start active and nothing escalates + by time; the catalog lists only PRODUCTS, with the URLs from + PRODUCT_LAUNCH_URLS / PRODUCT_PROVISION_URLS. The trial-offer, trial-terms, + catalog request, trial request, admin trial and ERP webhook routes answer + 404 `not_available`. contact: email: oncall@breakpilot.com license: -- 2.54.1 From b30b5e3f1cae8df7d39fda20a232c8240292fbbd Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:39:22 +0100 Subject: [PATCH 2/8] 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 (cherry picked from commit 3e42b1ceb80dd4c454e8dc5445b066b3a6a7be14) --- README.md | 2 +- cmd/server/main.go | 12 ++- internal/server/catalog.go | 6 +- internal/server/onprem_test.go | 102 ++++++++++++++++++++++- internal/store/product_overrides.go | 41 ++++++++- internal/store/product_overrides_test.go | 38 +++++++++ 6 files changed, 196 insertions(+), 5 deletions(-) create mode 100644 internal/store/product_overrides_test.go diff --git a/README.md b/README.md index 593403d..fc6d47f 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ State-changing endpoints emit audit events automatically. The OpenAPI contract t - 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 nothing is sent to a Breakpilot host. Each listed product needs a launch URL. +- 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) diff --git a/cmd/server/main.go b/cmd/server/main.go index 165e21c..bf54457 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -84,9 +84,19 @@ func main() { 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() { - slog.Info("on-prem mode: no ERP, no trial ladder, no sign-up", "products", cfg.Products) + 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 diff --git a/internal/server/catalog.go b/internal/server/catalog.go index ddb09eb..096bc7b 100644 --- a/internal/server/catalog.go +++ b/internal/server/catalog.go @@ -24,7 +24,11 @@ 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}) } diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index 49fc5ef..5741834 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -79,12 +79,23 @@ func TestOnPrem_cloudOnlyRoutesAnswer404(t *testing.T) { func TestOnPrem_newWorkspaceIsActiveAndQueuesNothingForTheERP(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { - onPremHarness(h, nil) 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) @@ -190,3 +201,92 @@ func newTrial(t *testing.T, h *testHarness) *store.Tenant { } 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/store/product_overrides.go b/internal/store/product_overrides.go index ee5474c..c29acaa 100644 --- a/internal/store/product_overrides.go +++ b/internal/store/product_overrides.go @@ -1,6 +1,11 @@ package store -import "context" +import ( + "context" + "fmt" + "sort" + "strings" +) // ProductOverrides decorates a Store's catalog reads with the deployment's // own product list and URLs (PRODUCTS, PRODUCT_LAUNCH_URLS, @@ -77,3 +82,37 @@ func (o *ProductOverrides) ListProducts(ctx context.Context, includeDisabled boo } return out, nil } + +// CheckProductKeys fails when PRODUCTS or a URL override names a product the +// catalog does not know: a typo would otherwise ship a product without a +// tile or skip its provisioning without a trace. +func CheckProductKeys(ctx context.Context, s Store, only []string, launch, provision map[string]string) error { + all, err := s.ListProducts(ctx, true) + if err != nil { + return err + } + known := map[string]bool{} + for _, p := range all { + known[p.Key] = true + } + var unknown []string + add := func(src, k string) { + if !known[k] { + unknown = append(unknown, src+": "+k) + } + } + for _, k := range only { + add("PRODUCTS", k) + } + for k := range launch { + add("PRODUCT_LAUNCH_URLS", k) + } + for k := range provision { + add("PRODUCT_PROVISION_URLS", k) + } + if len(unknown) > 0 { + sort.Strings(unknown) + return fmt.Errorf("unknown products (%s)", strings.Join(unknown, ", ")) + } + return nil +} diff --git a/internal/store/product_overrides_test.go b/internal/store/product_overrides_test.go new file mode 100644 index 0000000..916f573 --- /dev/null +++ b/internal/store/product_overrides_test.go @@ -0,0 +1,38 @@ +package store + +import ( + "context" + "strings" + "testing" +) + +func TestCheckProductKeys(t *testing.T) { + m := NewMemory() + ctx := context.Background() + if err := CheckProductKeys(ctx, m, []string{"pruefwerk", "werkmeister"}, + map[string]string{"pruefwerk": "https://pruefwerk.onprem.test"}, + map[string]string{"pruefwerk": "https://pruefwerk.onprem.test/{id}"}); err != nil { + t.Errorf("known keys refused: %v", err) + } + err := CheckProductKeys(ctx, m, []string{"pruefwerck"}, map[string]string{"firmwrk": "https://x.onprem.test"}, nil) + if err == nil || !strings.Contains(err.Error(), "PRODUCTS: pruefwerck") || !strings.Contains(err.Error(), "PRODUCT_LAUNCH_URLS: firmwrk") { + t.Errorf("err = %v", err) + } +} + +func TestProductOverrides_doNotShareTheStoreMaps(t *testing.T) { + m := NewMemory() + ctx := context.Background() + o := WithProductOverrides(m, "onprem", nil, map[string]string{"pruefwerk": "https://pruefwerk.onprem.test"}, nil) + p, err := o.GetProduct(ctx, "pruefwerk") + if err != nil || p.LaunchURLs["onprem"] != "https://pruefwerk.onprem.test" { + t.Fatalf("override missing: %v %v", p, err) + } + raw, _ := m.GetProduct(ctx, "pruefwerk") + if _, leaked := raw.LaunchURLs["onprem"]; leaked { + t.Error("the override was written into the store's own map") + } + if WithProductOverrides(m, "prod", nil, nil, nil) != Store(m) { + t.Error("no overrides should return the store unchanged") + } +} -- 2.54.1 From 90ae11ae427ef82aa4054639f7eba617abad9989 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:18:22 +0100 Subject: [PATCH 3/8] feat(onprem): directory users instead of invitations On-prem every account comes from the customer's AD through Keycloak's federation, so an AD admin answered email_taken and invitations asked for a new password. The Keycloak adapter gets a directory mode (DirectoryUsers, on with APP_ENV=onprem): - The first admin and invited members are existing directory users, attached to the organization with their role. No local user is created, no execute-actions mail is sent (invite status "added", audit user.added / keycloak.admin_added). - An unknown address (or one outside the admitted AD groups) answers 404 not_in_directory. For the workspace's admin it is checked before the workspace is created, and the adapter looks the user up before creating the organization, so nothing is left behind. - Resend answers 409 no_invite_mail; directory members are never pending. - Member lists read the roles from the user when Keycloak lists a federated member with its LDAP attributes only (seen with Keycloak 26.8). - The admin address is normalized once for lookup, store and Keycloak. Checked against Keycloak 26.8.1 with a Samba AD (the test install in platform/onprem, realm with UNSYNCED federation and realm-policy.sh). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b8206c553fe0ed4b6245600d2bdbd0f91b35b3d1) --- README.md | 1 + cmd/server/main.go | 2 + internal/keycloak/adapter.go | 10 ++ internal/keycloak/client.go | 7 ++ internal/keycloak/directory_test.go | 112 ++++++++++++++++++ internal/keycloak/members.go | 18 ++- internal/keycloak/members_test.go | 57 ++++++--- internal/keycloak/mock.go | 34 ++++++ internal/keycloak/orgs.go | 172 ++++++++++++++++++++-------- internal/server/admin_lifecycle.go | 18 ++- internal/server/members.go | 15 ++- internal/server/onprem_test.go | 74 ++++++++++++ internal/server/tenants.go | 24 +++- openapi.yaml | 9 +- 14 files changed, 477 insertions(+), 76 deletions(-) create mode 100644 internal/keycloak/directory_test.go diff --git a/README.md b/README.md index fc6d47f..4704b1b 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ State-changing endpoints emit audit events automatically. The OpenAPI contract t - 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. +- Accounts only from the customer's directory (Keycloak federates their AD; the package's `keycloak/realm-policy.sh` keeps passwords in AD). The workspace's first admin (`admin_email`) and every invited member must be an existing directory user: they are added to the organization with their role, get no set-password mail and sign in with their directory password. An unknown address answers `not_in_directory`; there is no invitation to resend (`no_invite_mail`). - 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) diff --git a/cmd/server/main.go b/cmd/server/main.go index bf54457..5cb66d0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -110,6 +110,8 @@ func main() { InviteClientID: cfg.InviteClientID, InviteRedirectURI: cfg.InviteRedirectURI, + // On-prem every account comes from the customer's directory. + DirectoryUsers: cfg.OnPrem(), }) slog.Info("keycloak adapter configured", "url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID) diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index b8efcd2..ed3e65f 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -28,6 +28,12 @@ var ( ErrUnavailable = errors.New("keycloak: unreachable") ErrUserNotFound = errors.New("keycloak: user does not exist") ErrOrgNotFound = errors.New("keycloak: organization does not exist") + // Directory mode (on-prem): accounts come from the customer's directory. + // ErrNotInDirectory: no directory user with this e-mail (or not in the + // groups the realm admits). ErrNoInviteMail: there is no invitation mail + // to resend; directory users sign in with their directory password. + ErrNotInDirectory = errors.New("keycloak: no directory user with this e-mail") + ErrNoInviteMail = errors.New("keycloak: directory users get no invitation mail") ) // InviteInput captures the per-tenant onboarding event from POST /v1/tenants. @@ -47,6 +53,9 @@ type InviteInput struct { // the invitation only asks to set a password; otherwise Keycloak would // demand a second e-mail confirmation. EmailVerified bool + // TenantStatus is written as the admin's tenant_status attribute. + // Empty: "trial" (a new cloud workspace). + TenantStatus string } // InviteResult is what the adapter produces. OrganizationID is what the @@ -128,6 +137,7 @@ type MemberInviteInput struct { const ( InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent InviteStatusMember = "member" // already a member; nothing changed, no mail + InviteStatusAdded = "added" // directory mode: an existing directory user added to the org; no mail ) // MemberInviteResult reports what InviteMember did. diff --git a/internal/keycloak/client.go b/internal/keycloak/client.go index 42d4cae..9ee408d 100644 --- a/internal/keycloak/client.go +++ b/internal/keycloak/client.go @@ -44,6 +44,13 @@ type HTTPConfig struct { // portal forwards to //dashboard; Keycloak only allows /start*). InviteClientID string InviteRedirectURI string + + // DirectoryUsers (on-prem): every account comes from the customer's + // directory through the realm's user federation. The adapter never + // creates a user and never sends the set-password mail: it attaches the + // existing directory user to the organization. Passwords stay in the + // directory. + DirectoryUsers bool } func NewHTTPAdapter(cfg HTTPConfig) *HTTPAdapter { diff --git a/internal/keycloak/directory_test.go b/internal/keycloak/directory_test.go new file mode 100644 index 0000000..a8af6e7 --- /dev/null +++ b/internal/keycloak/directory_test.go @@ -0,0 +1,112 @@ +package keycloak + +import ( + "context" + "errors" + "strings" + "testing" +) + +// Directory mode (on-prem): the users come from the customer's directory. +func newDirectoryKC(t *testing.T) (*membersKC, *HTTPAdapter) { + t.Helper() + k, a := newMembersKC(t) + a.cfg.DirectoryUsers = true + return k, a +} + +func TestDirectory_adminIsAttachedWithoutMail(t *testing.T) { + k, a := newDirectoryKC(t) + res, err := a.CreateOrgAndInvite(context.Background(), InviteInput{ + TenantID: "t-2", Slug: "werk", Name: "Werk GmbH", AdminEmail: "loose@acme.test", TenantStatus: "active", + }) + if err != nil { + t.Fatal(err) + } + if res.UserID != "u-loose" || res.InviteURL != "" || res.MailError != nil { + t.Fatalf("result: %+v", res) + } + if len(k.created) != 0 || len(k.mails) != 0 { + t.Errorf("directory mode created %d users and sent %d mails", len(k.created), len(k.mails)) + } + if got := k.members["org-werk"]; len(got) != 1 || got[0] != "u-loose" { + t.Errorf("membership: %v", got) + } + // The installer named this person the admin: the workspace attributes are set, also over old ones. + want := map[string]string{"tenant_id": "t-2", "tenant_slug": "werk", "org_roles": "IT_ADMIN", "tenant_status": "active"} + for key, val := range want { + if got := k.puts["u-loose"][key]; len(got) != 1 || got[0] != val { + t.Errorf("attribute %s = %v, want %s", key, got, val) + } + } +} + +func TestDirectory_unknownAdminLeavesNoOrganization(t *testing.T) { + k, a := newDirectoryKC(t) + _, err := a.CreateOrgAndInvite(context.Background(), InviteInput{TenantID: "t-3", Slug: "nobody", Name: "N", AdminEmail: "ghost@acme.test"}) + if !errors.Is(err, ErrNotInDirectory) { + t.Fatalf("err = %v, want ErrNotInDirectory", err) + } + if len(k.orgsCreated) != 0 || len(k.created) != 0 { + t.Errorf("orgs created %v, users created %d", k.orgsCreated, len(k.created)) + } +} + +func TestDirectory_memberIsAddedWithoutMail(t *testing.T) { + k, a := newDirectoryKC(t) + res, err := a.InviteMember(context.Background(), MemberInviteInput{ + TenantID: "t-1", Slug: "acme", TenantStatus: "active", Email: "loose@acme.test", Role: "USER", + }) + if err != nil { + t.Fatal(err) + } + if res.Status != InviteStatusAdded || res.Created || len(k.mails) != 0 { + t.Fatalf("result %+v, mails %v", res, k.mails) + } + if got := k.members["org-acme"]; len(got) != 2 || got[1] != "u-loose" { + t.Errorf("membership: %v", got) + } + if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "ghost@acme.test", Role: "USER"}); !errors.Is(err, ErrNotInDirectory) { + t.Errorf("unknown member: %v", err) + } + if len(k.created) != 0 { + t.Errorf("a local user was created in directory mode") + } +} + +func TestDirectory_noResendAndNeverPending(t *testing.T) { + k, a := newDirectoryKC(t) + delete(k.creds, "u-admin") // like an AD user: no password in Keycloak + // Control: the same member without a Keycloak password is pending in the cloud. + kc, cloud := newMembersKC(t) + delete(kc.creds, "u-admin") + if ms, err := cloud.ListOrgMembers(context.Background(), "acme"); err != nil || len(ms) == 0 || !ms[0].Pending { + t.Fatalf("control: cloud member not pending: %+v %v", ms, err) + } + if err := a.ResendInvite(context.Background(), "acme", "admin@acme.test"); !errors.Is(err, ErrNoInviteMail) { + t.Errorf("resend: %v", err) + } + members, err := a.ListOrgMembers(context.Background(), "acme") + if err != nil { + t.Fatal(err) + } + for _, m := range members { + if m.Pending { + t.Errorf("%s pending: a directory user has no Keycloak password and is never pending", m.Email) + } + } +} + +// KC 26 lists a federated member with its LDAP attributes only; the roles are +// read from the user itself. +func TestDirectory_memberRolesWhenTheListCarriesOnlyLDAPAttributes(t *testing.T) { + k, a := newDirectoryKC(t) + k.ldapOnly = true + members, err := a.ListOrgMembers(context.Background(), "acme") + if err != nil { + t.Fatal(err) + } + if len(members) != 1 || strings.Join(members[0].OrgRoles, ",") != "IT_ADMIN,OWNER" { + t.Errorf("members = %+v", members) + } +} diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 30856b8..81b32ae 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -67,8 +67,9 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem } out := make([]OrgMember, 0, len(members)) for _, m := range members { - if m.Attributes == nil { - // Brief representation: attributes (org_roles) live on the user. + if m.Attributes == nil || len(attrValues(m.Attributes, "org_roles")) == 0 { + // Brief representation, or a federated (AD) user, whose list entry + // carries only the LDAP attributes: org_roles live on the user. var u memberRepresentation resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u) if err == nil && resp.StatusCode/100 == 2 { @@ -78,7 +79,8 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem } } om := m.toOrgMember() - om.Pending = !a.hasPassword(ctx, m.ID) + // A directory user has no password in Keycloak and is never pending. + om.Pending = !a.cfg.DirectoryUsers && !a.hasPassword(ctx, m.ID) out = append(out, om) } return out, nil @@ -114,6 +116,9 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (* if aerr := a.ensureUserAttributes(ctx, userID, attrs); aerr != nil { slog.Warn("keycloak user attributes not merged", "user_id", userID, "err", aerr) } + case errors.Is(err, errUserLookupMiss) && a.cfg.DirectoryUsers: + // Never a local account next to the directory. + return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.Email) case errors.Is(err, errUserLookupMiss): userID, err = a.createUser(ctx, userCreate{ Username: in.Email, @@ -148,6 +153,10 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (* } _ = resp.Body.Close() + if a.cfg.DirectoryUsers { + // Signs in with the directory password: no set-password mail. + return &MemberInviteResult{UserID: userID, Status: InviteStatusAdded}, nil + } res := &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: created} if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.inviteRedirect(in.Slug)); merr != nil { res.MailError = merr @@ -199,6 +208,9 @@ func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, a } func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error { + if a.cfg.DirectoryUsers { + return ErrNoInviteMail + } members, err := a.ListOrgMembers(ctx, slug) if err != nil { return err diff --git a/internal/keycloak/members_test.go b/internal/keycloak/members_test.go index c9dec4d..ab34f7a 100644 --- a/internal/keycloak/members_test.go +++ b/internal/keycloak/members_test.go @@ -16,22 +16,24 @@ import ( // org lookup by alias, member list, user search/create/get/put, member add // (bare-id body, 409 when already a member) and execute-actions e-mail. type membersKC struct { - mu sync.Mutex - orgs map[string]string // alias → org id - members map[string][]string // org id → user ids - users map[string]memberRepresentation // user id → user - brief bool // member list omits attributes - mails []string // user ids that got the execute-actions mail - redirects []string // redirect_uri of each execute-actions mail - created []userCreate - puts map[string]map[string][]string // user id → attributes PUT - createErr int // non-zero: POST /users answers this status - nextID int - creds map[string][]string // user id → credential types - idp map[string]bool // user id → linked to an identity provider - logouts []string // user ids logged out - deleted []string // user ids deleted - failWrite int // non-zero: member DELETE / logout answer this status + mu sync.Mutex + orgs map[string]string // alias → org id + members map[string][]string // org id → user ids + users map[string]memberRepresentation // user id → user + brief bool // member list omits attributes + mails []string // user ids that got the execute-actions mail + redirects []string // redirect_uri of each execute-actions mail + created []userCreate + puts map[string]map[string][]string // user id → attributes PUT + createErr int // non-zero: POST /users answers this status + nextID int + creds map[string][]string // user id → credential types + idp map[string]bool // user id → linked to an identity provider + logouts []string // user ids logged out + deleted []string // user ids deleted + failWrite int // non-zero: member DELETE / logout answer this status + orgsCreated []string // aliases of organizations created + ldapOnly bool // member list carries only LDAP attributes } // orgName is the display name the registry gives an organization: the company @@ -100,6 +102,10 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { if k.brief { u.Attributes = nil } + if k.ldapOnly { + // KC 26 for a federated user: only the LDAP attributes in the list. + u.Attributes = map[string][]string{"LDAP_ID": {"x"}} + } out = append(out, u) } _ = json.NewEncoder(w).Encode(out) @@ -259,6 +265,25 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { k.logouts = append(k.logouts, r.PathValue("id")) w.WriteHeader(http.StatusNoContent) }) + // Organization create (directory-mode admin path). + mux.HandleFunc("POST /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + var body struct { + Alias string `json:"alias"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + if _, taken := k.orgs[body.Alias]; taken { + w.WriteHeader(http.StatusConflict) + return + } + id := "org-" + body.Alias + k.orgs[body.Alias] = id + k.members[id] = []string{} + k.orgsCreated = append(k.orgsCreated, body.Alias) + w.Header().Set("Location", "http://kc/admin/realms/test-realm/organizations/"+id) + w.WriteHeader(http.StatusCreated) + }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) a := NewHTTPAdapter(HTTPConfig{ diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index d7be0ee..085314b 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -37,6 +37,10 @@ type Mock struct { Removed []string // every RemoveMember call, by user id Deleted []string // accounts RemoveMember deleted LoggedOut []string // every LogoutUser call + + // Directory mode (on-prem): Users is the customer's directory. No user + // is created, no invitation mail is recorded. + Directory bool } func NewMock() *Mock { @@ -207,6 +211,16 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv } } userID, created := m.Users[in.Email] + if m.Directory { + if userID == "" { + return nil, ErrNotInDirectory + } + now := time.Now().UTC() + m.Members[in.Slug] = append(members, OrgMember{ + UserID: userID, Email: in.Email, OrgRoles: []string{in.Role}, Enabled: true, CreatedAt: &now, + }) + return &MemberInviteResult{UserID: userID, Status: InviteStatusAdded}, nil + } if userID == "" { userID = "mock-user-" + in.Email m.Users[in.Email] = userID @@ -231,6 +245,9 @@ func (m *Mock) UserExists(_ context.Context, email string) (bool, error) { func (m *Mock) ResendInvite(_ context.Context, slug, email string) error { m.mu.Lock() defer m.mu.Unlock() + if m.Directory { + return ErrNoInviteMail + } if m.FailNext != nil { err := m.FailNext m.FailNext = nil @@ -277,6 +294,23 @@ func (m *Mock) CreateOrgAndInvite(_ context.Context, in InviteInput) (*InviteRes if _, taken := m.Orgs[in.TenantID]; taken { return nil, ErrOrgConflict } + if m.Directory { + userID, ok := m.Users[in.AdminEmail] + if !ok { + return nil, ErrNotInDirectory + } + orgID := "mock-org-" + in.Slug + m.Orgs[in.TenantID] = orgID + now := time.Now().UTC() + if m.Members == nil { + m.Members = map[string][]OrgMember{} + } + m.Members[in.Slug] = append(m.Members[in.Slug], OrgMember{ + UserID: userID, Email: in.AdminEmail, OrgRoles: []string{"IT_ADMIN"}, Enabled: true, CreatedAt: &now, + }) + m.Created = append(m.Created, in) + return &InviteResult{OrganizationID: orgID, UserID: userID}, nil + } if _, taken := m.Users[in.AdminEmail]; taken { return nil, ErrUserConflict } diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 70b46f9..fe396c1 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -50,57 +50,13 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* if in.AdminEmail == "" { return nil, fmt.Errorf("keycloak: admin email required") } - - // 1. Create org with tenant_id baked in as an attribute so we can - // correlate the two systems with a single Admin API call later. - orgPayload := orgCreate{ - Name: in.Name, - Alias: in.Slug, - Description: fmt.Sprintf("Auto-provisioned from tenant-registry %s", in.TenantID), - // Keycloak 26 rejects an organization with no domain ("You must - // provide at least one domain"). Membership is registry-authoritative - // (model B2), so we do NOT use Keycloak's email-domain auto-join; a - // synthetic per-tenant domain derived from the unique slug satisfies - // the constraint without depending on the customer's real mail domain - // (which may be a shared public domain and would collide across - // tenants). Unverified is fine — verification only gates auto-join. - Domains: []map[string]any{ - {"name": in.Slug + orgDomainSuffix, "verified": false}, - }, - Attributes: map[string][]string{ - "tenant_id": {in.TenantID}, - }, + if a.cfg.DirectoryUsers { + return a.attachDirectoryAdmin(ctx, in) } - resp, err := a.adminCall(ctx, http.MethodPost, "/organizations", orgPayload, nil) + orgID, err := a.createOrg(ctx, in) if err != nil { return nil, err } - switch resp.StatusCode { - case http.StatusCreated: - // keep going - case http.StatusConflict: - _ = resp.Body.Close() - return nil, fmt.Errorf("%w: alias=%s", ErrOrgConflict, in.Slug) - default: - body, _ := io.ReadAll(resp.Body) - _ = resp.Body.Close() - return nil, fmt.Errorf("create org: %d %s", resp.StatusCode, body) - } - // Keycloak returns the id in the Location header. - orgID := lastSegment(resp.Header.Get("Location")) - _ = resp.Body.Close() - if orgID == "" { - // Fallback: query by alias. - orgID, err = a.findOrgByAlias(ctx, in.Slug) - if err != nil { - return nil, fmt.Errorf("create org: missing Location and lookup failed: %w", err) - } - } - // Keycloak 26 ignores attributes on create; write them with a PUT so the - // org carries tenant_id (non-fatal: the alias stays the correlation key). - if err := a.ensureOrgAttributes(ctx, orgID, orgPayload.Attributes); err != nil { - slogWarn("keycloak org attributes not set", orgID, err) - } // 2. Create the user (disabled until they set a password). first, last := splitName(in.AdminName) @@ -118,10 +74,10 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* "tenant_id": {in.TenantID}, "tenant_slug": {in.Slug}, "org_roles": {"IT_ADMIN"}, - "tenant_status": {"trial"}, + "tenant_status": {statusOr(in.TenantStatus, "trial")}, }, } - resp, err = a.adminCall(ctx, http.MethodPost, "/users", userPayload, nil) + resp, err := a.adminCall(ctx, http.MethodPost, "/users", userPayload, nil) if err != nil { return nil, fmt.Errorf("create user: %w", err) } @@ -176,6 +132,124 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: inviteURL}, nil } +// createOrg creates the tenant's organization and returns its id. +func (a *HTTPAdapter) createOrg(ctx context.Context, in InviteInput) (string, error) { + // Create org with tenant_id baked in as an attribute so we can + // correlate the two systems with a single Admin API call later. + orgPayload := orgCreate{ + Name: in.Name, + Alias: in.Slug, + Description: fmt.Sprintf("Auto-provisioned from tenant-registry %s", in.TenantID), + // Keycloak 26 rejects an organization with no domain ("You must + // provide at least one domain"). Membership is registry-authoritative + // (model B2), so we do NOT use Keycloak's email-domain auto-join; a + // synthetic per-tenant domain derived from the unique slug satisfies + // the constraint without depending on the customer's real mail domain + // (which may be a shared public domain and would collide across + // tenants). Unverified is fine — verification only gates auto-join. + Domains: []map[string]any{ + {"name": in.Slug + orgDomainSuffix, "verified": false}, + }, + Attributes: map[string][]string{ + "tenant_id": {in.TenantID}, + }, + } + resp, err := a.adminCall(ctx, http.MethodPost, "/organizations", orgPayload, nil) + if err != nil { + return "", err + } + switch resp.StatusCode { + case http.StatusCreated: + // keep going + case http.StatusConflict: + _ = resp.Body.Close() + return "", fmt.Errorf("%w: alias=%s", ErrOrgConflict, in.Slug) + default: + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + return "", fmt.Errorf("create org: %d %s", resp.StatusCode, body) + } + // Keycloak returns the id in the Location header. + orgID := lastSegment(resp.Header.Get("Location")) + _ = resp.Body.Close() + if orgID == "" { + // Fallback: query by alias. + orgID, err = a.findOrgByAlias(ctx, in.Slug) + if err != nil { + return "", fmt.Errorf("create org: missing Location and lookup failed: %w", err) + } + } + // Keycloak 26 ignores attributes on create; write them with a PUT so the + // org carries tenant_id (non-fatal: the alias stays the correlation key). + if err := a.ensureOrgAttributes(ctx, orgID, orgPayload.Attributes); err != nil { + slogWarn("keycloak org attributes not set", orgID, err) + } + return orgID, nil +} + +// attachDirectoryAdmin is CreateOrgAndInvite in directory mode: the admin is +// an existing directory user. Looked up first, so a wrong address leaves no +// organization behind. The workspace attributes are set (the installer named +// this person the IT admin), the user joins the organization, and no mail is +// sent: they sign in with their directory password. +func (a *HTTPAdapter) attachDirectoryAdmin(ctx context.Context, in InviteInput) (*InviteResult, error) { + userID, err := a.findUserByEmail(ctx, in.AdminEmail) + if errors.Is(err, errUserLookupMiss) { + return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.AdminEmail) + } + if err != nil { + return nil, err + } + orgID, err := a.createOrg(ctx, in) + if err != nil { + return nil, err + } + attrs := map[string][]string{ + "tenant_id": {in.TenantID}, + "tenant_slug": {in.Slug}, + "org_roles": {"IT_ADMIN"}, + "tenant_status": {statusOr(in.TenantStatus, "active")}, + } + if err := a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool { + for k, v := range attrs { + existing[k] = v + } + return true + }); err != nil { + return nil, fmt.Errorf("set admin attributes: %w", err) + } + if _, err := a.addOrgMember(ctx, orgID, userID); err != nil { + return nil, err + } + return &InviteResult{OrganizationID: orgID, UserID: userID}, nil +} + +// addOrgMember adds userID to the organization; already reports a 409 (the +// user was a member). KC 26: the body is the bare user id as a JSON string; +// an object yields "User does not exist". +func (a *HTTPAdapter) addOrgMember(ctx context.Context, orgID, userID string) (already bool, err error) { + resp, err := a.adminCall(ctx, http.MethodPost, fmt.Sprintf("/organizations/%s/members", orgID), userID, nil) + if err != nil { + return false, fmt.Errorf("add member: %w", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode == http.StatusConflict { + return true, nil + } + if resp.StatusCode/100 != 2 { + body, _ := io.ReadAll(resp.Body) + return false, fmt.Errorf("add member: %d %s", resp.StatusCode, body) + } + return false, nil +} + +func statusOr(s, fallback string) string { + if s == "" { + return fallback + } + return s +} + // SyncClaims pushes the up-to-date claim bundle into the user's KC // attributes. Called by tenant-registry whenever entitlements change. func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) error { diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 894a937..049c9c9 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -56,7 +56,7 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { _, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug) switch { case errors.Is(lerr, keycloak.ErrOrgNotFound): - res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email}) + res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email, TenantStatus: t.Status}) if err != nil { if errors.Is(err, keycloak.ErrUserConflict) { writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant") @@ -67,6 +67,8 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { } if res.MailError != nil { outcome = "created_mail_failed" + } else if s.onPrem() { + outcome = "added" } case lerr != nil: s.writeKeycloakError(w, t.ID, "reprovision", lerr) @@ -77,12 +79,20 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { s.writeKeycloakError(w, t.ID, "reprovision", err) return } - if res.Status == keycloak.InviteStatusMember { - if err := s.Keycloak.ResendInvite(ctx, t.Slug, email); err != nil { + switch { + case res.Status == keycloak.InviteStatusAdded: + outcome = "added" + case res.Status == keycloak.InviteStatusMember: + err := s.Keycloak.ResendInvite(ctx, t.Slug, email) + switch { + case errors.Is(err, keycloak.ErrNoInviteMail): + outcome = "member" // a directory user: nothing to resend + case err != nil: s.writeKeycloakError(w, t.ID, "reprovision", err) return + default: + outcome = "resent" } - outcome = "resent" } } if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil { diff --git a/internal/server/members.go b/internal/server/members.go index 6f51342..61bc8a4 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -190,13 +190,17 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) { return } + action := "user.invited" + if res.Status == keycloak.InviteStatusAdded { + action = "user.added" // a directory user: no mail, signs in at once + } meta := map[string]interface{}{"role": in.Role, "user_id": res.UserID, "user_created": res.Created} if res.MailError != nil { s.Log.Warn("invite mail failed", "tenant_id", t.ID, "user_id", res.UserID, "err", res.MailError) meta["mail_error"] = res.MailError.Error() } ev := store.AuditEvent{ - TenantID: t.ID, Action: "user.invited", + TenantID: t.ID, Action: action, TargetID: in.Email, TargetType: "user", TargetName: in.Email, Metadata: meta, } @@ -223,6 +227,15 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) { // writeKeycloakError maps adapter failures: unreachable/unauthorized are a // 503 (the portal shows "identity provider unavailable"), anything else 502. func (s *Server) writeKeycloakError(w http.ResponseWriter, tenantID, op string, err error) { + // Directory mode (on-prem): answers, not failures. + switch { + case errors.Is(err, keycloak.ErrNotInDirectory): + writeError(w, http.StatusNotFound, "not_in_directory", "no directory account with this e-mail in the groups that may use the platform") + return + case errors.Is(err, keycloak.ErrNoInviteMail): + writeError(w, http.StatusConflict, "no_invite_mail", "directory users sign in with their directory password; there is no invitation to resend") + return + } s.Log.Error("keycloak "+op+" failed", "tenant_id", tenantID, "err", err) if errors.Is(err, keycloak.ErrUnavailable) || errors.Is(err, keycloak.ErrUnauthorized) { writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error()) diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index 5741834..207fa99 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -19,6 +19,11 @@ import ( // 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} + // The adapter runs in directory mode on-prem (main.go: DirectoryUsers); + // the mock's Users are then the customer's directory. + h.kcMock.Directory = true + h.kcMock.Users["anna.admin@onprem.test"] = "u-anna" + h.kcMock.Users["ben.user@onprem.test"] = "u-ben" 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"}, @@ -290,3 +295,72 @@ func TestOnPrem_catalogOffersNoTrials(t *testing.T) { } }) } + +func TestOnPrem_workspaceAdminIsTheDirectoryUser(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + onPremHarness(h, nil) + resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "Anna.Admin@onprem.test"}) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("create = %d %s", resp.StatusCode, body) + } + out := decode[createResp](t, body) + if out.InviteURL != "" { + t.Errorf("invite URL on-prem: %s", out.InviteURL) + } + members := h.kcMock.Members["werk"] + if len(members) != 1 || members[0].UserID != "u-anna" || members[0].OrgRoles[0] != "IT_ADMIN" { + t.Errorf("members = %+v", members) + } + if n := auditCount(t, h, "action=keycloak.admin_added&tenant_id="+out.Tenant.ID); n != 1 { + t.Errorf("admin_added audits = %d", n) + } + if n := auditCount(t, h, "action=keycloak.invite_sent&tenant_id="+out.Tenant.ID); n != 0 { + t.Errorf("invite_sent audits = %d", n) + } + }) +} + +func TestOnPrem_unknownAdminCreatesNoWorkspace(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + onPremHarness(h, nil) + resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "ghost@onprem.test"}) + if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_in_directory") { + t.Fatalf("create = %d %s, want 404 not_in_directory", resp.StatusCode, body) + } + if resp, _ := h.do("GET", "/v1/tenants/by-slug/werk", nil); resp.StatusCode != http.StatusNotFound { + t.Errorf("workspace left behind: %d", resp.StatusCode) + } + }) +} + +func TestOnPrem_membersAreAddedFromTheDirectory(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + onPremHarness(h, nil) + _, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "anna.admin@onprem.test"}) + ws := decode[createResp](t, body).Tenant + + resp, body := h.do("POST", "/v1/tenants/"+ws.ID+"/invites", map[string]any{"email": "ben.user@onprem.test", "role": "USER"}) + if resp.StatusCode != http.StatusAccepted || !strings.Contains(string(body), `"status":"added"`) { + t.Fatalf("invite = %d %s, want 202 added", resp.StatusCode, body) + } + if len(h.kcMock.Invites) != 0 { + t.Errorf("invitation mails recorded: %+v", h.kcMock.Invites) + } + if n := auditCount(t, h, "action=user.added&tenant_id="+ws.ID); n != 1 { + t.Errorf("user.added audits = %d", n) + } + resp, body = h.do("POST", "/v1/tenants/"+ws.ID+"/invites", map[string]any{"email": "ghost@onprem.test", "role": "USER"}) + if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_in_directory") { + t.Errorf("unknown member = %d %s, want 404 not_in_directory", resp.StatusCode, body) + } + resp, body = h.do("POST", "/v1/admin/tenants/"+ws.ID+"/invites/resend", map[string]any{"email": "ben.user@onprem.test"}) + if resp.StatusCode != http.StatusConflict || !strings.Contains(string(body), "no_invite_mail") { + t.Errorf("resend = %d %s, want 409 no_invite_mail", resp.StatusCode, body) + } + }) +} + +type createResp struct { + Tenant *store.Tenant `json:"tenant"` + InviteURL string `json:"invite_url"` +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 2267430..463808d 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -104,11 +104,24 @@ type apiError struct { // and the ERP customer (each best effort, audited). Shared by POST // /v1/tenants and the trial activation. func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in createTenantReq) (*store.Tenant, kcInvite, *apiError) { + // One spelling of the address for the lookup, the store and Keycloak. + in.AdminEmail = strings.ToLower(strings.TrimSpace(in.AdminEmail)) // An address with an account already belongs to a workspace (or to // staff): reject before anything is created, so no admin-less tenant and // no orphan organization are left behind. A lookup failure falls through // to the best-effort provisioning below. - if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil { + if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil && s.onPrem() { + // On-prem the admin is an existing directory user (the realm's AD + // federation finds them by e-mail); a wrong address must not leave a + // workspace without an admin behind. + exists, err := s.Keycloak.UserExists(ctx, email) + if err != nil { + return nil, kcInvite{}, &apiError{http.StatusServiceUnavailable, "keycloak_unavailable", "directory lookup failed"} + } + if !exists { + return nil, kcInvite{}, &apiError{http.StatusNotFound, "not_in_directory", "no directory account with this e-mail in the groups that may use the platform"} + } + } else if email != "" && s.Keycloak != nil { if taken, err := s.Keycloak.UserExists(ctx, email); err == nil && taken { return nil, kcInvite{}, &apiError{http.StatusConflict, "email_taken", "an account with this email already exists"} } else if err != nil { @@ -152,7 +165,8 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat // tenant back — the operator can resend the invite via the KC admin UI. // We emit an audit event regardless so the failure is traceable. invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ - AdminEmail: in.AdminEmail, AdminName: in.AdminName, + TenantStatus: t.Status, + AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, }) if kcErr != nil { @@ -167,6 +181,12 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, Metadata: map[string]interface{}{"err": invite.MailErr.Error()}, }) + } else if in.AdminEmail != "" && s.onPrem() { + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "keycloak.admin_added", + TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, + Metadata: map[string]interface{}{"role": "IT_ADMIN", "directory": true}, + }) } else if in.AdminEmail != "" { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.invite_sent", diff --git a/openapi.yaml b/openapi.yaml index a6d7759..e92db7b 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -27,6 +27,13 @@ info: PRODUCT_LAUNCH_URLS / PRODUCT_PROVISION_URLS. The trial-offer, trial-terms, catalog request, trial request, admin trial and ERP webhook routes answer 404 `not_available`. + + On-prem every account comes from the customer's directory (Keycloak's AD + federation). Creating a workspace with `admin_email` and inviting a member + attach the existing directory user (no local account, no set-password + mail; invite status `added`). An address with no directory account in the + admitted groups answers 404 `not_in_directory`; resending an invitation + answers 409 `no_invite_mail`. contact: email: oncall@breakpilot.com license: @@ -3366,7 +3373,7 @@ components: properties: user_id: { type: string } email: { type: string, format: email } - status: { type: string, enum: [invited, member] } + status: { type: string, enum: [invited, member, added], description: "added: on-prem, an existing directory user joined; no mail" } TenantCreate: type: object -- 2.54.1 From 30cd577a33b0842b799db0bfc0750e683e33c53d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:24:55 +0100 Subject: [PATCH 4/8] fix(onprem): the cloud admin keeps tenant_status trial Only on-prem passes the workspace's status to Keycloak for its first admin; a cloud demo workspace with an admin wrote demo instead of trial (pinned by a test). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d8cb363d5c98eb802207a327e0a411642b5162f4) --- internal/server/admin_lifecycle.go | 2 +- internal/server/keycloak.go | 10 ++++++++++ internal/server/onprem_test.go | 20 ++++++++++++++++++++ internal/server/tenants.go | 2 +- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 049c9c9..1003f12 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -56,7 +56,7 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { _, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug) switch { case errors.Is(lerr, keycloak.ErrOrgNotFound): - res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email, TenantStatus: t.Status}) + res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email, TenantStatus: s.onPremStatus(t)}) if err != nil { if errors.Is(err, keycloak.ErrUserConflict) { writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant") diff --git a/internal/server/keycloak.go b/internal/server/keycloak.go index 08fb5f6..09bb758 100644 --- a/internal/server/keycloak.go +++ b/internal/server/keycloak.go @@ -24,6 +24,16 @@ type kcInvite struct { MailErr error } +// onPremStatus is the tenant_status a new workspace admin gets in Keycloak: +// the workspace's own on-prem; empty in the cloud, where the adapter keeps +// writing "trial" as before. +func (s *Server) onPremStatus(t *store.Tenant) string { + if s.onPrem() { + return t.Status + } + return "" +} + func (s *Server) provisionKeycloak(ctx context.Context, t *store.Tenant, in keycloak.InviteInput) (kcInvite, error) { if in.AdminEmail == "" { // Skip silently — caller chose not to invite anyone yet (sales-led diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index 207fa99..aad3e9d 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -364,3 +364,23 @@ type createResp struct { Tenant *store.Tenant `json:"tenant"` InviteURL string `json:"invite_url"` } + +// The cloud admin keeps the adapter's default tenant_status ("trial"); only +// on-prem passes the workspace's own. +func TestTenantStatusForTheAdminOnlyOnPrem(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "cloud-demo", "name": "Demo", "kind": "demo", "admin_email": "demo@cloud.test"}); resp.StatusCode != http.StatusCreated { + t.Fatalf("cloud create = %d %s", resp.StatusCode, body) + } + if c := h.kcMock.Created; len(c) != 1 || c[0].TenantStatus != "" { + t.Fatalf("cloud: %+v", c) + } + onPremHarness(h, nil) + if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk", "admin_email": "anna.admin@onprem.test"}); resp.StatusCode != http.StatusCreated { + t.Fatalf("on-prem create = %d %s", resp.StatusCode, body) + } + if c := h.kcMock.Created; len(c) != 2 || c[1].TenantStatus != store.StatusActive { + t.Errorf("on-prem: %+v", c) + } + }) +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 463808d..28c1f5c 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -165,7 +165,7 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat // tenant back — the operator can resend the invite via the KC admin UI. // We emit an audit event regardless so the failure is traceable. invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ - TenantStatus: t.Status, + TenantStatus: s.onPremStatus(t), AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, }) -- 2.54.1 From afe62e47959f70c4a7784dc03505ad4d1e1533b4 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:16:24 +0100 Subject: [PATCH 5/8] feat(onprem): mails come from the installation, not from us On APP_ENV=onprem the registry's mails (new findings, published documents) no longer carry our company signature, address, register entry, contact address or legal pages. They say the installation sent them, name the customer's contact (MAIL_CONTACT) and link the customer's imprint and privacy notice (LEGAL_IMPRINT_URL, LEGAL_PRIVACY_URL), each only when set. mail.View gets a Site; the zero value is the cloud, so cloud mails stay as they were (checked byte for byte against the previous templates) apart from the spelling "Breakpilot", also in the default sender name. The legal line moved from every text template into signature.tmpl. On-prem the registry also refuses to start when MAIL_FROM, PORTAL_URL, INVITE_REDIRECT_URI or LEGAL_* point at breakpilot.com. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6058a94254014bc6473a113453658bb03f122020) --- README.md | 7 +- internal/config/config.go | 18 ++++- internal/config/onprem_test.go | 10 ++- internal/mail/mail_test.go | 66 ++++++++++++++++++- internal/mail/render.go | 31 +++++++++ .../mail/templates/de_document.published.tmpl | 6 +- internal/mail/templates/de_findings.new.tmpl | 2 +- .../mail/templates/de_trial.activated.tmpl | 2 +- .../mail/templates/de_trial.received.tmpl | 2 +- .../mail/templates/en_document.published.tmpl | 6 +- internal/mail/templates/en_findings.new.tmpl | 2 +- internal/mail/templates/layout.html | 3 +- internal/mail/templates/signature.tmpl | 36 +++++++--- internal/server/notify.go | 9 ++- internal/server/onprem_test.go | 37 +++++++++++ internal/server/trialoffers.go | 2 + 16 files changed, 212 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 4704b1b..3602646 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,9 @@ Env vars (override at the shell): | `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 | +| `MAIL_FROM` / `MAIL_FROM_NAME` | `noreply@breakpilot.com` / `Breakpilot` | Sender of platform mail | +| `LEGAL_IMPRINT_URL` / `LEGAL_PRIVACY_URL` | our imprint and privacy notice (cloud); none (on-prem) | Legal links under every mail | +| `MAIL_CONTACT` | empty | On-prem: whom to ask (their IT), shown in every mail; the cloud signature names our contact | | `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`) | | `ERP_BASE_URL` / `ERP_API_KEY` / `ERP_API_SECRET` | empty (outbox idle) | ERPNext / erpmock base URL + `token key:secret` credentials | @@ -121,7 +123,8 @@ State-changing endpoints emit audit events automatically. The OpenAPI contract t - 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. - Accounts only from the customer's directory (Keycloak federates their AD; the package's `keycloak/realm-policy.sh` keeps passwords in AD). The workspace's first admin (`admin_email`) and every invited member must be an existing directory user: they are added to the organization with their role, get no set-password mail and sign in with their directory password. An unknown address answers `not_in_directory`; there is no invitation to resend (`no_invite_mail`). -- 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. +- 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. `MAIL_FROM`, `PORTAL_URL`, `INVITE_REDIRECT_URI` and `LEGAL_*` must not point at `breakpilot.com`. +- Mail is the installation's, not ours: no company signature (address, register entry, our contact), instead a short note that the installation sent it, `MAIL_CONTACT` if set, and the customer's `LEGAL_IMPRINT_URL` / `LEGAL_PRIVACY_URL`, each left out when empty. ## ERP link (M-MIG-7) diff --git a/internal/config/config.go b/internal/config/config.go index 6579c30..31ecb62 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -99,6 +99,13 @@ type Config struct { 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 @@ -214,7 +221,10 @@ func Load() (*Config, error) { SMTPUser: os.Getenv("SMTP_USER"), SMTPPassword: os.Getenv("SMTP_PASSWORD"), MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"), - MailFromName: getenv("MAIL_FROM_NAME", "BreakPilot"), + 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"), @@ -282,6 +292,12 @@ func (c *Config) checkOnPrem() error { 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) diff --git a/internal/config/onprem_test.go b/internal/config/onprem_test.go index 0055150..551d73b 100644 --- a/internal/config/onprem_test.go +++ b/internal/config/onprem_test.go @@ -32,7 +32,8 @@ func onPremEnv(t *testing.T) { } { t.Setenv(k, v) } - for _, k := range []string{"ERP_BASE_URL", "ERP_WEBHOOK_SECRET", "CONTRACT_DOCUMENTS", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL", "SMTP_USER"} { + for _, k := range []string{"ERP_BASE_URL", "ERP_WEBHOOK_SECRET", "CONTRACT_DOCUMENTS", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL", "SMTP_USER", + "LEGAL_IMPRINT_URL", "LEGAL_PRIVACY_URL", "MAIL_CONTACT", "MAIL_FROM_NAME"} { t.Setenv(k, "") } } @@ -46,6 +47,9 @@ func TestLoad_onPremComplete(t *testing.T) { if !c.OnPrem() || c.CatalogEnv() != "onprem" { t.Errorf("OnPrem=%v CatalogEnv=%q", c.OnPrem(), c.CatalogEnv()) } + if c.LegalImprintURL != "" || c.LegalPrivacyURL != "" || c.MailContact != "" || c.MailFromName != "Breakpilot" { + t.Errorf("mail site: %q %q %q %q", c.LegalImprintURL, c.LegalPrivacyURL, c.MailContact, c.MailFromName) + } if c.SMTPTLS != "none" || c.SMTPPort != 25 { t.Errorf("smtp = %s:%d", c.SMTPTLS, c.SMTPPort) } @@ -70,6 +74,10 @@ func TestLoad_onPremRefusesCloudDefaults(t *testing.T) { {"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"`}, + {"our sender", "MAIL_FROM", "noreply@breakpilot.com", "MAIL_FROM points at breakpilot.com"}, + {"our portal", "PORTAL_URL", "https://app.breakpilot.com", "PORTAL_URL points"}, + {"our imprint", "LEGAL_IMPRINT_URL", "https://Breakpilot.com/impressum", "LEGAL_IMPRINT_URL points"}, + {"our privacy notice", "LEGAL_PRIVACY_URL", "https://app.breakpilot.com/datenschutz", "LEGAL_PRIVACY_URL points"}, } { t.Run(c.name, func(t *testing.T) { onPremEnv(t) diff --git a/internal/mail/mail_test.go b/internal/mail/mail_test.go index 3eff389..19b5c40 100644 --- a/internal/mail/mail_test.go +++ b/internal/mail/mail_test.go @@ -129,8 +129,8 @@ func TestSMTP_dialFailure(t *testing.T) { func TestRender_signature(t *testing.T) { for _, kind := range []string{KindDocumentPublished, KindFindingsNew} { for _, c := range []struct{ lang, greeting, team string }{ - {"de", "Mit freundlichen Grüßen", "Ihr BreakPilot-Team"}, - {"en", "Kind regards", "Your BreakPilot team"}, + {"de", "Mit freundlichen Grüßen", "Ihr Breakpilot-Team"}, + {"en", "Kind regards", "Your Breakpilot team"}, } { m, err := Render(kind, c.lang, View{Tenant: "acme", URL: "https://app/acme", D: map[string]any{"title": "T", "target_name": "fw", "new_count": 2}}) @@ -153,6 +153,68 @@ func TestRender_signature(t *testing.T) { } } +// The cloud's legal line: our imprint and privacy notice, overridable. +func TestRender_cloudLegalLinks(t *testing.T) { + m, _ := Render(KindFindingsNew, "de", View{URL: "https://x", D: map[string]any{"target_name": "fw", "new_count": 2}}) + if !strings.Contains(m.Text, "Breakpilot GmbH · "+CloudImprint) || !strings.Contains(m.HTML, `href="`+CloudImprint+`"`) || !strings.Contains(m.HTML, `href="`+CloudPrivacy+`"`) { + t.Fatalf("cloud defaults:\n%s", m.Text) + } + m, _ = Render(KindTrialReceived, "de", View{Site: Site{Imprint: "https://i.test", Privacy: "https://p.test"}}) + if !strings.Contains(m.Text, "Breakpilot GmbH · https://i.test · https://p.test") || strings.Contains(m.HTML, CloudImprint) { + t.Fatalf("override:\n%s", m.Text) + } +} + +// On a customer's installation no mail carries our company data, address, +// contact or legal pages; it names their pages and contact when given. +func TestRender_onPrem(t *testing.T) { + d := map[string]any{"title": "T", "target_name": "fw", "new_count": 2} + ours := []string{"breakpilot.com", "Breakpilot GmbH", "Bodman", "DE464808363", "HRB 736403", "Parnerkar", "Mit freundlichen", "Kind regards"} + for _, kind := range []string{KindDocumentPublished, KindFindingsNew} { + for _, c := range []struct{ lang, note, ask, imprint, privacy string }{ + {"de", "die Installation in Ihrem", "Fragen", "Impressum", "Datenschutz"}, + {"en", "the installation in your company", "Questions", "Imprint", "Privacy"}, + } { + full, err := Render(kind, c.lang, View{Tenant: "werk", URL: "https://bp.onprem.test/werk", + D: d, Site: Site{OnPrem: true, Imprint: "https://intranet.onprem.test/impressum", Privacy: "https://intranet.onprem.test/datenschutz", Contact: "IT "}}) + if err != nil { + t.Fatal(err) + } + for _, body := range []string{full.Text, full.HTML} { + for _, bad := range ours { + if strings.Contains(body, bad) { + t.Errorf("%s/%s: %q in an on-prem mail", kind, c.lang, bad) + } + } + for _, want := range []string{c.note, c.ask, "https://intranet.onprem.test/impressum", "https://intranet.onprem.test/datenschutz"} { + if !strings.Contains(body, want) { + t.Errorf("%s/%s: %q missing", kind, c.lang, want) + } + } + } + if !strings.Contains(full.Text, "IT ") || !strings.Contains(full.HTML, "IT <it@onprem.test>") { + t.Errorf("%s/%s: contact not shown (escaped in HTML)", kind, c.lang) + } + if strings.Index(full.Text, c.note) > strings.Index(full.Text, "\n--\n") { + t.Errorf("%s/%s: note after the footer", kind, c.lang) + } + // Nothing named: no legal line, no contact, no empty link. + bare, _ := Render(kind, c.lang, View{Tenant: "werk", URL: "https://bp.onprem.test/werk", D: d, Site: Site{OnPrem: true}}) + for _, body := range []string{bare.Text, bare.HTML} { + for _, bad := range append(ours, c.imprint+":", c.ask+":", `href=""`) { + if strings.Contains(body, bad) { + t.Errorf("%s/%s bare: %q", kind, c.lang, bad) + } + } + } + if !strings.HasSuffix(bare.Text, "werk verwalten.\n") && !strings.HasSuffix(bare.Text, "einsehen dürfen.\n") && + !strings.HasSuffix(bare.Text, ".\n") { + t.Errorf("%s/%s bare: text ends %q", kind, c.lang, bare.Text[max(0, len(bare.Text)-40):]) + } + } + } +} + func TestBuild_attachmentsAreAMixedMultipart(t *testing.T) { pdf := bytes.Repeat([]byte("%PDF-1.7 Testbedingungen \x00\xff"), 20) raw := Build(Message{To: "a@b.de", Subject: "Aktiviert", Text: "Text ä", HTML: "

ä

", diff --git a/internal/mail/render.go b/internal/mail/render.go index 40c4f35..bf01a4e 100644 --- a/internal/mail/render.go +++ b/internal/mail/render.go @@ -37,8 +37,31 @@ type View struct { URL string Subject string D map[string]any + // Site is who sends the mail; the zero value is the cloud. + Site Site } +// Site decides the signature and the legal links of every mail. +// +// In the cloud the mail comes from Breakpilot GmbH: the company signature +// (no-reply sender, address, register entry) and our imprint and privacy +// notice. On a customer's own installation (APP_ENV=onprem) it comes from +// their system, through their relay and from their address: no company +// signature of ours, their imprint and privacy notice if they name one, and +// whom to ask (their IT) instead of our contact address. +type Site struct { + OnPrem bool + Imprint string // legal notice URL; on-prem empty = left out + Privacy string // privacy notice URL; on-prem empty = left out + Contact string // on-prem: whom to ask (an address or a short text); empty = left out +} + +// Cloud legal pages, used when a cloud Site leaves them empty. +const ( + CloudImprint = "https://breakpilot.com/impressum" + CloudPrivacy = "https://app.breakpilot.com/datenschutz" +) + // Render builds the subject, text and HTML body of kind in locale ("de" // unless "en"). HTML values are escaped by html/template; the text body and // subject are plain. @@ -50,6 +73,14 @@ func Render(kind, locale string, v View) (Message, error) { locale = "de" } v.Lang = locale + if !v.Site.OnPrem { + if v.Site.Imprint == "" { + v.Site.Imprint = CloudImprint + } + if v.Site.Privacy == "" { + v.Site.Privacy = CloudPrivacy + } + } if v.D == nil { v.D = map[string]any{} } diff --git a/internal/mail/templates/de_document.published.tmpl b/internal/mail/templates/de_document.published.tmpl index 4e44a70..5ba92fc 100644 --- a/internal/mail/templates/de_document.published.tmpl +++ b/internal/mail/templates/de_document.published.tmpl @@ -2,13 +2,13 @@ {{define "button"}}Dokument öffnen{{end}} {{define "footer"}}Sie erhalten diese E-Mail, weil Sie im Arbeitsbereich {{.Tenant}} Unterlagen einsehen dürfen.{{end}} {{define "html"}}

Ein neues Dokument liegt für Sie bereit

-

BreakPilot hat im Arbeitsbereich {{.Tenant}} ein Dokument veröffentlicht:

+

Breakpilot hat im Arbeitsbereich {{.Tenant}} ein Dokument veröffentlicht:

{{.D.title}}

{{if .D.description}}

{{.D.description}}

{{end}}

Sie finden es im Portal unter Dokumente. Jeder Download wird im Audit-Log festgehalten.

{{end}} {{define "text"}}Ein neues Dokument liegt für Sie bereit -BreakPilot hat im Arbeitsbereich {{.Tenant}} ein Dokument veröffentlicht: +Breakpilot hat im Arbeitsbereich {{.Tenant}} ein Dokument veröffentlicht: {{.D.title}} {{if .D.description}} {{.D.description}} @@ -20,4 +20,4 @@ Sie finden es im Portal unter "Dokumente": -- Sie erhalten diese E-Mail, weil Sie im Arbeitsbereich {{.Tenant}} Unterlagen einsehen dürfen. -BreakPilot GmbH · https://breakpilot.com/impressum{{end}} +{{template "legal_text" .}}{{end}} diff --git a/internal/mail/templates/de_findings.new.tmpl b/internal/mail/templates/de_findings.new.tmpl index 57ebff5..356324a 100644 --- a/internal/mail/templates/de_findings.new.tmpl +++ b/internal/mail/templates/de_findings.new.tmpl @@ -28,4 +28,4 @@ Befunde ansehen: -- Sie erhalten diese E-Mail, weil Sie den Arbeitsbereich {{.Tenant}} verwalten. -Breakpilot GmbH · https://breakpilot.com/impressum{{end}} +{{template "legal_text" .}}{{end}} diff --git a/internal/mail/templates/de_trial.activated.tmpl b/internal/mail/templates/de_trial.activated.tmpl index 65623cf..ff6116d 100644 --- a/internal/mail/templates/de_trial.activated.tmpl +++ b/internal/mail/templates/de_trial.activated.tmpl @@ -37,4 +37,4 @@ Die Vertragsbedingungen im Anhang sind die für Ihren Vertrag geltende Fassung. -- Sie erhalten diese E-Mail, weil Sie einen kostenlosen Breakpilot-Testzugang für {{.D.company_name}} angefordert und Ihre E-Mail-Adresse bestätigt haben. -Breakpilot GmbH · https://breakpilot.com/impressum · https://app.breakpilot.com/datenschutz{{end}} +{{template "legal_text_full" .}}{{end}} diff --git a/internal/mail/templates/de_trial.received.tmpl b/internal/mail/templates/de_trial.received.tmpl index 622a2c8..db598c7 100644 --- a/internal/mail/templates/de_trial.received.tmpl +++ b/internal/mail/templates/de_trial.received.tmpl @@ -33,4 +33,4 @@ Der Bestätigungslink ist {{.D.valid_hours}} Stunden gültig und kann einmal ver -- Sie erhalten diese E-Mail, weil mit dieser Adresse ein kostenloser Breakpilot-Testzugang angefordert wurde. Waren Sie das nicht, ignorieren Sie diese E-Mail: Ohne Bestätigung wird nichts freigeschaltet. -Breakpilot GmbH · https://breakpilot.com/impressum · https://app.breakpilot.com/datenschutz{{end}} +{{template "legal_text_full" .}}{{end}} diff --git a/internal/mail/templates/en_document.published.tmpl b/internal/mail/templates/en_document.published.tmpl index dbf3c4f..0bf692e 100644 --- a/internal/mail/templates/en_document.published.tmpl +++ b/internal/mail/templates/en_document.published.tmpl @@ -2,13 +2,13 @@ {{define "button"}}Open the document{{end}} {{define "footer"}}You receive this email because you may view documents in the {{.Tenant}} workspace.{{end}} {{define "html"}}

A new document is ready for you

-

BreakPilot published a document in the {{.Tenant}} workspace:

+

Breakpilot published a document in the {{.Tenant}} workspace:

{{.D.title}}

{{if .D.description}}

{{.D.description}}

{{end}}

You find it in the portal under Documents. Every download is recorded in the audit log.

{{end}} {{define "text"}}A new document is ready for you -BreakPilot published a document in the {{.Tenant}} workspace: +Breakpilot published a document in the {{.Tenant}} workspace: {{.D.title}} {{if .D.description}} {{.D.description}} @@ -20,4 +20,4 @@ You find it in the portal under "Documents": -- You receive this email because you may view documents in the {{.Tenant}} workspace. -BreakPilot GmbH · https://breakpilot.com/impressum{{end}} +{{template "legal_text" .}}{{end}} diff --git a/internal/mail/templates/en_findings.new.tmpl b/internal/mail/templates/en_findings.new.tmpl index ee9c957..8c7fa33 100644 --- a/internal/mail/templates/en_findings.new.tmpl +++ b/internal/mail/templates/en_findings.new.tmpl @@ -28,4 +28,4 @@ View the findings: -- You receive this email because you administer the {{.Tenant}} workspace. -Breakpilot GmbH · https://breakpilot.com/impressum{{end}} +{{template "legal_text" .}}{{end}} diff --git a/internal/mail/templates/layout.html b/internal/mail/templates/layout.html index 8c1f4d8..0a307a5 100644 --- a/internal/mail/templates/layout.html +++ b/internal/mail/templates/layout.html @@ -20,8 +20,7 @@ {{template "signature_html" .}} -{{template "footer" .}}
-Breakpilot GmbH · {{if eq .Lang "de"}}Impressum{{else}}Imprint{{end}} · {{if eq .Lang "de"}}Datenschutz{{else}}Privacy{{end}} +{{template "footer" .}}{{template "legal_html" .}} diff --git a/internal/mail/templates/signature.tmpl b/internal/mail/templates/signature.tmpl index 82c9652..d8a830a 100644 --- a/internal/mail/templates/signature.tmpl +++ b/internal/mail/templates/signature.tmpl @@ -1,10 +1,12 @@ {{/* The company signature of every mail, modelled on the founders' signature (Brand_Assets/Email_Signature) but for the no-reply sender. Company data - as in the website's Impressum. */}} -{{define "signature_html"}} + as in the website's Impressum. On a customer's own installation + (.Site.OnPrem) the mail comes from their system instead: a short note, + whom to ask there, no company data of ours. */}} +{{define "signature_html"}}{{if .Site.OnPrem}}{{template "signature_onprem_html" .}}{{else}}
{{if eq .Lang "de"}}Mit freundlichen Grüßen{{else}}Kind regards{{end}}
-
{{if eq .Lang "de"}}Ihr BreakPilot-Team{{else}}Your BreakPilot team{{end}}
+
{{if eq .Lang "de"}}Ihr Breakpilot-Team{{else}}Your Breakpilot team{{end}}
Breakpilot GmbH
In Steinäckern 16
78351 Bodman-Ludwigshafen
@@ -15,10 +17,10 @@
USt.-ID: DE464808363
Amtsgericht Freiburg, HRB 736403
{{if eq .Lang "de"}}Geschäftsführer{{else}}Managing directors{{end}}: Benjamin Bönisch {{if eq .Lang "de"}}und{{else}}and{{end}} Sharang Deepak Parnerkar
-
{{end}} -{{define "signature_text"}}{{if eq .Lang "de"}}Mit freundlichen Grüßen -Ihr BreakPilot-Team{{else}}Kind regards -Your BreakPilot team{{end}} +{{end}}{{end}} +{{define "signature_text"}}{{if .Site.OnPrem}}{{template "signature_onprem_text" .}}{{else}}{{if eq .Lang "de"}}Mit freundlichen Grüßen +Ihr Breakpilot-Team{{else}}Kind regards +Your Breakpilot team{{end}} Breakpilot GmbH In Steinäckern 16 @@ -30,4 +32,22 @@ Web: www.breakpilot.com USt.-ID: DE464808363 Amtsgericht Freiburg, HRB 736403 -{{if eq .Lang "de"}}Geschäftsführer{{else}}Managing directors{{end}}: Benjamin Bönisch {{if eq .Lang "de"}}und{{else}}and{{end}} Sharang Deepak Parnerkar{{end}} +{{if eq .Lang "de"}}Geschäftsführer{{else}}Managing directors{{end}}: Benjamin Bönisch {{if eq .Lang "de"}}und{{else}}and{{end}} Sharang Deepak Parnerkar{{end}}{{end}} +{{define "signature_onprem_html"}}
+{{if eq .Lang "de"}}Diese Nachricht hat Breakpilot verschickt, die Installation in Ihrem Unternehmen. Antworten an diese Adresse werden nicht gelesen.{{else}}This message was sent by Breakpilot, the installation in your company. Replies to this address are not read.{{end}} +{{with .Site.Contact}}
{{if eq $.Lang "de"}}Fragen{{else}}Questions{{end}}: {{.}}{{end}} +
{{end}} +{{define "signature_onprem_text"}}{{if eq .Lang "de"}}Diese Nachricht hat Breakpilot verschickt, die Installation in Ihrem +Unternehmen. Antworten an diese Adresse werden nicht gelesen.{{else}}This message was sent by Breakpilot, the installation in your company. +Replies to this address are not read.{{end}}{{with .Site.Contact}} +{{if eq $.Lang "de"}}Fragen{{else}}Questions{{end}}: {{.}}{{end}}{{end}} + +{{/* The legal line under the footer. Cloud: our company with imprint (and, + in the trial mails, the privacy notice). On-prem: the customer's pages, + each only if named. */}} +{{define "legal_text"}}{{if .Site.OnPrem}}{{template "legal_onprem_text" .}}{{else}}Breakpilot GmbH · {{.Site.Imprint}}{{end}}{{end}} +{{define "legal_text_full"}}{{if .Site.OnPrem}}{{template "legal_onprem_text" .}}{{else}}Breakpilot GmbH · {{.Site.Imprint}} · {{.Site.Privacy}}{{end}}{{end}} +{{define "legal_onprem_text"}}{{with .Site.Imprint}}{{if eq $.Lang "de"}}Impressum{{else}}Imprint{{end}}: {{.}}{{end}}{{if and .Site.Imprint .Site.Privacy}} · {{end}}{{with .Site.Privacy}}{{if eq $.Lang "de"}}Datenschutz{{else}}Privacy{{end}}: {{.}}{{end}}{{end}} +{{define "legal_html"}}{{if .Site.OnPrem}}{{if or .Site.Imprint .Site.Privacy}}
+{{with .Site.Imprint}}{{if eq $.Lang "de"}}Impressum{{else}}Imprint{{end}}{{end}}{{if and .Site.Imprint .Site.Privacy}} · {{end}}{{with .Site.Privacy}}{{if eq $.Lang "de"}}Datenschutz{{else}}Privacy{{end}}{{end}}{{end}}{{else}}
+Breakpilot GmbH · {{if eq .Lang "de"}}Impressum{{else}}Imprint{{end}} · {{if eq .Lang "de"}}Datenschutz{{else}}Privacy{{end}}{{end}}{{end}} diff --git a/internal/server/notify.go b/internal/server/notify.go index 4888775..2b9f218 100644 --- a/internal/server/notify.go +++ b/internal/server/notify.go @@ -37,6 +37,13 @@ func (s *Server) portalURL() string { return u } +// mailSite is who the registry's mails come from (mail.Site): the cloud +// company, or the customer's installation with their legal pages and contact. +func (s *Server) mailSite() mail.Site { + c := s.cfg() + return mail.Site{OnPrem: c.OnPrem(), Imprint: c.LegalImprintURL, Privacy: c.LegalPrivacyURL, Contact: c.MailContact} +} + // notifyTenant queues kind for every enabled member of t whose bundle grants // the kind's capability. Demo tenants get nothing. Returns how many rows were // queued (0 for a repeat of the same key). @@ -231,7 +238,7 @@ func (s *Server) DrainMail(ctx context.Context) (int, error) { func (s *Server) sendMail(ctx context.Context, it store.MailItem) error { tenant, _ := it.Data["tenant_name"].(string) url, _ := it.Data["url"].(string) - msg, err := mail.Render(it.Kind, it.Locale, mail.View{Tenant: tenant, URL: url, D: it.Data}) + msg, err := mail.Render(it.Kind, it.Locale, mail.View{Tenant: tenant, URL: url, D: it.Data, Site: s.mailSite()}) if err != nil { return err } diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index aad3e9d..e3206ff 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -12,6 +12,7 @@ import ( "time" "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/mail" "git.breakpilot.com/platform/tenant-registry/internal/store" ) @@ -384,3 +385,39 @@ func TestTenantStatusForTheAdminOnlyOnPrem(t *testing.T) { } }) } + +// A notification on-prem is the installation's mail: no company signature or +// legal pages of ours, the customer's contact and pages from the values. +func TestOnPrem_notificationMailIsTheInstallations(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + onPremHarness(h, nil) + h.app.Cfg.PortalURL = "https://bp.onprem.test" + h.app.Cfg.MailContact = "it@onprem.test" + h.app.Cfg.LegalPrivacyURL = "https://intranet.onprem.test/datenschutz" + rec := &mail.Recorder{} + h.app.Mail = rec + seedMembers(h, "acme") + body := map[string]any{"tenant_id": h.tenant.ID, "kind": "findings.new", "idempotency_key": "scan-1", + "data": map[string]any{"target_name": "Presse", "new_count": 1, "url": "https://pruefwerk.onprem.test/targets/t1"}} + if resp, raw := h.do("POST", "/v1/notifications", body); resp.StatusCode != 202 { + t.Fatalf("queue: %d %s", resp.StatusCode, raw) + } + if _, err := h.app.DrainMail(context.Background()); err != nil { + t.Fatal(err) + } + msgs := rec.Messages() + if len(msgs) == 0 { + t.Fatal("no mail") + } + for _, m := range msgs { + for _, b := range []string{m.Text, m.HTML} { + if strings.Contains(b, "breakpilot.com") || strings.Contains(b, "Breakpilot GmbH") { + t.Fatalf("cloud data in an on-prem mail:\n%s", b) + } + if !strings.Contains(b, "it@onprem.test") || !strings.Contains(b, "https://intranet.onprem.test/datenschutz") { + t.Fatalf("contact or privacy link missing:\n%s", b) + } + } + } + }) +} diff --git a/internal/server/trialoffers.go b/internal/server/trialoffers.go index 440709d..96797ec 100644 --- a/internal/server/trialoffers.go +++ b/internal/server/trialoffers.go @@ -249,6 +249,7 @@ func (s *Server) sendReceipt(ctx context.Context, o *store.TrialOffer, token str return false } msg, err := bpmail.Render(bpmail.KindTrialReceived, "de", bpmail.View{ + Site: s.mailSite(), Tenant: o.CompanyName, URL: s.portalURL() + "/start/bestaetigen?token=" + token, D: map[string]any{ @@ -494,6 +495,7 @@ func (s *Server) sendActivation(ctx context.Context, o *store.TrialOffer, t *sto } workspace := s.portalURL() + "/" + t.Slug msg, err := bpmail.Render(bpmail.KindTrialActivated, "de", bpmail.View{ + Site: s.mailSite(), Tenant: o.CompanyName, URL: workspace + "/dashboard", D: map[string]any{ -- 2.54.1 From 76b836653a6a8c4e8b33339082276cf9c6587ca5 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:00:45 +0100 Subject: [PATCH 6/8] fix(onprem): only directory users join a workspace In directory mode the registry attached any Keycloak user found by e-mail. On an installation the realm also holds our local staff accounts (onprem keycloak/staff-account.sh): a workspace admin could add one to their team (201 added), giving our support account workspace attributes and membership. Found in the test install. Now only a user with a federation link (from the AD) counts, for the first admin and for members; a local account answers not_in_directory like an unknown address. The cloud is unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1b821baa7bc5ec4113855190c6ffed4d2c1102cb) --- internal/keycloak/directory_test.go | 28 +++++++++++++++++++ internal/keycloak/members.go | 5 +++- internal/keycloak/orgs.go | 42 +++++++++++++++++++++++------ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/internal/keycloak/directory_test.go b/internal/keycloak/directory_test.go index a8af6e7..ab4ebf1 100644 --- a/internal/keycloak/directory_test.go +++ b/internal/keycloak/directory_test.go @@ -12,9 +12,37 @@ func newDirectoryKC(t *testing.T) (*membersKC, *HTTPAdapter) { t.Helper() k, a := newMembersKC(t) a.cfg.DirectoryUsers = true + // The test users come from the directory (the AD federation), as on an installation. + for id, u := range k.users { + u.FederationLink = "ldap-ad" + k.users[id] = u + } return k, a } +// A local account (our staff on an installation) is no directory user: neither the first +// admin of a workspace nor a member, whatever its address. +func TestDirectory_localAccountIsNotADirectoryUser(t *testing.T) { + k, a := newDirectoryKC(t) + k.users["u-staff"] = memberRepresentation{ID: "u-staff", Username: "bp-support", Email: "support@staff.test", Enabled: true} + if _, err := a.CreateOrgAndInvite(context.Background(), InviteInput{TenantID: "t-9", Slug: "staffws", Name: "S", AdminEmail: "support@staff.test"}); !errors.Is(err, ErrNotInDirectory) { + t.Errorf("staff as workspace admin: %v, want ErrNotInDirectory", err) + } + if _, err := a.InviteMember(context.Background(), MemberInviteInput{TenantID: "t-1", Slug: "acme", Email: "support@staff.test", Role: "USER"}); !errors.Is(err, ErrNotInDirectory) { + t.Errorf("staff as member: %v, want ErrNotInDirectory", err) + } + if len(k.orgsCreated) != 0 || len(k.puts["u-staff"]) != 0 { + t.Errorf("orgs %v, attributes written %v", k.orgsCreated, k.puts["u-staff"]) + } + for org, ids := range k.members { + for _, id := range ids { + if id == "u-staff" { + t.Errorf("staff joined %s", org) + } + } + } +} + func TestDirectory_adminIsAttachedWithoutMail(t *testing.T) { k, a := newDirectoryKC(t) res, err := a.CreateOrgAndInvite(context.Background(), InviteInput{ diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 81b32ae..b07e8fc 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -24,6 +24,9 @@ type memberRepresentation struct { Enabled bool `json:"enabled"` CreatedTimestamp int64 `json:"createdTimestamp"` // epoch millis Attributes map[string][]string `json:"attributes"` + // FederationLink names the user storage (the AD federation) a user comes from; empty for a + // local account. + FederationLink string `json:"federationLink,omitempty"` } func (m memberRepresentation) toOrgMember() OrgMember { @@ -107,7 +110,7 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (* "tenant_status": {in.TenantStatus}, } created := false - userID, err := a.findUserByEmail(ctx, in.Email) + userID, err := a.findMemberUser(ctx, in.Email) switch { case err == nil: // Existing user (possibly created by an earlier, half-failed invite): diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index fe396c1..2f46c98 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -193,7 +193,7 @@ func (a *HTTPAdapter) createOrg(ctx context.Context, in InviteInput) (string, er // this person the IT admin), the user joins the organization, and no mail is // sent: they sign in with their directory password. func (a *HTTPAdapter) attachDirectoryAdmin(ctx context.Context, in InviteInput) (*InviteResult, error) { - userID, err := a.findUserByEmail(ctx, in.AdminEmail) + userID, err := a.findDirectoryUserByEmail(ctx, in.AdminEmail) if errors.Is(err, errUserLookupMiss) { return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.AdminEmail) } @@ -346,28 +346,54 @@ func (a *HTTPAdapter) UserExists(ctx context.Context, email string) (bool, error } func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string, error) { + id, _, err := a.lookupUserByEmail(ctx, email) + return id, err +} + +// findDirectoryUserByEmail is findUserByEmail for directory mode: only a user from the +// directory (a federation link) counts. A local account with that address -- our staff +// accounts on an installation (onprem keycloak/staff-account.sh) -- is no workspace member: +// errUserLookupMiss, so callers answer not_in_directory. +func (a *HTTPAdapter) findDirectoryUserByEmail(ctx context.Context, email string) (string, error) { + id, federated, err := a.lookupUserByEmail(ctx, email) + if err == nil && !federated { + return "", errUserLookupMiss + } + return id, err +} + +// findMemberUser looks up a member to add: any user in the cloud, a directory user on-prem. +func (a *HTTPAdapter) findMemberUser(ctx context.Context, email string) (string, error) { + if a.cfg.DirectoryUsers { + return a.findDirectoryUserByEmail(ctx, email) + } + return a.findUserByEmail(ctx, email) +} + +func (a *HTTPAdapter) lookupUserByEmail(ctx context.Context, email string) (id string, federated bool, err error) { resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/users?email=%s&exact=true", url.QueryEscape(email)), nil, nil) if err != nil { - return "", err + return "", false, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode/100 != 2 { - return "", fmt.Errorf("find user: %d", resp.StatusCode) + return "", false, fmt.Errorf("find user: %d", resp.StatusCode) } var users []struct { - ID string `json:"id"` - Email string `json:"email"` + ID string `json:"id"` + Email string `json:"email"` + FederationLink string `json:"federationLink"` } if err := json.NewDecoder(resp.Body).Decode(&users); err != nil { - return "", err + return "", false, err } for _, u := range users { if strings.EqualFold(u.Email, email) { - return u.ID, nil + return u.ID, u.FederationLink != "", nil } } - return "", errUserLookupMiss + return "", false, errUserLookupMiss } // inviteRedirect is the configured invite redirect with "{slug}" replaced by -- 2.54.1 From ebeed5f0cf6b328e65e0797a34b58c90f30ab39d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:15:17 +0100 Subject: [PATCH 7/8] fix(migrations): werkpilot description is 0033 (0032 is connections) main took 0032 for tenant connections (#145) while the on-prem branch had 0032 for the neutral Werkpilot text; golang-migrate refuses two files with one version. Co-Authored-By: Claude Opus 5.5 --- ...t_description.down.sql => 0033_werkpilot_description.down.sql} | 0 ...pilot_description.up.sql => 0033_werkpilot_description.up.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename migrations/{0032_werkpilot_description.down.sql => 0033_werkpilot_description.down.sql} (100%) rename migrations/{0032_werkpilot_description.up.sql => 0033_werkpilot_description.up.sql} (100%) diff --git a/migrations/0032_werkpilot_description.down.sql b/migrations/0033_werkpilot_description.down.sql similarity index 100% rename from migrations/0032_werkpilot_description.down.sql rename to migrations/0033_werkpilot_description.down.sql diff --git a/migrations/0032_werkpilot_description.up.sql b/migrations/0033_werkpilot_description.up.sql similarity index 100% rename from migrations/0032_werkpilot_description.up.sql rename to migrations/0033_werkpilot_description.up.sql -- 2.54.1 From ffe10d5ca67313fecb840ddbc3f1dba409972a6f Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:23:30 +0100 Subject: [PATCH 8/8] fix(lint): tagged switch on the invite status; close checked in the relay test Co-Authored-By: Claude Opus 5.5 --- internal/mail/plain_test.go | 2 +- internal/server/admin_lifecycle.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/mail/plain_test.go b/internal/mail/plain_test.go index 63e4701..20dbeaf 100644 --- a/internal/mail/plain_test.go +++ b/internal/mail/plain_test.go @@ -24,7 +24,7 @@ func plainRelay(t *testing.T) (host string, port int, cmds chan string) { if err != nil { return } - defer conn.Close() + defer func() { _ = conn.Close() }() r := bufio.NewReader(conn) say := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) } say("220 relay.onprem.test ESMTP") diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 1003f12..1a809b2 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -79,10 +79,10 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { s.writeKeycloakError(w, t.ID, "reprovision", err) return } - switch { - case res.Status == keycloak.InviteStatusAdded: + switch res.Status { + case keycloak.InviteStatusAdded: outcome = "added" - case res.Status == keycloak.InviteStatusMember: + case keycloak.InviteStatusMember: err := s.Keycloak.ResendInvite(ctx, t.Slug, email) switch { case errors.Is(err, keycloak.ErrNoInviteMail): -- 2.54.1