feat(onprem): APP_ENV=onprem for a customer's own node #142
No files matched your search
@@ -36,7 +36,7 @@ Env vars (override at the shell):
|
||||
|
||||
| Var | Default | Purpose |
|
||||
|---|---|---|
|
||||
| `APP_ENV` | `dev` | one of `dev`, `stage`, `prod` |
|
||||
| `APP_ENV` | `dev` | one of `dev`, `stage`, `prod`, `onprem` (see [On-prem](#on-prem)) |
|
||||
| `ADDR` | `:8090` | listen address (avoids Keycloak's :8080) |
|
||||
| `KEYCLOAK_ISSUER` | `http://localhost:8080/realms/breakpilot-dev` | OIDC issuer URL (the JWT signer) |
|
||||
| `DATABASE_URL` | empty (in-memory store fallback) | Postgres DSN; service uses Memory when empty |
|
||||
@@ -50,6 +50,9 @@ Env vars (override at the shell):
|
||||
| `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing |
|
||||
| `DOCUMENTS_MAX_MB` | `200` | Upload limit per document |
|
||||
| `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) |
|
||||
| `SMTP_TLS` | `tls` on port 465, else `starttls` | `starttls`, `tls` or `none` (a plain relay inside the customer's network; refused together with `SMTP_USER`) |
|
||||
| `PRODUCTS` | empty (the catalog's own enabled flags) | Comma list of the products this installation offers; a listed product is offered even if its row is disabled |
|
||||
| `PRODUCT_LAUNCH_URLS` / `PRODUCT_PROVISION_URLS` | empty (the URLs seeded per environment) | `key=url,key=url` overrides; a provision URL carries `{id}`. Checked at start |
|
||||
| `MAIL_FROM` / `MAIL_FROM_NAME` | `noreply@breakpilot.com` / `BreakPilot` | Sender of platform mail |
|
||||
| `PORTAL_URL` | `https://app.breakpilot.com` | Portal origin for links in mail |
|
||||
| `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) |
|
||||
@@ -109,6 +112,16 @@ Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary:
|
||||
|
||||
State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec.
|
||||
|
||||
## On-prem
|
||||
|
||||
`APP_ENV=onprem` runs the registry on a customer's own node (the package in `platform/onprem`). Differences from the cloud:
|
||||
|
||||
- No ERP: the outbox takes nothing, the ERP webhook is off, and `ERP_BASE_URL` / `ERP_WEBHOOK_SECRET` must be empty.
|
||||
- No trial: a new workspace starts `active`, and the ladder never escalates by time (the licence is the contract).
|
||||
- No sign-up and no sales requests: the trial-offer, trial-terms, catalog request, trial request and admin trial routes answer 404 `not_available`.
|
||||
- Products and URLs only from `PRODUCTS` and `PRODUCT_*_URLS`. The seeded `stage`/`prod` URLs are never used, so provisioning never reaches a Breakpilot host (the test install in `platform/onprem` checks all outbound traffic). Each listed product needs a launch URL; an unknown key stops the start. The catalog offers no trials.
|
||||
- No cloud defaults: the registry refuses to start without `AUTH_ENABLED=true`, `AUTHZ_RULES`, `LICENCE_SIGNING_KEY`, `DATABASE_URL`, the Keycloak admin settings, `PORTAL_URL`, `INVITE_CLIENT_ID`, `INVITE_REDIRECT_URI`, `MAIL_FROM` and `PRODUCTS`, and without `LITELLM_BASE_URL` when `LITELLM_MASTER_KEY` is set. Contract documents stay off.
|
||||
|
||||
## ERP link (M-MIG-7)
|
||||
|
||||
ERPNext is the commercial authority; the registry mirrors it and moves tenants
|
||||
|
||||
+18
-2
@@ -82,6 +82,22 @@ func main() {
|
||||
s = pg
|
||||
}
|
||||
defer s.Close()
|
||||
kind := storeKind(s)
|
||||
// PRODUCTS / PRODUCT_*_URLS (on-prem: the only source of product URLs).
|
||||
if err := store.CheckProductKeys(bootCtx, s, cfg.Products, cfg.LaunchURLs, cfg.ProvisionURLs); err != nil {
|
||||
slog.Error("product overrides invalid", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
s = store.WithProductOverrides(s, cfg.CatalogEnv(), cfg.Products, cfg.LaunchURLs, cfg.ProvisionURLs)
|
||||
if cfg.OnPrem() {
|
||||
var noProvision []string
|
||||
for _, k := range cfg.Products {
|
||||
if cfg.ProvisionURLs[k] == "" {
|
||||
noProvision = append(noProvision, k)
|
||||
}
|
||||
}
|
||||
slog.Info("on-prem mode: no ERP, no trial ladder, no sign-up", "products", cfg.Products, "without_provisioning", noProvision)
|
||||
}
|
||||
|
||||
var kc keycloak.Adapter
|
||||
if cfg.KeycloakAdminURL != "" && cfg.KeycloakClientID != "" {
|
||||
@@ -189,7 +205,7 @@ func main() {
|
||||
logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503")
|
||||
}
|
||||
var mailer mail.Sender
|
||||
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName}); mc.Configured() {
|
||||
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName, TLS: cfg.SMTPTLS}); mc.Configured() {
|
||||
mailer = &mail.SMTP{Cfg: mc}
|
||||
}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Secrets: secrets, Objects: objects, Mail: mailer}
|
||||
@@ -215,7 +231,7 @@ func main() {
|
||||
go app.RunModuleUserCount(ctx, 15*time.Minute)
|
||||
|
||||
go func() {
|
||||
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s))
|
||||
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", kind)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Error("server crashed", "err", err)
|
||||
os.Exit(1)
|
||||
|
||||
+135
-5
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+21
-3
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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: "<p>hi</p>"}); 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)
|
||||
}
|
||||
}
|
||||
@@ -24,18 +24,31 @@ func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
items := make([]store.CatalogEntry, 0, len(products))
|
||||
for _, p := range products {
|
||||
items = append(items, p.Catalog(s.env()))
|
||||
e := p.Catalog(s.env())
|
||||
if s.onPrem() {
|
||||
e.SupportsTrial = false // no trials on a customer's node: the portal hides the button
|
||||
}
|
||||
items = append(items, e)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
// env is the environment key used for per-env product URLs. "dev" reads the
|
||||
// stage URLs so a laptop portal links somewhere real.
|
||||
func (s *Server) env() string {
|
||||
if s.Cfg == nil || s.Cfg.Env == "" || s.Cfg.Env == "dev" {
|
||||
return "stage"
|
||||
// env is the environment key used for per-env product URLs (see
|
||||
// config.CatalogEnv). On-prem the catalog has no seeded URLs; they come from
|
||||
// PRODUCT_*_URLS through store.ProductOverrides.
|
||||
func (s *Server) env() string { return s.Cfg.CatalogEnv() }
|
||||
|
||||
// onPrem reports a registry on a customer's node (APP_ENV=onprem).
|
||||
func (s *Server) onPrem() bool { return s.Cfg.OnPrem() }
|
||||
|
||||
// notOnPrem answers 404 for a feature that does not exist on-prem (sign-up,
|
||||
// trial offers, sales requests, the ERP) and reports whether it did.
|
||||
func (s *Server) notOnPrem(w http.ResponseWriter) bool {
|
||||
if !s.onPrem() {
|
||||
return false
|
||||
}
|
||||
return s.Cfg.Env
|
||||
writeError(w, http.StatusNotFound, "not_available", "not available in this installation")
|
||||
return true
|
||||
}
|
||||
|
||||
// product returns an enabled catalog product or ErrNotFound.
|
||||
@@ -63,6 +76,9 @@ type catalogRequestReq struct {
|
||||
// catalogRequest — customer requests a non-subscribed product. Emits an
|
||||
// audit event; the ERP outbox (M-MIG-7) turns it into a CRM Lead.
|
||||
func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notOnPrem(w) {
|
||||
return
|
||||
}
|
||||
var in catalogRequestReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
@@ -95,7 +111,7 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if p, _ := authn.PrincipalFrom(r.Context()); p != nil {
|
||||
email = p.Email
|
||||
}
|
||||
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
|
||||
if _, err := s.enqueueERP(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
|
||||
Payload: map[string]interface{}{"lead_name": t.Name, "company_name": t.Name, "email": email, "product": in.Product,
|
||||
"notes": "Requested " + in.Product + " from the platform catalog"}}); err != nil {
|
||||
s.Log.Error("enqueue lead failed", "tenant_id", in.TenantID, "err", err)
|
||||
@@ -109,6 +125,9 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
|
||||
// catalogTrialRequest — self-serve trial of a product that supports it.
|
||||
// Provisions the entitlement immediately (trial_days from the catalog).
|
||||
func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notOnPrem(w) {
|
||||
return
|
||||
}
|
||||
var in catalogRequestReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// onPremHarness turns a harness into an on-prem registry: Prüfwerk and
|
||||
// Werkmeister ship (Werkmeister's row is disabled in the seed), with local URLs.
|
||||
func onPremHarness(h *testHarness, provision map[string]string) {
|
||||
h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30}
|
||||
h.app.Store = store.WithProductOverrides(h.store, h.app.Cfg.CatalogEnv(),
|
||||
[]string{"pruefwerk", "werkmeister"},
|
||||
map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"},
|
||||
provision)
|
||||
}
|
||||
|
||||
func TestOnPrem_catalogListsOnlyShippedProductsWithLocalURLs(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
onPremHarness(h, nil)
|
||||
resp, body := h.do("GET", "/v1/catalog", nil)
|
||||
if resp.StatusCode != 200 {
|
||||
t.Fatalf("status = %d", resp.StatusCode)
|
||||
}
|
||||
out := decode[struct {
|
||||
Items []store.CatalogEntry `json:"items"`
|
||||
}](t, body)
|
||||
got := map[string]string{}
|
||||
for _, it := range out.Items {
|
||||
got[it.Key] = it.LaunchURL
|
||||
}
|
||||
want := map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("catalog = %v, want %v", got, want)
|
||||
}
|
||||
for k, v := range want {
|
||||
if got[k] != v {
|
||||
t.Errorf("%s launch URL = %q, want %q", k, got[k], v)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(body), "breakpilot.com") {
|
||||
t.Errorf("on-prem catalog names a Breakpilot host: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_cloudOnlyRoutesAnswer404(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
onPremHarness(h, nil)
|
||||
for _, c := range []struct{ method, path string }{
|
||||
{"POST", "/v1/catalog/request"},
|
||||
{"POST", "/v1/catalog/trial-request"},
|
||||
{"POST", "/v1/trial-offers"},
|
||||
{"POST", "/v1/trial-offers/verify"},
|
||||
{"GET", "/v1/trial-offers/x"},
|
||||
{"POST", "/v1/trial-offers/x/resend"},
|
||||
{"GET", "/v1/legal/trial-terms"},
|
||||
{"POST", "/v1/internal/erp/webhook"},
|
||||
{"POST", "/v1/admin/tenants/" + h.tenant.ID + "/trial"},
|
||||
{"GET", "/v1/tenants/" + h.tenant.ID + "/contracts/trial/terms.pdf"},
|
||||
} {
|
||||
resp, body := h.do(c.method, c.path, map[string]any{"tenant_id": h.tenant.ID, "product": "pruefwerk"})
|
||||
if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_available") {
|
||||
t.Errorf("%s %s = %d %s, want 404 not_available", c.method, c.path, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_newWorkspaceIsActiveAndQueuesNothingForTheERP(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
ctx := context.Background()
|
||||
// Control: in the cloud a new workspace queues its ERP customer.
|
||||
before, err := h.store.PendingOutbox(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "cloud-ws", "name": "Cloud GmbH"}); resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("cloud create = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if n, _ := h.store.PendingOutbox(ctx); n != before+1 {
|
||||
t.Fatalf("cloud outbox %d → %d, want +1", before, n)
|
||||
}
|
||||
onPremHarness(h, nil)
|
||||
before, err = h.store.PendingOutbox(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH"})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
out := decode[struct {
|
||||
Tenant *store.Tenant `json:"tenant"`
|
||||
}](t, body)
|
||||
if out.Tenant.Status != store.StatusActive {
|
||||
t.Errorf("status = %q, want active", out.Tenant.Status)
|
||||
}
|
||||
after, err := h.store.PendingOutbox(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after != before {
|
||||
t.Errorf("outbox grew from %d to %d on-prem", before, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_nothingEscalatesByTime(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
ctx := context.Background()
|
||||
trial := newTrial(t, h)
|
||||
onPremHarness(h, nil)
|
||||
// A year later the cloud would have restricted it.
|
||||
h.app.Now = func() time.Time { return time.Now().AddDate(1, 0, 0) }
|
||||
rep := h.app.Reconcile(ctx)
|
||||
if len(rep.Escalated) != 0 {
|
||||
t.Errorf("escalated on-prem: %v", rep.Escalated)
|
||||
}
|
||||
got, err := h.store.GetTenant(ctx, trial.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status != store.StatusTrial {
|
||||
t.Errorf("status trial → %q", got.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_activationProvisionsAtTheLocalURL(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
var mu sync.Mutex
|
||||
var paths []string
|
||||
local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
mu.Lock()
|
||||
paths = append(paths, r.Method+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer local.Close()
|
||||
onPremHarness(h, map[string]string{"pruefwerk": local.URL + "/api/v1/platform/tenants/{id}/provision"})
|
||||
|
||||
resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{
|
||||
"products": []map[string]any{{"key": "pruefwerk"}},
|
||||
})
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("activate = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := "POST /api/v1/platform/tenants/" + h.tenant.ID + "/provision"
|
||||
if len(paths) != 1 || paths[0] != want {
|
||||
t.Errorf("provision calls = %v, want [%s]", paths, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_unshippedProductCannotBeActivated(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
onPremHarness(h, nil)
|
||||
resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{
|
||||
"products": []map[string]any{{"key": "firmwerk"}},
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "unknown_product") {
|
||||
t.Errorf("activate firmwerk = %d %s, want 400 unknown_product", resp.StatusCode, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The same year-old trial does escalate in the cloud (the control for the test above).
|
||||
func TestCloud_trialStillEscalatesByTime(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
trial := newTrial(t, h)
|
||||
h.app.Now = func() time.Time { return time.Now().AddDate(1, 0, 0) }
|
||||
rep := h.app.Reconcile(context.Background())
|
||||
if !slices.Contains(rep.Escalated, trial.Slug+"→"+store.StatusRestricted) {
|
||||
t.Errorf("escalated = %v, want %s restricted", rep.Escalated, trial.Slug)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func newTrial(t *testing.T, h *testHarness) *store.Tenant {
|
||||
t.Helper()
|
||||
tr, err := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "trial-ws", Name: "Trial Workspace"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Status != store.StatusTrial || tr.TrialEndsAt == nil {
|
||||
t.Fatalf("new tenant is %q (trial end %v), want a trial", tr.Status, tr.TrialEndsAt)
|
||||
}
|
||||
return tr
|
||||
}
|
||||
|
||||
// cloudURLStore serves Prüfwerk with seeded stage/prod provision URLs, as the
|
||||
// migrations do on a real database.
|
||||
type cloudURLStore struct {
|
||||
store.Store
|
||||
url string
|
||||
}
|
||||
|
||||
func (c cloudURLStore) seed(p *store.Product) {
|
||||
if p.Key == "pruefwerk" {
|
||||
p.ProvisionURLs = map[string]string{"stage": c.url + "/{id}/stage", "prod": c.url + "/{id}/prod"}
|
||||
}
|
||||
}
|
||||
|
||||
func (c cloudURLStore) GetProduct(ctx context.Context, key string) (*store.Product, error) {
|
||||
p, err := c.Store.GetProduct(ctx, key)
|
||||
if err == nil {
|
||||
c.seed(p)
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (c cloudURLStore) ListProducts(ctx context.Context, all bool) ([]store.Product, error) {
|
||||
ps, err := c.Store.ListProducts(ctx, all)
|
||||
for i := range ps {
|
||||
c.seed(&ps[i])
|
||||
}
|
||||
return ps, err
|
||||
}
|
||||
|
||||
// Blocker #1: the seeded cloud URLs are never called on-prem, even when the
|
||||
// values file gives a product no provision URL of its own.
|
||||
func TestOnPrem_seededCloudProvisionURLsAreNeverCalled(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
cloud := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer cloud.Close()
|
||||
seeded := cloudURLStore{Store: h.store, url: cloud.URL}
|
||||
activate := func() {
|
||||
t.Helper()
|
||||
if resp, body := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/activate", map[string]any{
|
||||
"products": []map[string]any{{"key": "pruefwerk"}},
|
||||
}); resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("activate = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// Control: in the cloud (dev reads stage) the seeded URL is called.
|
||||
h.app.Store = seeded
|
||||
activate()
|
||||
mu.Lock()
|
||||
if calls != 1 {
|
||||
t.Fatalf("cloud: %d calls to the seeded URL, want 1", calls)
|
||||
}
|
||||
calls = 0
|
||||
mu.Unlock()
|
||||
|
||||
h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30}
|
||||
h.app.Store = store.WithProductOverrides(seeded, h.app.Cfg.CatalogEnv(), []string{"pruefwerk"},
|
||||
map[string]string{"pruefwerk": "https://pruefwerk.onprem.test"}, nil)
|
||||
activate()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if calls != 0 {
|
||||
t.Errorf("on-prem: %d calls to a seeded cloud URL", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnPrem_catalogOffersNoTrials(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
onPremHarness(h, nil)
|
||||
_, body := h.do("GET", "/v1/catalog", nil)
|
||||
out := decode[struct {
|
||||
Items []store.CatalogEntry `json:"items"`
|
||||
}](t, body)
|
||||
for _, it := range out.Items {
|
||||
if it.SupportsTrial {
|
||||
t.Errorf("%s offers a trial on-prem", it.Key)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -64,6 +64,17 @@ func (s *Server) now() time.Time {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// cloudOnly wraps a handler of a feature that exists only in our cloud
|
||||
// (sign-up, trial offers and terms, the ERP): 404 on-prem.
|
||||
func (s *Server) cloudOnly(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notOnPrem(w) {
|
||||
return
|
||||
}
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) cfg() *config.Config {
|
||||
if s.Cfg == nil {
|
||||
return &config.Config{}
|
||||
@@ -99,14 +110,14 @@ func NewRouter(s *Server) http.Handler {
|
||||
root.HandleFunc("GET /version", s.version)
|
||||
// PUBLIC_EXPLICIT: ERPNext webhooks carry no Keycloak token — the body
|
||||
// is HMAC-signed with ERP_WEBHOOK_SECRET (receiver refuses without it).
|
||||
root.HandleFunc("POST /v1/internal/erp/webhook", s.erpWebhook)
|
||||
root.HandleFunc("POST /v1/internal/erp/webhook", s.cloudOnly(s.erpWebhook))
|
||||
// PUBLIC_EXPLICIT: licence verification keys + heartbeat. The heartbeat
|
||||
// is authenticated by the licence JWT it carries (offline CLIs hold no
|
||||
// Keycloak session).
|
||||
root.HandleFunc("GET /.well-known/licence-keys.json", s.licenceKeys)
|
||||
// Trial terms (portal#64): public, the same bytes before and after the offer.
|
||||
root.HandleFunc("GET /v1/legal/trial-terms", s.legalTrialTerms)
|
||||
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.legalTrialTermsFile)
|
||||
root.HandleFunc("GET /v1/legal/trial-terms", s.cloudOnly(s.legalTrialTerms))
|
||||
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.cloudOnly(s.legalTrialTermsFile))
|
||||
root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat)
|
||||
// PUBLIC_EXPLICIT: CI licences are authenticated by the tenant API key in
|
||||
// the Authorization header (scope <product>:licence), checked in the handler.
|
||||
@@ -145,11 +156,11 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/capability-requests/{rid}", s.deleteCapabilityRequest)
|
||||
// Trial signup (portal#64): offer, confirmation/activation, new link; the
|
||||
// contract documents of a tenant.
|
||||
mux.HandleFunc("POST /v1/trial-offers", s.createTrialOffer)
|
||||
mux.HandleFunc("POST /v1/trial-offers/verify", s.verifyTrialOffer)
|
||||
mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.resendTrialOffer)
|
||||
mux.HandleFunc("GET /v1/trial-offers/{id}", s.trialOfferStatus)
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.tenantTrialTermsPDF)
|
||||
mux.HandleFunc("POST /v1/trial-offers", s.cloudOnly(s.createTrialOffer))
|
||||
mux.HandleFunc("POST /v1/trial-offers/verify", s.cloudOnly(s.verifyTrialOffer))
|
||||
mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.cloudOnly(s.resendTrialOffer))
|
||||
mux.HandleFunc("GET /v1/trial-offers/{id}", s.cloudOnly(s.trialOfferStatus))
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.cloudOnly(s.tenantTrialTermsPDF))
|
||||
// Contract documents (AGB, AVV, TOM, Leistungsbeschreibungen): "<doc>.pdf".
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/contracts/documents/{file}", s.tenantContractDocumentPDF)
|
||||
// Projekte (0010): the list is a {sub} of tenantSubresource.
|
||||
@@ -229,7 +240,7 @@ func NewRouter(s *Server) http.Handler {
|
||||
// Staff administration (portal /admin; group "admin").
|
||||
mux.HandleFunc("GET /v1/admin/tenants", s.adminListTenants)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.cloudOnly(s.adminExtendTrial))
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
|
||||
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/members/{uid}", s.adminPatchMember)
|
||||
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/members/{uid}", s.adminDeleteMember)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)},
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package store
|
||||
|
||||
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,
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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"},
|
||||
|
||||
@@ -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.';
|
||||
@@ -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.';
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user