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

424 lines
15 KiB
Go

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/mail"
"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}
// 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"},
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)
}
}
})
}
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"`
}
// 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)
}
})
}
// 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)
}
}
}
})
}