Files
tenant-registry/internal/server/branding_test.go
T
Sharang ParnerkarandClaude Opus 5.5 c7dda6da5a feat(branding): tenant branding store, endpoints and check field
Customer branding (#155), the contract part: products and the portal
can read and set a workspace's CI colour and logo. The derivation from
the signup domain follows in a separate change.

- Migration 0035: tenant_branding (colour, 256×256 PNG logo with its
  sha256 ETag, manual flag, provenance, derivation queue, notice ack).
  ON DELETE CASCADE, so a purge removes it.
- Entitlements check: "branding" {color, logo_etag, notice, domain,
  name}, only when allowed and there is a colour or logo. A read error
  leaves the field out instead of failing the check.
- GET/PUT /v1/tenants/{id}/branding (tenants.read/write): the portal's
  Erscheinungsbild page; a PUT makes the branding manual. Logos are
  decoded (PNG, JPEG, GIF, ICO) and re-encoded; SVG is refused.
- GET /v1/tenants/{id}/branding/logo (branding.read): PNG, ETag, 304.
- POST /v1/tenants/{id}/branding/ack (branding.ack): "Passt" by an IT
  admin or owner, checked in Keycloak; 403 not_admin otherwise.
- BRANDING_DERIVE config switch (off by default), reported to the
  portal as derive_enabled.
- CI runs the new internal/branding tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:08:54 +01:00

301 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server_test
import (
"bytes"
"context"
"encoding/base64"
"image"
"image/color"
"image/png"
"io"
"net/http"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
type brandingResp struct {
Color *string `json:"color"`
LogoETag *string `json:"logo_etag"`
Manual bool `json:"manual"`
Domain string `json:"domain"`
ColorSource string `json:"color_source"`
DeriveState string `json:"derive_state"`
Notice bool `json:"notice"`
NoticeAckAt *time.Time `json:"notice_ack_at"`
DeriveEnabled bool `json:"derive_enabled"`
}
func solidPNG(t *testing.T, w, h int, c color.Color) []byte {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Set(x, y, c)
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func brandingTenant(t *testing.T, h *testHarness, slug string) *store.Tenant {
t.Helper()
_, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": slug, "name": "Brand Co"})
tn := decode[struct {
Tenant *store.Tenant `json:"tenant"`
}](t, raw).Tenant
if resp, _ := h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); resp.StatusCode != 201 {
t.Fatalf("trial: %d", resp.StatusCode)
}
return tn
}
func TestBranding_manualAndCheck(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := brandingTenant(t, h, "brand-co")
base := "/v1/tenants/" + tn.ID + "/branding"
// Nothing yet: state none, no branding in the check, logo 404.
resp, raw := h.do("GET", base, nil)
if resp.StatusCode != 200 {
t.Fatalf("get: %d %s", resp.StatusCode, raw)
}
if b := decode[brandingResp](t, raw); b.DeriveState != "none" || b.Color != nil || b.DeriveEnabled {
t.Fatalf("empty: %+v", b)
}
if got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); got.Branding != nil {
t.Fatalf("check without branding: %+v", got.Branding)
}
if resp, _ := h.do("GET", base+"/logo", nil); resp.StatusCode != 404 {
t.Fatalf("logo before: %d", resp.StatusCode)
}
// Bad input.
for _, body := range []map[string]any{
{}, {"color": "blue"}, {"color": "#12345"}, {"logo": "%%%"}, {"other": 1},
{"logo": base64.StdEncoding.EncodeToString([]byte(`<svg xmlns="http://www.w3.org/2000/svg"/>`))},
} {
if resp, raw := h.do("PUT", base, body); resp.StatusCode != 400 {
t.Fatalf("PUT %v: %d %s", body, resp.StatusCode, raw)
}
}
// Colour (any case → lowercase) and logo.
logo := solidPNG(t, 64, 32, color.NRGBA{R: 200, G: 30, B: 40, A: 255})
resp, raw = h.do("PUT", base, map[string]any{"color": "#1A5FB4", "logo": base64.StdEncoding.EncodeToString(logo)})
if resp.StatusCode != 200 {
t.Fatalf("put: %d %s", resp.StatusCode, raw)
}
b := decode[brandingResp](t, raw)
if b.Color == nil || *b.Color != "#1a5fb4" || b.LogoETag == nil || !b.Manual || b.Notice || b.ColorSource != "manual" {
t.Fatalf("after put: %+v", b)
}
// The check carries it, without a notice (manual).
got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if got.Branding == nil || *got.Branding.Color != "#1a5fb4" || *got.Branding.LogoETag != *b.LogoETag ||
got.Branding.Notice || got.Branding.Domain != "" || got.Branding.Name != "Brand Co" {
t.Fatalf("check branding: %+v", got.Branding)
}
// Not allowed: no branding.
if got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "werkpilot"}); got.Allowed || got.Branding != nil {
t.Fatalf("not entitled: %+v", got)
}
// The logo: a 256×256 PNG with the ETag, 304 on a match.
req, _ := http.NewRequest("GET", h.srv.URL+base+"/logo", nil)
r1, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(r1.Body)
_ = r1.Body.Close()
if r1.StatusCode != 200 || r1.Header.Get("Content-Type") != "image/png" || r1.Header.Get("ETag") != `"`+*b.LogoETag+`"` {
t.Fatalf("logo: %d %v", r1.StatusCode, r1.Header)
}
img, err := png.Decode(bytes.NewReader(body))
if err != nil || img.Bounds().Dx() != 256 || img.Bounds().Dy() != 256 {
t.Fatalf("logo image: %v %v", err, img)
}
req.Header.Set("If-None-Match", `"`+*b.LogoETag+`"`)
r2, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
_ = r2.Body.Close()
if r2.StatusCode != 304 {
t.Fatalf("If-None-Match: %d", r2.StatusCode)
}
// Removing the colour keeps the logo; removing the logo empties it.
resp, raw = h.do("PUT", base, map[string]any{"color": nil})
if b := decode[brandingResp](t, raw); resp.StatusCode != 200 || b.Color != nil || b.LogoETag == nil || b.ColorSource != "" {
t.Fatalf("remove colour: %d %+v", resp.StatusCode, b)
}
_, _ = h.do("PUT", base, map[string]any{"logo": nil})
if got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); got.Branding != nil {
t.Fatalf("emptied: %+v", got.Branding)
}
if resp, _ := h.do("GET", base+"/logo", nil); resp.StatusCode != 404 {
t.Fatalf("logo after removal: %d", resp.StatusCode)
}
if resp, _ := h.do("GET", "/v1/tenants/00000000-0000-0000-0000-00000000dead/branding", nil); resp.StatusCode != 404 {
t.Fatalf("unknown tenant: %d", resp.StatusCode)
}
})
}
func TestBranding_derivedNoticeAndAck(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
tn := brandingTenant(t, h, "ack-co")
h.kcMock.Members["ack-co"] = []keycloak.OrgMember{
{UserID: "admin", Email: "it@ack.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true},
{UserID: "user", Email: "u@ack.test", OrgRoles: []string{"USER"}, Enabled: true},
{UserID: "off", Email: "off@ack.test", OrgRoles: []string{"OWNER"}, Enabled: false},
}
color := "#0a7d3e"
now := time.Now().UTC().Truncate(time.Second)
if ok, err := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{
TenantID: tn.ID, Color: &color, Domain: "example.test", ColorSource: store.BrandingSourceThemeColor,
HTMLSHA256: "ab", At: now,
}); err != nil || !ok {
t.Fatalf("derive: %v %v", ok, err)
}
got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if got.Branding == nil || !got.Branding.Notice || got.Branding.Domain != "example.test" || got.Branding.LogoETag != nil {
t.Fatalf("derived: %+v", got.Branding)
}
ack := "/v1/tenants/" + tn.ID + "/branding/ack"
for uid, want := range map[string]int{"": 400, "user": 403, "off": 403, "nobody": 403} {
if resp, raw := h.do("POST", ack, map[string]any{"user_id": uid}); resp.StatusCode != want {
t.Fatalf("ack by %q: %d %s", uid, resp.StatusCode, raw)
}
}
h.kcMock.FailNext = errAny
if resp, _ := h.do("POST", ack, map[string]any{"user_id": "admin"}); resp.StatusCode != 403 {
t.Fatalf("ack with keycloak down: %d", resp.StatusCode)
}
for i := 0; i < 2; i++ { // the second is a no-op
if resp, raw := h.do("POST", ack, map[string]any{"user_id": "admin"}); resp.StatusCode != 204 {
t.Fatalf("ack %d: %d %s", i, resp.StatusCode, raw)
}
}
got = check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"})
if got.Branding == nil || got.Branding.Notice || got.Branding.Domain != "" {
t.Fatalf("after ack: %+v", got.Branding)
}
events, _, _ := h.store.ListAudit(ctx, store.AuditFilter{TenantID: tn.ID, Action: "branding.acknowledged"})
if len(events) != 1 || events[0].ActorID != "admin" {
t.Fatalf("audit: %+v", events)
}
// The same result again keeps the acknowledgement; a new colour
// raises the notice again.
if ok, _ := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{TenantID: tn.ID, Color: &color, Domain: "example.test", At: now.Add(time.Hour)}); !ok {
t.Fatal("re-derive not applied")
}
if b, _ := h.store.GetTenantBranding(ctx, tn.ID); b.Notice() {
t.Fatalf("unchanged result raised the notice: %+v", b)
}
other := "#334455"
if _, err := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{TenantID: tn.ID, Color: &other, Domain: "example.test", At: now.Add(2 * time.Hour)}); err != nil {
t.Fatal(err)
}
if b, _ := h.store.GetTenantBranding(ctx, tn.ID); !b.Notice() {
t.Fatalf("changed result without notice: %+v", b)
}
// A manual choice is never derived over, unless forced.
if resp, _ := h.do("PUT", "/v1/tenants/"+tn.ID+"/branding", map[string]any{"color": "#ffffff"}); resp.StatusCode != 200 {
t.Fatal("manual put")
}
if ok, err := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{TenantID: tn.ID, Color: &color, At: now.Add(3 * time.Hour)}); err != nil || ok {
t.Fatalf("derived over manual: %v %v", ok, err)
}
if b, _ := h.store.GetTenantBranding(ctx, tn.ID); *b.Color != "#ffffff" || !b.Manual {
t.Fatalf("manual lost: %+v", b)
}
if ok, _ := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{TenantID: tn.ID, Color: &color, At: now.Add(4 * time.Hour), Force: true, By: "it@ack.test"}); !ok {
t.Fatal("forced derive not applied")
}
if b, _ := h.store.GetTenantBranding(ctx, tn.ID); *b.Color != color || b.Manual || b.Notice() {
t.Fatalf("forced: %+v", b)
}
})
}
func TestBranding_queue(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
now := time.Now().UTC().Truncate(time.Second)
a := brandingTenant(t, h, "queue-a")
b := brandingTenant(t, h, "queue-b")
if created, err := h.store.EnqueueBranding(ctx, a.ID, now); err != nil || !created {
t.Fatalf("enqueue: %v %v", created, err)
}
if created, _ := h.store.EnqueueBranding(ctx, a.ID, now); created {
t.Fatal("enqueued twice")
}
if _, err := h.store.EnqueueBranding(ctx, "00000000-0000-0000-0000-00000000dead", now); err == nil {
t.Fatal("unknown tenant enqueued")
}
// The backfill adds every other customer (acme, queue-b), once.
n, err := h.store.EnqueueMissingBranding(ctx, now.Add(time.Second))
if err != nil || n != 2 {
t.Fatalf("backfill: %d %v", n, err)
}
if n, _ := h.store.EnqueueMissingBranding(ctx, now); n != 0 {
t.Fatalf("second backfill: %d", n)
}
due, _ := h.store.DueBranding(ctx, now.Add(time.Minute), 10)
if len(due) != 3 || due[0] != a.ID {
t.Fatalf("due: %v", due)
}
// A retry later is not due before its time; a final failure never.
next := now.Add(time.Hour)
noErr(t, h.store.FailBranding(ctx, a.ID, "timeout", &next, now))
noErr(t, h.store.FailBranding(ctx, b.ID, "no domain", nil, now))
due, _ = h.store.DueBranding(ctx, now.Add(time.Minute), 10)
if len(due) != 1 {
t.Fatalf("due after failures: %v", due)
}
due, _ = h.store.DueBranding(ctx, now.Add(2*time.Hour), 10)
if len(due) != 2 {
t.Fatalf("due after the retry time: %v", due)
}
if br, _ := h.store.GetTenantBranding(ctx, b.ID); br.DeriveState != store.BrandingFailed || br.DeriveAttempts != 1 || br.DeriveError != "no domain" {
t.Fatalf("failed row: %+v", br)
}
// A failure keeps what a derivation found earlier.
c := "#123456"
if _, err := h.store.SaveDerivedBranding(ctx, store.DerivedBranding{TenantID: a.ID, Color: &c, At: now}); err != nil {
t.Fatal(err)
}
noErr(t, h.store.FailBranding(ctx, a.ID, "timeout", nil, now))
if br, _ := h.store.GetTenantBranding(ctx, a.ID); br.Color == nil || *br.Color != c {
t.Fatalf("failure wiped the branding: %+v", br)
}
// Purging the tenant removes its branding.
if err := h.store.DeleteTenant(ctx, a.ID); err != nil {
t.Fatal(err)
}
if _, err := h.store.GetTenantBranding(ctx, a.ID); err == nil {
t.Fatal("branding outlived the tenant")
}
})
}
func noErr(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}