Files
tenant-registry/internal/server/trialoffers_test.go
sharangandClaude Opus 5.5 60f20e6419
ci / shared (push) Successful in 13s
ci / test (push) Successful in 23m58s
ci / image (push) Successful in 36s
feat(trial): legal trial signup: offer, confirmation, activation (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 16:00:52 +00:00

325 lines
15 KiB
Go

package server_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"regexp"
"strings"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/legal/trialterms"
"git.breakpilot.com/platform/tenant-registry/internal/mail"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func trialOffer(email string) map[string]any {
v := trialterms.Current()
return map[string]any{
"company_name": "Müller Maschinenbau GmbH", "street": "Hauptstr. 1", "postcode": "78224", "city": "Singen",
"country": "de", "first_name": "Anna", "last_name": "Müller", "email": email,
"terms_version": v.Version, "terms_sha256": v.SHA256PDF,
"notice_version": trialterms.NoticeVersion, "flow_version": trialterms.FlowVersion, "terms_accepted": true,
}
}
var tokenRE = regexp.MustCompile(`token=([A-Za-z0-9_-]+)`)
func lastToken(t *testing.T, rec *mail.Recorder) string {
t.Helper()
msgs := rec.Messages()
if len(msgs) == 0 {
t.Fatal("no mail sent")
}
m := tokenRE.FindStringSubmatch(msgs[len(msgs)-1].Text)
if m == nil {
t.Fatalf("no token in mail: %s", msgs[len(msgs)-1].Text)
}
return m[1]
}
func TestTrialTerms_publicAndByteIdentical(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
v := trialterms.Current()
resp, raw := h.do("GET", "/v1/legal/trial-terms", nil)
var meta map[string]string
_ = json.Unmarshal(raw, &meta)
if resp.StatusCode != 200 || meta["version"] != "1.0" || meta["sha256_pdf"] != v.SHA256PDF || meta["notice_version"] != trialterms.NoticeVersion {
t.Fatalf("meta %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("GET", "/v1/legal/trial-terms/1.0.pdf", nil)
if resp.StatusCode != 200 || !bytes.Equal(raw, v.PDF) || resp.Header.Get("Content-Type") != "application/pdf" ||
resp.Header.Get("ETag") != `"`+v.SHA256PDF+`"` || !strings.Contains(resp.Header.Get("Content-Disposition"), v.PDFName) {
t.Fatalf("pdf %d %v", resp.StatusCode, resp.Header)
}
if resp, raw = h.do("GET", "/v1/legal/trial-terms/1.0.html", nil); resp.StatusCode != 200 || !bytes.Equal(raw, v.HTML) {
t.Fatalf("html %d", resp.StatusCode)
}
if resp, _ = h.do("GET", "/v1/legal/trial-terms/1.0.md", nil); resp.StatusCode != 200 {
t.Fatalf("md %d", resp.StatusCode)
}
for _, p := range []string{"/v1/legal/trial-terms/2.0.pdf", "/v1/legal/trial-terms/1.0.exe", "/v1/legal/trial-terms/nodot"} {
if resp, _ = h.do("GET", p, nil); resp.StatusCode != 404 {
t.Errorf("%s: %d", p, resp.StatusCode)
}
}
})
}
func TestTrialOffer_validation(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
h.app.Mail = &mail.Recorder{}
cases := []struct {
change func(map[string]any)
status int
code string
}{
{func(o map[string]any) { o["postcode"] = "1234" }, 400, "invalid_field"},
{func(o map[string]any) { o["email"] = "not an address" }, 400, "invalid_field"},
{func(o map[string]any) { o["country"] = "Deutschland" }, 400, "invalid_field"},
{func(o map[string]any) { o["company_name"] = " " }, 400, "invalid_field"},
{func(o map[string]any) { o["terms_accepted"] = false }, 400, "terms_not_accepted"},
{func(o map[string]any) { o["terms_sha256"] = strings.Repeat("0", 64) }, 409, "version_mismatch"},
{func(o map[string]any) { o["notice_version"] = "old" }, 409, "version_mismatch"},
}
for i, c := range cases {
o := trialOffer("v@firma.de")
c.change(o)
resp, raw := h.do("POST", "/v1/trial-offers", o)
if resp.StatusCode != c.status || !strings.Contains(string(raw), c.code) {
t.Errorf("case %d: %d %s", i, resp.StatusCode, raw)
}
}
// a foreign postcode is not checked against the German format
o := trialOffer("at@firma.at")
o["country"], o["postcode"] = "AT", "1010"
if resp, raw := h.do("POST", "/v1/trial-offers", o); resp.StatusCode != 201 {
t.Fatalf("AT: %d %s", resp.StatusCode, raw)
}
// an address with an account is refused before anything is recorded
h.kcMock.Users["taken@firma.de"] = "u1"
if resp, raw := h.do("POST", "/v1/trial-offers", trialOffer("taken@firma.de")); resp.StatusCode != 409 || !strings.Contains(string(raw), "email_taken") {
t.Fatalf("taken: %d %s", resp.StatusCode, raw)
}
})
}
func TestTrialOffer_offerConfirmActivate(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
rec := &mail.Recorder{}
h.app.Mail = rec
h.app.Cfg.PortalURL = "https://app-stage.breakpilot.com"
resp, raw := h.do("POST", "/v1/trial-offers", trialOffer(" Anna@Mueller.de "))
var offer map[string]any
_ = json.Unmarshal(raw, &offer)
if resp.StatusCode != 201 || offer["state"] != "email_verification_pending" || offer["email"] != "anna@mueller.de" || offer["receipt_mail_sent"] != true {
t.Fatalf("offer %d %s", resp.StatusCode, raw)
}
receipt := rec.Messages()[0]
if receipt.To != "anna@mueller.de" || receipt.Subject != "Ihre Breakpilot-Testregistrierung ist eingegangen" ||
!strings.Contains(receipt.Text, "https://app-stage.breakpilot.com/start/bestaetigen?token=") ||
!strings.Contains(receipt.Text, "noch nicht freigeschaltet") || !strings.Contains(receipt.Text, "keine Kosten") ||
strings.Contains(receipt.Text, "Vertrag wurde abgeschlossen") || len(receipt.Attachments) != 0 {
t.Fatalf("receipt %+v", receipt)
}
// the same address again within 10 minutes: nothing new
if resp, raw := h.do("POST", "/v1/trial-offers", trialOffer("anna@mueller.de")); resp.StatusCode != 429 {
t.Fatalf("repeat %d %s", resp.StatusCode, raw)
}
if resp, _ := h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": "nope"}); resp.StatusCode != 404 {
t.Fatalf("bad token %d", resp.StatusCode)
}
token := lastToken(t, rec)
before := time.Now().UTC()
resp, raw = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": token})
var got struct {
Outcome string `json:"outcome"`
TenantSlug string `json:"tenant_slug"`
TrialStartedAt time.Time `json:"trial_started_at"`
TrialExpiresAt time.Time `json:"trial_expires_at"`
}
_ = json.Unmarshal(raw, &got)
if resp.StatusCode != 200 || got.Outcome != "activated" || got.TenantSlug != "mueller-maschinenbau" {
t.Fatalf("verify %d %s", resp.StatusCode, raw)
}
berlin, _ := time.LoadLocation("Europe/Berlin")
if got.TrialStartedAt.Before(before.Add(-time.Second)) ||
!got.TrialExpiresAt.Equal(got.TrialStartedAt.In(berlin).AddDate(0, 0, 14).UTC()) {
t.Fatalf("trial times %v → %v", got.TrialStartedAt, got.TrialExpiresAt)
}
// the tenant's trial end is the same instant (ladder and display agree)
tn, err := h.store.GetTenantBySlug(t.Context(), "mueller-maschinenbau")
if err != nil || tn.TrialEndsAt == nil || !tn.TrialEndsAt.Equal(got.TrialExpiresAt) || tn.Status != store.StatusTrial || tn.Name != "Müller Maschinenbau GmbH" {
t.Fatalf("tenant %+v %v", tn, err)
}
// Keycloak: the address is confirmed, the user only sets a password
created := h.kcMock.Created[len(h.kcMock.Created)-1]
if !created.EmailVerified || created.AdminEmail != "anna@mueller.de" || created.AdminFirst != "Anna" || created.AdminLast != "Müller" {
t.Fatalf("keycloak %+v", created)
}
// activation mail with the contract PDF
act := rec.Messages()[len(rec.Messages())-1]
v := trialterms.Current()
if act.Subject != "Ihr Breakpilot-Testzugang ist aktiviert" || len(act.Attachments) != 1 ||
act.Attachments[0].Name != "Breakpilot_Testbedingungen_v1.0_2026-10-01.pdf" || !bytes.Equal(act.Attachments[0].Data, v.PDF) ||
!strings.Contains(act.Text, got.TrialExpiresAt.In(berlin).Format("02.01.2006")) || !strings.Contains(act.Text, "Passwort festlegen") ||
!strings.Contains(act.Text, "1. Oktober 2026") || !strings.Contains(act.Text, "https://app-stage.breakpilot.com/mueller-maschinenbau") {
t.Fatalf("activation mail %q / %d attachments", act.Text, len(act.Attachments))
}
// the audit chain on the tenant
_, raw = h.do("GET", "/v1/audit?tenant_id="+tn.ID+"&limit=50", nil)
for _, a := range []string{"trial.offer_submitted", "trial.email_verified", "trial.contract_accepted", "trial.activated"} {
if !strings.Contains(string(raw), `"`+a+`"`) {
t.Errorf("audit lacks %s", a)
}
}
if !strings.Contains(string(raw), v.SHA256PDF) {
t.Error("offer event lacks the terms checksum")
}
// a second click: already activated, not an error, no second tenant
resp, raw = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": token})
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"already_activated"`) || !strings.Contains(string(raw), "mueller-maschinenbau") {
t.Fatalf("second click %d %s", resp.StatusCode, raw)
}
// Vertragsunterlagen
resp, raw = h.do("GET", "/v1/tenants/"+tn.ID+"/contracts", nil)
var c struct {
Trial *struct {
Status, TermsVersion, TermsDate, AcceptingEmail string
} `json:"trial"`
AVV, TOMs, SaaS struct{ Status string }
}
_ = json.Unmarshal(raw, &c)
if resp.StatusCode != 200 || c.Trial == nil || !strings.Contains(string(raw), `"status":"active"`) ||
!strings.Contains(string(raw), `"terms_version":"1.0"`) || !strings.Contains(string(raw), `"terms_date":"2026-10-01"`) ||
c.AVV.Status != "not_concluded" || c.TOMs.Status != "pending" || c.SaaS.Status != "not_concluded" {
t.Fatalf("contracts %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("GET", "/v1/tenants/"+tn.ID+"/contracts/trial/terms.pdf", nil)
if resp.StatusCode != 200 || !bytes.Equal(raw, v.PDF) || !strings.HasPrefix(resp.Header.Get("Content-Disposition"), "attachment") {
t.Fatalf("contract pdf %d %v", resp.StatusCode, resp.Header)
}
// a tenant created by staff has no trial contract: nothing is invented
resp, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/contracts", nil)
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"trial":null`) {
t.Fatalf("staff tenant %d %s", resp.StatusCode, raw)
}
if resp, _ = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/contracts/trial/terms.pdf", nil); resp.StatusCode != 404 {
t.Fatalf("staff tenant pdf %d", resp.StatusCode)
}
// after the end the trial contract shows as ended
h.app.Now = func() time.Time { return got.TrialExpiresAt.Add(time.Minute) }
_, raw = h.do("GET", "/v1/tenants/"+tn.ID+"/contracts", nil)
if !strings.Contains(string(raw), `"status":"ended"`) {
t.Fatalf("after end %s", raw)
}
h.app.Now = nil
})
}
func TestTrialOffer_expiredLinkAndResend(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
rec := &mail.Recorder{}
h.app.Mail = rec
_, raw := h.do("POST", "/v1/trial-offers", trialOffer("late@firma.de"))
var offer map[string]string
_ = json.Unmarshal(raw, &offer)
old := lastToken(t, rec)
h.app.Now = func() time.Time { return time.Now().Add(73 * time.Hour) }
resp, raw := h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": old})
if resp.StatusCode != 410 || !strings.Contains(string(raw), "token_expired") || !strings.Contains(string(raw), offer["offer_id"]) {
t.Fatalf("expired %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("POST", "/v1/trial-offers/"+offer["offer_id"]+"/resend", nil)
if resp.StatusCode != 202 || len(rec.Messages()) != 2 {
t.Fatalf("resend %d %s", resp.StatusCode, raw)
}
// again at once: wait a minute
if resp, _ = h.do("POST", "/v1/trial-offers/"+offer["offer_id"]+"/resend", nil); resp.StatusCode != 429 {
t.Fatalf("second resend %d", resp.StatusCode)
}
fresh := lastToken(t, rec)
if resp, _ = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": old}); resp.StatusCode != 404 {
t.Fatalf("old token still works: %d", resp.StatusCode)
}
if resp, raw = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": fresh}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"activated"`) {
t.Fatalf("fresh %d %s", resp.StatusCode, raw)
}
if resp, _ = h.do("POST", "/v1/trial-offers/"+offer["offer_id"]+"/resend", nil); resp.StatusCode != 409 {
t.Fatalf("resend after activation %d", resp.StatusCode)
}
if resp, _ = h.do("POST", "/v1/trial-offers/does-not-exist/resend", nil); resp.StatusCode != 404 {
t.Fatalf("unknown offer %d", resp.StatusCode)
}
h.app.Now = nil
})
}
func TestTrialOffer_slugCollisionAndFailedActivation(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
rec := &mail.Recorder{}
h.app.Mail = rec
// "Acme Inc." → "acme" is taken by the seeded tenant → "acme-2"
o := trialOffer("it@acme.example")
o["company_name"] = "Acme Inc."
h.do("POST", "/v1/trial-offers", o)
tok := lastToken(t, rec)
// the account appears between offer and click: refused, offer stays confirmable
h.kcMock.Users["it@acme.example"] = "u9"
resp, raw := h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": tok})
if resp.StatusCode != 409 || !strings.Contains(string(raw), "email_taken") {
t.Fatalf("taken at click %d %s", resp.StatusCode, raw)
}
delete(h.kcMock.Users, "it@acme.example")
resp, raw = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": tok})
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"tenant_slug":"acme-2"`) {
t.Fatalf("retry %d %s", resp.StatusCode, raw)
}
})
}
func TestTrialOffer_noMailRelay(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
resp, raw := h.do("POST", "/v1/trial-offers", trialOffer("quiet@firma.de"))
if resp.StatusCode != 201 || !strings.Contains(string(raw), `"receipt_mail_sent":false`) {
t.Fatalf("%d %s", resp.StatusCode, raw)
}
resp, raw = h.do("POST", "/v1/trial-offers/verify", map[string]string{"token": ""})
if resp.StatusCode != 404 {
t.Fatalf("empty token %d %s", resp.StatusCode, raw)
}
_ = io.Discard
_ = http.StatusOK
})
}
func TestAdminExtendTrial_recordsTheExtensionEvent(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
_, raw := h.do("POST", "/v1/tenants", map[string]string{"slug": "ext-co", "name": "Ext Co"})
var created struct {
Tenant struct{ ID string } `json:"tenant"`
}
_ = json.Unmarshal(raw, &created)
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+created.Tenant.ID+"/trial", strings.NewReader(`{"days":14}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Portal-User-Email", "benjamin@breakpilot.com")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 200 {
t.Fatalf("extend %v %v", err, resp)
}
_ = resp.Body.Close()
_, raw = h.do("GET", "/v1/audit?tenant_id="+created.Tenant.ID+"&action=trial.extension_granted", nil)
if !strings.Contains(string(raw), "trial.extension_granted") || !strings.Contains(string(raw), "benjamin@breakpilot.com") ||
!strings.Contains(string(raw), "new_expiry") || !strings.Contains(string(raw), "old_expiry") {
t.Fatalf("audit %s", raw)
}
})
}