From c7dda6da5aef2aff6999cd567d9eccc78c1788dc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:08:54 +0100 Subject: [PATCH 1/4] feat(branding): tenant branding store, endpoints and check field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .gitea/workflows/ci.yaml | 2 +- internal/branding/image.go | 225 +++++++++++++++ internal/branding/image_test.go | 119 ++++++++ internal/config/config.go | 6 + internal/server/authz.go | 6 + internal/server/authz_test.go | 12 +- internal/server/branding.go | 347 +++++++++++++++++++++++ internal/server/branding_test.go | 300 ++++++++++++++++++++ internal/server/entitlements.go | 10 +- internal/server/members.go | 4 +- internal/server/openapi_test.go | 4 + internal/server/server.go | 4 + internal/store/branding.go | 84 ++++++ internal/store/memory.go | 4 + internal/store/memory_branding.go | 238 ++++++++++++++++ internal/store/postgres_branding.go | 218 ++++++++++++++ internal/store/store.go | 23 ++ migrations/0035_tenant_branding.down.sql | 1 + migrations/0035_tenant_branding.up.sql | 33 +++ openapi.yaml | 117 ++++++++ 20 files changed, 1753 insertions(+), 4 deletions(-) create mode 100644 internal/branding/image.go create mode 100644 internal/branding/image_test.go create mode 100644 internal/server/branding.go create mode 100644 internal/server/branding_test.go create mode 100644 internal/store/branding.go create mode 100644 internal/store/memory_branding.go create mode 100644 internal/store/postgres_branding.go create mode 100644 migrations/0035_tenant_branding.down.sql create mode 100644 migrations/0035_tenant_branding.up.sql diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 30b3bd4..048b72a 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -86,7 +86,7 @@ jobs: # package result leaves its share out of cover.out, so the total # dropped below the gate whenever the runner had cached results # (main 2026-11-12 08:55 passed uncached; PR #126 failed cached). - run: go test -count=1 -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/... ./internal/telemetry/... ./internal/legal/... + run: go test -count=1 -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/branding/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/... ./internal/telemetry/... ./internal/legal/... - name: coverage gate run: | diff --git a/internal/branding/image.go b/internal/branding/image.go new file mode 100644 index 0000000..f35662b --- /dev/null +++ b/internal/branding/image.go @@ -0,0 +1,225 @@ +// Package branding derives and normalises a workspace's branding (#155): +// the CI colour and the logo every Breakpilot frontend shows. +package branding + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + "image/color" + "image/draw" + _ "image/gif" // registered for image.DecodeConfig / image.Decode + _ "image/jpeg" // registered for image.DecodeConfig / image.Decode + "image/png" + + xdraw "golang.org/x/image/draw" +) + +// LogoSize is the edge of the stored logo: always a 256×256 PNG. +const LogoSize = 256 + +// MaxImageBytes caps an image as fetched or uploaded. +const MaxImageBytes = 1 << 20 + +// maxSourcePixels caps the decoded size of a source image, checked from its +// header before decoding. +const maxSourcePixels = 4096 * 4096 + +var ( + ErrNotImage = errors.New("not a PNG, JPEG, GIF or ICO image") + ErrSVG = errors.New("SVG is not supported") + ErrImageTooLarge = errors.New("image too large") +) + +// NormalizeLogo decodes a PNG, JPEG, GIF or ICO image and returns it fitted +// into a transparent 256×256 square as PNG, with that PNG's sha256 (hex). +// The same input always gives the same bytes. +func NormalizeLogo(data []byte) (pngBytes []byte, etag string, err error) { + img, err := DecodeImage(data) + if err != nil { + return nil, "", err + } + out := fit(img, LogoSize) + var buf bytes.Buffer + if err := (&png.Encoder{CompressionLevel: png.DefaultCompression}).Encode(&buf, out); err != nil { + return nil, "", err + } + sum := sha256.Sum256(buf.Bytes()) + return buf.Bytes(), hex.EncodeToString(sum[:]), nil +} + +// DecodeImage decodes one image, refusing SVG and oversized ones. +func DecodeImage(data []byte) (image.Image, error) { + if len(data) > MaxImageBytes { + return nil, ErrImageTooLarge + } + if looksLikeSVG(data) { + return nil, ErrSVG + } + if isICO(data) { + return decodeICO(data) + } + cfg, _, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return nil, ErrNotImage + } + if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxSourcePixels { + return nil, ErrImageTooLarge + } + img, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return nil, ErrNotImage + } + return img, nil +} + +// fit scales img to fit a size×size square, centred on transparency. +func fit(img image.Image, size int) *image.NRGBA { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + dw, dh := size, size + if w > h { + dh = max(1, (h*size+w/2)/w) + } else if h > w { + dw = max(1, (w*size+h/2)/h) + } + out := image.NewNRGBA(image.Rect(0, 0, size, size)) + x0, y0 := (size-dw)/2, (size-dh)/2 + xdraw.CatmullRom.Scale(out, image.Rect(x0, y0, x0+dw, y0+dh), img, b, draw.Over, nil) + return out +} + +func looksLikeSVG(data []byte) bool { + head := bytes.ToLower(bytes.TrimSpace(data[:min(len(data), 512)])) + return bytes.HasPrefix(head, []byte("= 6 && data[0] == 0 && data[1] == 0 && data[2] == 1 && data[3] == 0 && le16(data[4:]) > 0 +} + +// decodeICO decodes the largest image of an ICO file (PNG or BMP entry). +func decodeICO(data []byte) (image.Image, error) { + n := int(le16(data[4:])) + if len(data) < 6+16*n { + return nil, ErrNotImage + } + best, bestArea, bestBits := -1, 0, 0 + for i := 0; i < n; i++ { + e := data[6+16*i:] + w, h := int(e[0]), int(e[1]) + if w == 0 { + w = 256 + } + if h == 0 { + h = 256 + } + bits := int(le16(e[6:])) + if a := w * h; a > bestArea || (a == bestArea && bits > bestBits) { + best, bestArea, bestBits = i, a, bits + } + } + e := data[6+16*best:] + size, off := int(le32(e[8:])), int(le32(e[12:])) + if off < 0 || size <= 0 || off > len(data) || size > len(data)-off { + return nil, ErrNotImage + } + entry := data[off : off+size] + if bytes.HasPrefix(entry, pngMagic) { + return DecodeImage(entry) + } + return decodeDIB(entry) +} + +// decodeDIB decodes an ICO's BMP entry: BITMAPINFOHEADER, optional palette, +// bottom-up XOR rows, then the 1-bit AND (transparency) mask. +func decodeDIB(d []byte) (image.Image, error) { + if len(d) < 40 || le32(d) < 40 { + return nil, ErrNotImage + } + hdr := int(le32(d)) + w, h2 := int(int32(le32(d[4:]))), int(int32(le32(d[8:]))) + bpp, compression := int(le16(d[14:])), le32(d[16:]) + h := h2 / 2 + if w <= 0 || h <= 0 || w > 1024 || h > 1024 || compression != 0 { + return nil, ErrNotImage + } + var palette []color.NRGBA + pos := hdr + switch bpp { + case 1, 4, 8: + count := int(le32(d[32:])) + if count == 0 || count > 1<= pos+stride*h+maskStride*h { + mask = d[pos+stride*h : pos+stride*h+maskStride*h] + } + img := image.NewNRGBA(image.Rect(0, 0, w, h)) + anyAlpha := false + for y := 0; y < h; y++ { + row := pix[(h-1-y)*stride:] + for x := 0; x < w; x++ { + var c color.NRGBA + switch bpp { + case 32: + c = color.NRGBA{R: row[4*x+2], G: row[4*x+1], B: row[4*x], A: row[4*x+3]} + anyAlpha = anyAlpha || c.A != 0 + case 24: + c = color.NRGBA{R: row[3*x+2], G: row[3*x+1], B: row[3*x], A: 255} + default: + bit := x * bpp + idx := int(row[bit/8]>>(8-bpp-bit%8)) & (1<>(x%8)) != 0 { + c.A = 0 + } + img.SetNRGBA(x, y, c) + } + } + } + return img, nil +} + +func le16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 } +func le32(b []byte) uint32 { + return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 +} diff --git a/internal/branding/image_test.go b/internal/branding/image_test.go new file mode 100644 index 0000000..19746e7 --- /dev/null +++ b/internal/branding/image_test.go @@ -0,0 +1,119 @@ +package branding + +import ( + "bytes" + "encoding/binary" + "errors" + "image" + "image/color" + "image/png" + "testing" +) + +func encodePNG(t *testing.T, img image.Image) []byte { + t.Helper() + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func solid(w, h int, c color.NRGBA) *image.NRGBA { + img := image.NewNRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + img.SetNRGBA(x, y, c) + } + } + return img +} + +// ico wraps one entry (PNG bytes or a DIB) into an ICO file. +func ico(w, h, bits int, entry []byte) []byte { + var b bytes.Buffer + _ = binary.Write(&b, binary.LittleEndian, []uint16{0, 1, 1}) + b.Write([]byte{byte(w % 256), byte(h % 256), 0, 0}) + _ = binary.Write(&b, binary.LittleEndian, []uint16{1, uint16(bits)}) + _ = binary.Write(&b, binary.LittleEndian, []uint32{uint32(len(entry)), 22}) + b.Write(entry) + return b.Bytes() +} + +// dib32 is a 32-bit BMP entry: a red left half, a transparent right half. +func dib32(w, h int) []byte { + var b bytes.Buffer + _ = binary.Write(&b, binary.LittleEndian, []uint32{40, uint32(w), uint32(2 * h)}) + _ = binary.Write(&b, binary.LittleEndian, []uint16{1, 32}) + _ = binary.Write(&b, binary.LittleEndian, []uint32{0, 0, 0, 0, 0, 0}) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + if x < w/2 { + b.Write([]byte{0, 0, 255, 255}) // BGRA red + } else { + b.Write([]byte{0, 0, 0, 0}) + } + } + } + b.Write(make([]byte, ((w+31)/32)*4*h)) // AND mask + return b.Bytes() +} + +func TestNormalizeLogo(t *testing.T) { + red := color.NRGBA{R: 255, A: 255} + t.Run("deterministic 256 square, aspect kept", func(t *testing.T) { + src := encodePNG(t, solid(100, 50, red)) + a, ea, err := NormalizeLogo(src) + if err != nil { + t.Fatal(err) + } + b, eb, _ := NormalizeLogo(src) + if !bytes.Equal(a, b) || ea != eb || len(ea) != 64 { + t.Fatalf("not deterministic: %s %s", ea, eb) + } + img, _ := png.Decode(bytes.NewReader(a)) + if img.Bounds().Dx() != 256 || img.Bounds().Dy() != 256 { + t.Fatalf("size %v", img.Bounds()) + } + // 100×50 fits as 256×128, centred: the top rows are transparent. + if _, _, _, alpha := img.At(128, 10).RGBA(); alpha != 0 { + t.Fatalf("top is not transparent: %v", img.At(128, 10)) + } + if r, _, _, alpha := img.At(128, 128).RGBA(); alpha != 0xffff || r != 0xffff { + t.Fatalf("centre is not red: %v", img.At(128, 128)) + } + }) + t.Run("ICO with a PNG entry", func(t *testing.T) { + if _, _, err := NormalizeLogo(ico(32, 32, 32, encodePNG(t, solid(32, 32, red)))); err != nil { + t.Fatal(err) + } + }) + t.Run("ICO with a 32-bit BMP entry", func(t *testing.T) { + img, err := DecodeImage(ico(16, 16, 32, dib32(16, 16))) + if err != nil { + t.Fatal(err) + } + if c := color.NRGBAModel.Convert(img.At(2, 3)).(color.NRGBA); c != red { + t.Fatalf("left %v", c) + } + if c := color.NRGBAModel.Convert(img.At(12, 3)).(color.NRGBA); c.A != 0 { + t.Fatalf("right %v", c) + } + }) + t.Run("refused", func(t *testing.T) { + for name, tc := range map[string]struct { + data []byte + want error + }{ + "svg": {[]byte(``), ErrSVG}, + "text": {[]byte("hello"), ErrNotImage}, + "too big": {make([]byte, MaxImageBytes+1), ErrImageTooLarge}, + "short ico": {[]byte{0, 0, 1, 0, 5, 0}, ErrNotImage}, + "bad entry": {ico(16, 16, 32, []byte{1, 2, 3}), ErrNotImage}, + } { + if _, _, err := NormalizeLogo(tc.data); !errors.Is(err, tc.want) { + t.Errorf("%s: %v, want %v", name, err, tc.want) + } + } + }) +} diff --git a/internal/config/config.go b/internal/config/config.go index 31ecb62..8c5a007 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -114,6 +114,11 @@ type Config struct { PruefwerkPlatformURL string PruefwerkURL string + // BrandingDerive (BRANDING_DERIVE=on) lets the registry fetch the home + // page of a workspace's signup domain to derive its colour and logo + // (#155). Off by default: the privacy notice has to name the fetch first. + BrandingDerive bool + // 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". @@ -228,6 +233,7 @@ func Load() (*Config, error) { PortalURL: getenv("PORTAL_URL", "https://app.breakpilot.com"), PruefwerkPlatformURL: os.Getenv("PRUEFWERK_PLATFORM_URL"), PruefwerkURL: os.Getenv("PRUEFWERK_URL"), + BrandingDerive: getenv("BRANDING_DERIVE", "off") == "on", LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"), LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"), diff --git a/internal/server/authz.go b/internal/server/authz.go index c632eb5..d0d8253 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -112,6 +112,12 @@ func routeGroup(method, path string) string { return "licences" case strings.HasPrefix(path, "/v1/trial-offers"): return "tenants.write" + case strings.HasPrefix(path, "/v1/tenants/") && strings.HasSuffix(path, "/branding/logo"): + // Customer branding (#155): every product client reads the logo and + // records "Passt"; the portal's writes stay tenants.write. + return "branding.read" + case strings.HasPrefix(path, "/v1/tenants/") && strings.HasSuffix(path, "/branding/ack"): + return "branding.ack" case strings.HasPrefix(path, "/v1/tenants"): if method == http.MethodGet { return "tenants.read" diff --git a/internal/server/authz_test.go b/internal/server/authz_test.go index 4bc9099..d52d1a9 100644 --- a/internal/server/authz_test.go +++ b/internal/server/authz_test.go @@ -3,7 +3,7 @@ package server import "testing" func TestAuthzRules(t *testing.T) { - a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; root:* ;broken") + a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read,branding.read,branding.ack; werkpilot-svc:tenants.read; root:* ;broken") cases := []struct { azp, method, path string want bool @@ -30,6 +30,16 @@ func TestAuthzRules(t *testing.T) { {"portal-svc", "GET", "/v1/internal/connections/c1", false}, {"portal-svc", "POST", "/v1/tenants/t1/connections", true}, {"pruefwerk-svc", "POST", "/v1/tenants/t1/connection-invites", false}, + // Branding (#155): products read the logo and acknowledge with their + // own groups; the portal's writes stay tenants.write. + {"pruefwerk-svc", "GET", "/v1/tenants/t1/branding/logo", true}, + {"pruefwerk-svc", "POST", "/v1/tenants/t1/branding/ack", true}, + {"pruefwerk-svc", "PUT", "/v1/tenants/t1/branding", false}, + {"werkpilot-svc", "GET", "/v1/tenants/t1/branding/logo", false}, + {"portal-svc", "PUT", "/v1/tenants/t1/branding", true}, + {"portal-svc", "GET", "/v1/tenants/t1/branding", true}, + {"portal-svc", "GET", "/v1/tenants/t1/branding/logo", false}, + {"portal-svc", "POST", "/v1/tenants/t1/branding/ack", false}, } for _, c := range cases { if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want { diff --git a/internal/server/branding.go b/internal/server/branding.go new file mode 100644 index 0000000..0347420 --- /dev/null +++ b/internal/server/branding.go @@ -0,0 +1,347 @@ +package server + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "slices" + "strings" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/branding" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Customer branding (#155, contract in the issue's comment of 01.12.2026): +// every frontend of a workspace shows its CI colour as a 6 px frame and its +// logo in the sidebar. +// +// GET /v1/tenants/{id}/branding (tenants.read) colour, provenance, state +// PUT /v1/tenants/{id}/branding (tenants.write) an admin's choice (manual) +// GET /v1/tenants/{id}/branding/logo (branding.read) 256×256 PNG, ETag +// POST /v1/tenants/{id}/branding/ack (branding.ack) "Passt" by an IT admin or owner +// +// The entitlements check carries the short form (BrandingCheck), so products +// need no call per page. The portal checks the user's org role before a PUT, +// as for the company profile; products name the user on an ack and the +// registry checks the role itself. + +// BrandingCheck is the "branding" field of the entitlements check. It is +// sent only when the tenant is allowed and has a colour or a logo. +type BrandingCheck struct { + Color *string `json:"color"` + LogoETag *string `json:"logo_etag"` + Notice bool `json:"notice"` + Domain string `json:"domain,omitempty"` // only with notice + Name string `json:"name,omitempty"` // tenants.name +} + +// brandingView is GET/PUT /v1/tenants/{id}/branding: the portal's +// Erscheinungsbild page. +type brandingView struct { + TenantID string `json:"tenant_id"` + Color *string `json:"color"` + LogoETag *string `json:"logo_etag"` + Manual bool `json:"manual"` + Domain string `json:"domain"` + ColorSource string `json:"color_source"` + LogoSource string `json:"logo_source"` + DerivedAt *time.Time `json:"derived_at"` + // DeriveState: none (never queued), pending, done or failed. + DeriveState string `json:"derive_state"` + DeriveError string `json:"derive_error,omitempty"` + Notice bool `json:"notice"` + NoticeAckAt *time.Time `json:"notice_ack_at"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedAt *time.Time `json:"updated_at"` + DeriveEnabled bool `json:"derive_enabled"` +} + +func (s *Server) brandingView(tenantID string, b *store.TenantBranding) brandingView { + v := brandingView{TenantID: tenantID, DeriveState: "none", DeriveEnabled: s.brandingDeriveEnabled()} + if b == nil { + return v + } + at := b.UpdatedAt + v.Color, v.LogoETag, v.Manual = b.Color, b.LogoETag, b.Manual + v.Domain, v.ColorSource, v.LogoSource, v.DerivedAt = b.Domain, b.ColorSource, b.LogoSource, b.DerivedAt + v.DeriveState, v.DeriveError = b.DeriveState, b.DeriveError + v.Notice, v.NoticeAckAt = b.Notice(), b.NoticeAckAt + v.UpdatedBy, v.UpdatedAt = b.UpdatedBy, &at + return v +} + +// brandingDeriveEnabled: the derivation (fetching the customer's home page) +// is switched on for this registry. +func (s *Server) brandingDeriveEnabled() bool { return s.Cfg != nil && s.Cfg.BrandingDerive } + +// brandingForCheck is the check's branding field; nil when there is nothing +// to show. A read error leaves it out: the check itself must not fail on it. +func (s *Server) brandingForCheck(ctx context.Context, tenantID, name string) *BrandingCheck { + b, err := s.Store.GetTenantBranding(ctx, tenantID) + if err != nil { + if !errors.Is(err, store.ErrNotFound) { + s.Log.Warn("branding read failed; check sent without it", "tenant_id", tenantID, "err", err) + } + return nil + } + if b.Empty() { + return nil + } + out := &BrandingCheck{Color: b.Color, LogoETag: b.LogoETag, Notice: b.Notice(), Name: name} + if out.Notice { + out.Domain = b.Domain + } + return out +} + +// getTenantBranding is GET /v1/tenants/{id}/branding (a tenantSubresource). +func (s *Server) getTenantBranding(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + b, err := s.Store.GetTenantBranding(ctx, t.ID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, s.brandingView(t.ID, b)) +} + +// getTenantBrandingLogo is GET /v1/tenants/{id}/branding/logo. +func (s *Server) getTenantBrandingLogo(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + png, etag, err := s.Store.GetTenantBrandingLogo(ctx, t.ID) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusNotFound, "no_logo", "the workspace has no logo") + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + tag := `"` + etag + `"` + w.Header().Set("ETag", tag) + w.Header().Set("Cache-Control", "private, no-cache") + w.Header().Set("X-Content-Type-Options", "nosniff") + if etagMatches(r.Header.Get("If-None-Match"), tag) { + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set("Content-Type", "image/png") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(png) +} + +// etagMatches: If-None-Match names tag (strong or weak) or is "*". +func etagMatches(header, tag string) bool { + for _, v := range strings.Split(header, ",") { + v = strings.TrimPrefix(strings.TrimSpace(v), "W/") + if v == tag || v == "*" { + return true + } + } + return false +} + +// maxBrandingBody: a base64 logo of at most 1 MiB plus the colour. +const maxBrandingBody = branding.MaxImageBytes*4/3 + 4096 + +// putTenantBranding is PUT /v1/tenants/{id}/branding. Body fields: +// "color" ("#rrggbb", any case) and "logo" (base64 PNG, JPEG, GIF or ICO); +// null removes one, a missing field leaves it as it is. Either way the +// branding becomes manual and is never derived over again. +func (s *Server) putTenantBranding(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, maxBrandingBody) + var in map[string]json.RawMessage + if !decodeJSON(w, r, &in) { + return + } + for k := range in { + if k != "color" && k != "logo" { + writeError(w, http.StatusBadRequest, "invalid_input", "unknown field "+k+"; expected color and/or logo") + return + } + } + rawColor, setColor := in["color"] + rawLogo, setLogo := in["logo"] + if !setColor && !setLogo { + writeError(w, http.StatusBadRequest, "invalid_input", "color or logo is required") + return + } + write := store.BrandingManualWrite{SetColor: setColor, SetLogo: setLogo, At: s.now()} + if setColor { + var c *string + if json.Unmarshal(rawColor, &c) != nil { + writeError(w, http.StatusBadRequest, "invalid_color", `color must be "#rrggbb" or null`) + return + } + if c != nil { + norm, ok := normalizeHexColor(*c) + if !ok { + writeError(w, http.StatusBadRequest, "invalid_color", `color must be "#rrggbb" or null`) + return + } + write.Color = &norm + } + } + if setLogo { + var enc *string + if json.Unmarshal(rawLogo, &enc) != nil { + writeError(w, http.StatusBadRequest, "invalid_logo", "logo must be a base64 image or null") + return + } + if enc != nil { + data, err := base64.StdEncoding.DecodeString(*enc) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_logo", "logo must be a base64 image or null") + return + } + png, etag, err := branding.NormalizeLogo(data) + switch { + case errors.Is(err, branding.ErrSVG): + writeError(w, http.StatusBadRequest, "svg_not_supported", "SVG logos are not supported; upload a PNG or JPEG") + return + case errors.Is(err, branding.ErrImageTooLarge): + writeError(w, http.StatusRequestEntityTooLarge, "logo_too_large", "the logo may have at most 1 MiB and 4096×4096 pixels") + return + case err != nil: + writeError(w, http.StatusBadRequest, "invalid_logo", "the logo must be a PNG, JPEG, GIF or ICO image") + return + } + write.Logo, write.LogoETag = png, etag + } + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + write.TenantID, write.By = t.ID, s.projectActor(r) + b, err := s.Store.SetManualBranding(ctx, write) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + meta := map[string]interface{}{"color_changed": setColor, "logo_changed": setLogo} + if setColor { + meta["color"] = write.Color + } + if setLogo { + meta["logo_etag"] = b.LogoETag + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "branding.updated", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", + ActorType: s.projectActorType(r), ActorName: write.By, Metadata: meta, + }) + writeJSON(w, http.StatusOK, s.brandingView(t.ID, b)) +} + +// normalizeHexColor accepts "#rrggbb" in any case and returns it lowercase. +func normalizeHexColor(c string) (string, bool) { + c = strings.ToLower(strings.TrimSpace(c)) + if len(c) != 7 || c[0] != '#' { + return "", false + } + for _, r := range c[1:] { + if !isLowerHex(r) { + return "", false + } + } + return c, true +} + +type brandingAckReq struct { + UserID string `json:"user_id"` +} + +// ackTenantBranding is POST /v1/tenants/{id}/branding/ack: "Passt" on the +// admin notice. Only an IT admin or owner of the tenant may; when that +// cannot be checked, the answer is 403 too. 204 also when it was +// acknowledged already or there is nothing to acknowledge. +func (s *Server) ackTenantBranding(w http.ResponseWriter, r *http.Request) { + var in brandingAckReq + if !decodeJSON(w, r, &in) { + return + } + userID := strings.TrimSpace(in.UserID) + if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() { + userID = p.Subject // a user token speaks for itself + } + if userID == "" { + writeError(w, http.StatusBadRequest, "invalid_input", "user_id is required") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + member, err := s.brandingAdmin(ctx, t, userID) + if err != nil { + s.Log.Warn("branding ack: role check failed", "tenant_id", t.ID, "user_id", userID, "err", err) + writeError(w, http.StatusForbidden, "not_admin", "the role of this user could not be checked") + return + } + if member == nil { + writeError(w, http.StatusForbidden, "not_admin", "only an IT admin or owner of the workspace may acknowledge the branding") + return + } + acked, err := s.Store.AckBrandingNotice(ctx, t.ID, userID, s.now()) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if acked { + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "branding.acknowledged", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", + ActorID: userID, ActorName: member.Email, ActorType: "user", + }) + } + w.WriteHeader(http.StatusNoContent) +} + +// brandingAdmin returns the member when userID is an enabled, unblocked IT +// admin or owner of t; nil when not. +func (s *Server) brandingAdmin(ctx context.Context, t *store.Tenant, userID string) (*keycloak.OrgMember, error) { + members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) + if errors.Is(err, keycloak.ErrOrgNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + for i := range members { + m := &members[i] + if m.UserID != userID { + continue + } + if !m.Enabled || slices.Contains(m.BlockedTenants, t.ID) { + return nil, nil + } + if slices.Contains(m.OrgRoles, authn.RoleITAdmin) || slices.Contains(m.OrgRoles, authn.RoleOwner) { + return m, nil + } + return nil, nil + } + return nil, nil +} + +func isLowerHex(r rune) bool { return '0' <= r && r <= '9' || 'a' <= r && r <= 'f' } diff --git a/internal/server/branding_test.go b/internal/server/branding_test.go new file mode 100644 index 0000000..69aacfe --- /dev/null +++ b/internal/server/branding_test.go @@ -0,0 +1,300 @@ +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(``))}, + } { + 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) + } +} diff --git a/internal/server/entitlements.go b/internal/server/entitlements.go index 887642c..313c2e8 100644 --- a/internal/server/entitlements.go +++ b/internal/server/entitlements.go @@ -32,6 +32,11 @@ type EntitlementCheck struct { // Preview: allowed through a staff preview grant (product not for sale // yet). Products may show it; usage under it is not invoiced. Preview bool `json:"preview,omitempty"` + // Branding (#155): the workspace's colour and logo, only when allowed + // and there is something to show. + Branding *BrandingCheck `json:"branding,omitempty"` + + tenantName string // for Branding.Name } // checkEntitlement is POST /v1/internal/entitlements/check. @@ -62,6 +67,9 @@ func (s *Server) checkEntitlement(w http.ResponseWriter, r *http.Request) { res = EntitlementCheck{Status: res.Status, Reason: "member_blocked"} } } + if res.Allowed { + res.Branding = s.brandingForCheck(ctx, in.TenantID, res.tenantName) + } writeJSON(w, http.StatusOK, res) } @@ -85,7 +93,7 @@ func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq } return EntitlementCheck{}, err } - out := EntitlementCheck{Status: t.Status} + out := EntitlementCheck{Status: t.Status, tenantName: t.Name} switch t.Status { case store.StatusArchived: out.Reason = "tenant_archived" diff --git a/internal/server/members.go b/internal/server/members.go index 61bc8a4..bc99326 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -70,7 +70,7 @@ func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *ht var tenantSubresources = []string{ "members", "documents", "projects", "contracts", "managed-services", "company-profile", "role-dataset", "store", - "module-users", "connections", "connection-invites", + "module-users", "connections", "connection-invites", "branding", } // tenantSubresource dispatches GET /v1/tenants/{id}/{sub}. Only the members @@ -102,6 +102,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) { s.listConnections(w, r) case "connection-invites": s.listConnectionInvites(w, r) + case "branding": + s.getTenantBranding(w, r) default: writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource") } diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 3b05e94..a17eb2d 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -50,6 +50,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants?limit=10"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding"}, + {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding/logo"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding/ack"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities"}, {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities/portal:billing.view"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests"}, diff --git a/internal/server/server.go b/internal/server/server.go index 6f63037..d396e40 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -176,6 +176,10 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/consent-banner", s.storeConsentBanner) mux.HandleFunc("GET /v1/tenants/{id}/store/assets/{sha}", s.storeAsset) // Unternehmensprofil (0021): the GET is a {sub} of tenantSubresource. + // Customer branding (#155, branding.go). + mux.HandleFunc("PUT /v1/tenants/{id}/branding", s.putTenantBranding) + mux.HandleFunc("GET /v1/tenants/{id}/branding/logo", s.getTenantBrandingLogo) + mux.HandleFunc("POST /v1/tenants/{id}/branding/ack", s.ackTenantBranding) mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile) mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile) // Rollen- und Befugnisdatensatz (0024): the GET is a {sub} of tenantSubresource. diff --git a/internal/store/branding.go b/internal/store/branding.go new file mode 100644 index 0000000..8a41d7b --- /dev/null +++ b/internal/store/branding.go @@ -0,0 +1,84 @@ +package store + +import "time" + +// Customer branding (0035, #155): the colour and logo every frontend of a +// workspace shows. A derivation reads the home page of the signup domain; +// an admin's choice in the portal (Manual) is never derived over. +const ( + BrandingPending = "pending" // waiting for the background derivation + BrandingDone = "done" + BrandingFailed = "failed" // gave up; "Neu ermitteln" tries again + + BrandingSourceThemeColor = "theme-color" + BrandingSourceManifest = "manifest" + BrandingSourceLogo = "logo" + BrandingSourceManual = "manual" +) + +// TenantBranding is one workspace's branding without the logo bytes. +type TenantBranding struct { + TenantID string `json:"tenant_id"` + Color *string `json:"color"` // "#rrggbb", lowercase + LogoETag *string `json:"logo_etag"` // sha256 hex of the stored PNG + Manual bool `json:"manual"` + + Domain string `json:"domain"` + ColorSource string `json:"color_source"` + LogoSource string `json:"logo_source"` + HTMLSHA256 string `json:"html_sha256"` + LogoSHA256 string `json:"logo_sha256"` + DerivedAt *time.Time `json:"derived_at"` + + DeriveState string `json:"derive_state"` + DeriveError string `json:"derive_error"` + DeriveAttempts int `json:"derive_attempts"` + NextAttemptAt *time.Time `json:"-"` + + NoticeAckAt *time.Time `json:"notice_ack_at"` + NoticeAckBy string `json:"-"` + UpdatedBy string `json:"updated_by"` + UpdatedAt time.Time `json:"updated_at"` +} + +// Empty: nothing to show (no colour, no logo). +func (b *TenantBranding) Empty() bool { return b == nil || (b.Color == nil && b.LogoETag == nil) } + +// Notice: a derived branding nobody has acknowledged yet. Admins see the +// one-time "Logo und Farbe von übernommen" until "Passt". +func (b *TenantBranding) Notice() bool { + return !b.Empty() && !b.Manual && b.DerivedAt != nil && b.NoticeAckAt == nil +} + +// BrandingManualWrite is an admin's change in the portal. Each part is +// changed only when its Set flag is true; a nil value then removes it. +// Either way the branding becomes manual. +type BrandingManualWrite struct { + TenantID string + SetColor bool + Color *string + SetLogo bool + Logo []byte // normalised 256×256 PNG + LogoETag string // sha256 hex of Logo + By string + At time.Time +} + +// DerivedBranding is the result of one successful derivation. +type DerivedBranding struct { + TenantID string + Color *string + Logo []byte + LogoETag string + Domain string + ColorSource string + LogoSource string + HTMLSHA256 string + LogoSHA256 string + At time.Time + // Force: an admin asked for it ("Neu ermitteln"). It replaces a manual + // choice and counts as acknowledged. Without it a manual branding is + // left alone (applied=false). + Force bool + By string +} diff --git a/internal/store/memory.go b/internal/store/memory.go index 5ca4395..b9e81a5 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -64,6 +64,8 @@ type Memory struct { moduleDays map[moduleDayKey]int // Managed Git daily counts (0031) moduleSeen map[moduleSeenKey]time.Time // licence users per month (0031) → first seen + + branding map[string]*memBranding // tenant_id → branding (0035) } type apiKeyWithHash struct { @@ -99,6 +101,7 @@ func NewMemory() *Memory { moduleDays: make(map[moduleDayKey]int), moduleSeen: make(map[moduleSeenKey]time.Time), + branding: make(map[string]*memBranding), } now := time.Now().UTC() seed := &Tenant{ @@ -632,6 +635,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id }) m.deleteConnections(id) m.deleteModuleUsers(id) + delete(m.branding, id) for kid, k := range m.apiKeys { if k.TenantID == id { delete(m.apiKeys, kid) diff --git a/internal/store/memory_branding.go b/internal/store/memory_branding.go new file mode 100644 index 0000000..1d3b8ee --- /dev/null +++ b/internal/store/memory_branding.go @@ -0,0 +1,238 @@ +package store + +import ( + "context" + "slices" + "sort" + "time" +) + +type memBranding struct { + TenantBranding + logo []byte +} + +func (b *memBranding) copyOut() *TenantBranding { + cp := b.TenantBranding + return &cp +} + +func (m *Memory) GetTenantBranding(_ context.Context, tenantID string) (*TenantBranding, error) { + m.mu.RLock() + defer m.mu.RUnlock() + b, ok := m.branding[tenantID] + if !ok { + return nil, ErrNotFound + } + return b.copyOut(), nil +} + +func (m *Memory) GetTenantBrandingLogo(_ context.Context, tenantID string) ([]byte, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + b, ok := m.branding[tenantID] + if !ok || b.logo == nil || b.LogoETag == nil { + return nil, "", ErrNotFound + } + return slices.Clone(b.logo), *b.LogoETag, nil +} + +// brandingRow returns the tenant's row, creating a pending one; nil for an +// unknown tenant. Callers hold m.mu. +func (m *Memory) brandingRow(tenantID string, at time.Time) (*memBranding, bool) { + if b, ok := m.branding[tenantID]; ok { + return b, false + } + if _, ok := m.tenants[tenantID]; !ok { + return nil, false + } + b := &memBranding{TenantBranding: TenantBranding{TenantID: tenantID, DeriveState: BrandingPending, UpdatedAt: at.UTC()}} + m.branding[tenantID] = b + return b, true +} + +func (m *Memory) EnqueueBranding(_ context.Context, tenantID string, at time.Time) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + b, created := m.brandingRow(tenantID, at) + if b == nil { + return false, ErrNotFound + } + return created, nil +} + +func (m *Memory) EnqueueMissingBranding(_ context.Context, at time.Time) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for id, t := range m.tenants { + if t.Kind != "customer" || t.Status == StatusDemo || t.Status == StatusArchived { + continue + } + if _, created := m.brandingRow(id, at); created { + n++ + } + } + return n, nil +} + +func (m *Memory) DueBranding(_ context.Context, now time.Time, limit int) ([]string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var due []*memBranding + for _, b := range m.branding { + if b.DeriveState == BrandingPending && !b.Manual && (b.NextAttemptAt == nil || !b.NextAttemptAt.After(now)) { + due = append(due, b) + } + } + sort.Slice(due, func(i, j int) bool { + if !due[i].UpdatedAt.Equal(due[j].UpdatedAt) { + return due[i].UpdatedAt.Before(due[j].UpdatedAt) + } + return due[i].TenantID < due[j].TenantID + }) + out := []string{} + for _, b := range due { + if limit > 0 && len(out) == limit { + break + } + out = append(out, b.TenantID) + } + return out, nil +} + +func (m *Memory) SaveDerivedBranding(_ context.Context, d DerivedBranding) (bool, error) { + if !validBrandingColor(d.Color) || (d.Logo == nil) != (d.LogoETag == "") { + return false, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + b, _ := m.brandingRow(d.TenantID, d.At) + if b == nil { + return false, ErrNotFound + } + if b.Manual && !d.Force { + return false, nil + } + at := d.At.UTC() + etag := optString(d.LogoETag) + unchanged := sameOptString(b.Color, d.Color) && sameOptString(b.LogoETag, etag) + switch { + case d.Force: + b.NoticeAckAt, b.NoticeAckBy = &at, d.By + case !unchanged: + b.NoticeAckAt, b.NoticeAckBy = nil, "" + } + b.Color, b.LogoETag, b.logo = cloneOptString(d.Color), etag, slices.Clone(d.Logo) + b.Manual = false + b.Domain, b.ColorSource, b.LogoSource = d.Domain, d.ColorSource, d.LogoSource + b.HTMLSHA256, b.LogoSHA256, b.DerivedAt = d.HTMLSHA256, d.LogoSHA256, &at + b.DeriveState, b.DeriveError, b.NextAttemptAt = BrandingDone, "", nil + b.DeriveAttempts++ + b.UpdatedBy, b.UpdatedAt = d.By, at + return true, nil +} + +func (m *Memory) FailBranding(_ context.Context, tenantID, msg string, next *time.Time, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + b, _ := m.brandingRow(tenantID, at) + if b == nil { + return ErrNotFound + } + b.DeriveState = BrandingFailed + b.NextAttemptAt = nil + if next != nil { + n := next.UTC() + b.DeriveState, b.NextAttemptAt = BrandingPending, &n + } + b.DeriveError = msg + b.DeriveAttempts++ + b.UpdatedAt = at.UTC() + return nil +} + +func (m *Memory) SetManualBranding(_ context.Context, w BrandingManualWrite) (*TenantBranding, error) { + if (w.SetColor && !validBrandingColor(w.Color)) || (w.SetLogo && (w.Logo == nil) != (w.LogoETag == "")) { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + b, created := m.brandingRow(w.TenantID, w.At) + if b == nil { + return nil, ErrNotFound + } + if created { + b.DeriveState = BrandingDone + } + if w.SetColor { + b.Color = cloneOptString(w.Color) + b.ColorSource = "" + if w.Color != nil { + b.ColorSource = BrandingSourceManual + } + } + if w.SetLogo { + b.LogoETag, b.logo = optString(w.LogoETag), slices.Clone(w.Logo) + b.LogoSource, b.LogoSHA256 = "", "" + } + b.Manual = true + b.UpdatedBy, b.UpdatedAt = w.By, w.At.UTC() + return b.copyOut(), nil +} + +func (m *Memory) AckBrandingNotice(_ context.Context, tenantID, by string, at time.Time) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + b, ok := m.branding[tenantID] + if !ok { + return false, ErrNotFound + } + if b.NoticeAckAt != nil { + return false, nil + } + t := at.UTC() + b.NoticeAckAt, b.NoticeAckBy = &t, by + return true, nil +} + +func optString(s string) *string { + if s == "" { + return nil + } + return &s +} + +func cloneOptString(s *string) *string { + if s == nil { + return nil + } + v := *s + return &v +} + +func sameOptString(a, b *string) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +// validBrandingColor: nil or lowercase "#rrggbb" (the column's CHECK). +func validBrandingColor(c *string) bool { + if c == nil { + return true + } + s := *c + if len(s) != 7 || s[0] != '#' { + return false + } + for _, r := range s[1:] { + if !isLowerHex(r) { + return false + } + } + return true +} + +func isLowerHex(r rune) bool { return '0' <= r && r <= '9' || 'a' <= r && r <= 'f' } diff --git a/internal/store/postgres_branding.go b/internal/store/postgres_branding.go new file mode 100644 index 0000000..fe5ecc8 --- /dev/null +++ b/internal/store/postgres_branding.go @@ -0,0 +1,218 @@ +package store + +import ( + "context" + "errors" + "time" + + "github.com/jackc/pgx/v5" +) + +const brandingSelect = ` +SELECT tenant_id::text, color, logo_etag, manual, domain, color_source, logo_source, + html_sha256, logo_sha256, derived_at, derive_state, derive_error, derive_attempts, + next_attempt_at, notice_ack_at, notice_ack_by, updated_by, updated_at +FROM tenant_branding ` + +func scanBranding(row pgx.Row) (*TenantBranding, error) { + var b TenantBranding + err := row.Scan(&b.TenantID, &b.Color, &b.LogoETag, &b.Manual, &b.Domain, &b.ColorSource, &b.LogoSource, + &b.HTMLSHA256, &b.LogoSHA256, &b.DerivedAt, &b.DeriveState, &b.DeriveError, &b.DeriveAttempts, + &b.NextAttemptAt, &b.NoticeAckAt, &b.NoticeAckBy, &b.UpdatedBy, &b.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) || isInvalidUUID(err) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &b, nil +} + +func (p *Postgres) GetTenantBranding(ctx context.Context, tenantID string) (*TenantBranding, error) { + return scanBranding(p.pool.QueryRow(ctx, brandingSelect+`WHERE tenant_id = $1::uuid`, tenantID)) +} + +func (p *Postgres) GetTenantBrandingLogo(ctx context.Context, tenantID string) ([]byte, string, error) { + var png []byte + var etag string + err := p.pool.QueryRow(ctx, ` + SELECT logo, logo_etag FROM tenant_branding + WHERE tenant_id = $1::uuid AND logo IS NOT NULL`, tenantID).Scan(&png, &etag) + if errors.Is(err, pgx.ErrNoRows) || isInvalidUUID(err) { + return nil, "", ErrNotFound + } + if err != nil { + return nil, "", err + } + return png, etag, nil +} + +func (p *Postgres) EnqueueBranding(ctx context.Context, tenantID string, at time.Time) (bool, error) { + tag, err := p.pool.Exec(ctx, ` + INSERT INTO tenant_branding (tenant_id, updated_at) VALUES ($1::uuid, $2) + ON CONFLICT (tenant_id) DO NOTHING`, tenantID, at.UTC()) + if isFKViolation(err) || isInvalidUUID(err) { + return false, ErrNotFound + } + if err != nil { + return false, err + } + return tag.RowsAffected() == 1, nil +} + +func (p *Postgres) EnqueueMissingBranding(ctx context.Context, at time.Time) (int, error) { + tag, err := p.pool.Exec(ctx, ` + INSERT INTO tenant_branding (tenant_id, updated_at) + SELECT t.id, $1 FROM tenants t + WHERE t.kind = 'customer' AND t.status NOT IN ('demo', 'archived') + AND NOT EXISTS (SELECT 1 FROM tenant_branding b WHERE b.tenant_id = t.id) + ORDER BY t.created_at + ON CONFLICT (tenant_id) DO NOTHING`, at.UTC()) + if err != nil { + return 0, err + } + return int(tag.RowsAffected()), nil +} + +func (p *Postgres) DueBranding(ctx context.Context, now time.Time, limit int) ([]string, error) { + if limit <= 0 { + limit = 100 + } + rows, err := p.pool.Query(ctx, ` + SELECT tenant_id::text FROM tenant_branding + WHERE derive_state = 'pending' AND NOT manual + AND (next_attempt_at IS NULL OR next_attempt_at <= $1) + ORDER BY updated_at, tenant_id + LIMIT $2`, now.UTC(), limit) + if err != nil { + return nil, err + } + ids, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if ids == nil { + ids = []string{} + } + return ids, err +} + +func (p *Postgres) SaveDerivedBranding(ctx context.Context, d DerivedBranding) (bool, error) { + if !validBrandingColor(d.Color) || (d.Logo == nil) != (d.LogoETag == "") { + return false, ErrInvalidInput + } + // One statement: the manual check and the write cannot be separated by + // an admin's save. The notice comes back only when what is shown + // changed; a forced run ("Neu ermitteln") counts as acknowledged. + tag, err := p.pool.Exec(ctx, ` + INSERT INTO tenant_branding AS b (tenant_id, color, logo, logo_etag, manual, domain, color_source, + logo_source, html_sha256, logo_sha256, derived_at, derive_state, derive_error, derive_attempts, + next_attempt_at, notice_ack_at, notice_ack_by, updated_by, updated_at) + VALUES ($1::uuid, $2, $3, $4, false, $5, $6, $7, $8, $9, $10, 'done', '', 1, NULL, + CASE WHEN $11 THEN $10::timestamptz END, CASE WHEN $11 THEN $12 ELSE '' END, $12, $10) + ON CONFLICT (tenant_id) DO UPDATE SET + notice_ack_at = CASE + WHEN $11 THEN $10::timestamptz + WHEN b.color IS NOT DISTINCT FROM EXCLUDED.color AND b.logo_etag IS NOT DISTINCT FROM EXCLUDED.logo_etag THEN b.notice_ack_at + END, + notice_ack_by = CASE + WHEN $11 THEN $12 + WHEN b.color IS NOT DISTINCT FROM EXCLUDED.color AND b.logo_etag IS NOT DISTINCT FROM EXCLUDED.logo_etag THEN b.notice_ack_by + ELSE '' END, + color = EXCLUDED.color, logo = EXCLUDED.logo, logo_etag = EXCLUDED.logo_etag, manual = false, + domain = EXCLUDED.domain, color_source = EXCLUDED.color_source, logo_source = EXCLUDED.logo_source, + html_sha256 = EXCLUDED.html_sha256, logo_sha256 = EXCLUDED.logo_sha256, derived_at = EXCLUDED.derived_at, + derive_state = 'done', derive_error = '', derive_attempts = b.derive_attempts + 1, next_attempt_at = NULL, + updated_by = EXCLUDED.updated_by, updated_at = EXCLUDED.updated_at + WHERE NOT b.manual OR $11`, + d.TenantID, d.Color, nilIfEmpty(d.Logo), optString(d.LogoETag), d.Domain, d.ColorSource, d.LogoSource, + d.HTMLSHA256, d.LogoSHA256, d.At.UTC(), d.Force, d.By) + switch { + case isFKViolation(err), isInvalidUUID(err): + return false, ErrNotFound + case isCheckViolation(err): + return false, ErrInvalidInput + case err != nil: + return false, err + } + return tag.RowsAffected() == 1, nil +} + +func (p *Postgres) FailBranding(ctx context.Context, tenantID, msg string, next *time.Time, at time.Time) error { + state := BrandingFailed + if next != nil { + state = BrandingPending + n := next.UTC() + next = &n + } + _, err := p.pool.Exec(ctx, ` + INSERT INTO tenant_branding AS b (tenant_id, derive_state, derive_error, derive_attempts, next_attempt_at, updated_at) + VALUES ($1::uuid, $2, $3, 1, $4, $5) + ON CONFLICT (tenant_id) DO UPDATE SET + derive_state = EXCLUDED.derive_state, derive_error = EXCLUDED.derive_error, + derive_attempts = b.derive_attempts + 1, next_attempt_at = EXCLUDED.next_attempt_at, + updated_at = EXCLUDED.updated_at`, + tenantID, state, msg, next, at.UTC()) + if isFKViolation(err) || isInvalidUUID(err) { + return ErrNotFound + } + return err +} + +func (p *Postgres) SetManualBranding(ctx context.Context, w BrandingManualWrite) (*TenantBranding, error) { + if (w.SetColor && !validBrandingColor(w.Color)) || (w.SetLogo && (w.Logo == nil) != (w.LogoETag == "")) { + return nil, ErrInvalidInput + } + colorSource := "" + if w.Color != nil { + colorSource = BrandingSourceManual + } + // A first row written by hand is not waiting for a derivation. + _, err := p.pool.Exec(ctx, ` + INSERT INTO tenant_branding AS b (tenant_id, color, color_source, logo, logo_etag, manual, derive_state, updated_by, updated_at) + VALUES ($1::uuid, + CASE WHEN $2 THEN $3 END, CASE WHEN $2 THEN $4 ELSE '' END, + CASE WHEN $5 THEN $6::bytea END, CASE WHEN $5 THEN $7 END, + true, 'done', $8, $9) + ON CONFLICT (tenant_id) DO UPDATE SET + color = CASE WHEN $2 THEN $3 ELSE b.color END, + color_source = CASE WHEN $2 THEN $4 ELSE b.color_source END, + logo = CASE WHEN $5 THEN $6::bytea ELSE b.logo END, + logo_etag = CASE WHEN $5 THEN $7 ELSE b.logo_etag END, + logo_source = CASE WHEN $5 THEN '' ELSE b.logo_source END, + logo_sha256 = CASE WHEN $5 THEN '' ELSE b.logo_sha256 END, + manual = true, updated_by = EXCLUDED.updated_by, updated_at = EXCLUDED.updated_at`, + w.TenantID, w.SetColor, w.Color, colorSource, w.SetLogo, nilIfEmpty(w.Logo), optString(w.LogoETag), w.By, w.At.UTC()) + switch { + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + case err != nil: + return nil, err + } + return p.GetTenantBranding(ctx, w.TenantID) +} + +func (p *Postgres) AckBrandingNotice(ctx context.Context, tenantID, by string, at time.Time) (bool, error) { + tag, err := p.pool.Exec(ctx, ` + UPDATE tenant_branding SET notice_ack_at = $2, notice_ack_by = $3 + WHERE tenant_id = $1::uuid AND notice_ack_at IS NULL`, tenantID, at.UTC(), by) + if isInvalidUUID(err) { + return false, ErrNotFound + } + if err != nil { + return false, err + } + if tag.RowsAffected() == 1 { + return true, nil + } + if _, err := p.GetTenantBranding(ctx, tenantID); err != nil { + return false, err + } + return false, nil +} + +func nilIfEmpty(b []byte) []byte { + if len(b) == 0 { + return nil + } + return b +} diff --git a/internal/store/store.go b/internal/store/store.go index 6b9c812..2a36408 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -356,6 +356,29 @@ type Store interface { AddModuleUsersSeen(ctx context.Context, tenantID, module, month string, subjects []string) (int, error) ModuleUserCounts(ctx context.Context, tenantID, month string) ([]ModuleUserCount, error) + // Customer branding (0035, #155). GetTenantBranding is ErrNotFound when + // the tenant has no row; GetTenantBrandingLogo also when it has no logo. + // EnqueueBranding adds a pending row unless one exists (created=false; + // ErrNotFound for an unknown tenant); EnqueueMissingBranding does that + // for every customer tenant that is neither demo nor archived. + // DueBranding lists pending, not manual rows whose next attempt is due, + // oldest first. SaveDerivedBranding writes a derivation unless the row + // is manual and Force is false (applied=false); the notice is raised + // again only when colour or logo changed. FailBranding records a failed + // attempt: pending again at next, or failed when next is nil. + // SetManualBranding writes an admin's choice (ErrNotFound for an + // unknown tenant). AckBrandingNotice records "Passt" (ErrNotFound when + // there is no row; acked=false when it was acknowledged already). + GetTenantBranding(ctx context.Context, tenantID string) (*TenantBranding, error) + GetTenantBrandingLogo(ctx context.Context, tenantID string) (png []byte, etag string, err error) + EnqueueBranding(ctx context.Context, tenantID string, at time.Time) (created bool, err error) + EnqueueMissingBranding(ctx context.Context, at time.Time) (int, error) + DueBranding(ctx context.Context, now time.Time, limit int) ([]string, error) + SaveDerivedBranding(ctx context.Context, d DerivedBranding) (applied bool, err error) + FailBranding(ctx context.Context, tenantID, msg string, next *time.Time, at time.Time) error + SetManualBranding(ctx context.Context, w BrandingManualWrite) (*TenantBranding, error) + AckBrandingNotice(ctx context.Context, tenantID, by string, at time.Time) (acked bool, err error) + // Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey // (false when the key existed). ClaimMail leases due unsent rows. EnqueueMail(ctx context.Context, m MailItem) (bool, error) diff --git a/migrations/0035_tenant_branding.down.sql b/migrations/0035_tenant_branding.down.sql new file mode 100644 index 0000000..e25d193 --- /dev/null +++ b/migrations/0035_tenant_branding.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS tenant_branding; diff --git a/migrations/0035_tenant_branding.up.sql b/migrations/0035_tenant_branding.up.sql new file mode 100644 index 0000000..1e9ca30 --- /dev/null +++ b/migrations/0035_tenant_branding.up.sql @@ -0,0 +1,33 @@ +-- Customer branding (#155): the CI colour and logo every frontend shows, +-- derived from the home page of the domain the customer signed up with, or +-- set by a workspace admin in the portal (manual, never derived over). +CREATE TABLE tenant_branding ( + tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE, + color TEXT CHECK (color ~ '^#[0-9a-f]{6}$'), + logo BYTEA, + logo_etag TEXT CHECK (logo_etag ~ '^[0-9a-f]{64}$'), + manual BOOLEAN NOT NULL DEFAULT false, + -- Provenance of the last derivation (no page content). + domain TEXT NOT NULL DEFAULT '', + color_source TEXT NOT NULL DEFAULT '' + CHECK (color_source IN ('', 'theme-color', 'manifest', 'logo', 'manual')), + logo_source TEXT NOT NULL DEFAULT '', + html_sha256 TEXT NOT NULL DEFAULT '', + logo_sha256 TEXT NOT NULL DEFAULT '', + derived_at TIMESTAMPTZ, + -- The derivation queue: pending rows are picked up in the background. + derive_state TEXT NOT NULL DEFAULT 'pending' + CHECK (derive_state IN ('pending', 'done', 'failed')), + derive_error TEXT NOT NULL DEFAULT '', + derive_attempts INT NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMPTZ, + -- "Passt": the admin notice was acknowledged. + notice_ack_at TIMESTAMPTZ, + notice_ack_by TEXT NOT NULL DEFAULT '', + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((logo IS NULL) = (logo_etag IS NULL)) +); + +CREATE INDEX tenant_branding_due ON tenant_branding (updated_at) + WHERE derive_state = 'pending' AND NOT manual; diff --git a/openapi.yaml b/openapi.yaml index 1851bb0..101d64c 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -450,6 +450,90 @@ paths: "404": { $ref: "#/components/responses/NotFound" } "502": { description: digest_mismatch or storage_failed. } + /v1/tenants/{id}/branding: + get: + summary: The workspace's branding (Erscheinungsbild) with its provenance. + description: | + Served by the `{id}/{sub}` route (tenants.read); user tokens reach + their own tenant only. No logo bytes; the logo is its own route. + derive_state is `none` when the workspace was never queued. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The branding. + content: + application/json: { schema: { $ref: "#/components/schemas/Branding" } } + "404": { $ref: "#/components/responses/NotFound" } + put: + summary: Set or remove the colour and/or logo (an admin's choice). + description: | + The portal calls this for IT admins and owners (named in + X-Portal-User-Email). A field that is missing stays as it is; null + removes it. The branding becomes manual: no derivation runs over it + again, and no notice is shown. The logo is decoded and stored as a + 256×256 PNG; SVG is refused. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + color: { type: string, nullable: true, pattern: "^#[0-9a-fA-F]{6}$" } + logo: { type: string, nullable: true, format: byte, description: "base64 PNG, JPEG, GIF or ICO, at most 1 MiB" } + responses: + "200": + description: Saved. + content: + application/json: { schema: { $ref: "#/components/schemas/Branding" } } + "400": { description: "invalid_input, invalid_color, invalid_logo or svg_not_supported." } + "404": { $ref: "#/components/responses/NotFound" } + "413": { description: "logo_too_large: more than 1 MiB or 4096×4096 pixels." } + + /v1/tenants/{id}/branding/logo: + get: + summary: The workspace's logo as a 256×256 PNG. + description: | + Route group branding.read (every product's service client). The + ETag is the quoted logo_etag of the entitlements check; a matching + If-None-Match answers 304. Never SVG. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: header, name: If-None-Match, required: false, schema: { type: string } } + responses: + "200": + description: The logo. + headers: + ETag: { schema: { type: string } } + content: + image/png: { schema: { type: string, format: binary } } + "304": { description: Not modified. } + "404": { description: The tenant does not exist or has no logo (no_logo). } + + /v1/tenants/{id}/branding/ack: + post: + summary: Acknowledge the branding notice ("Passt"). + description: | + Route group branding.ack. The registry checks that user_id is an + enabled, unblocked IT_ADMIN or OWNER of the tenant; otherwise, and + when that cannot be checked, 403 not_admin. A user token speaks for + itself (user_id is ignored). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: { type: object, required: [user_id], properties: { user_id: { type: string } } } + responses: + "204": { description: "Acknowledged, also when it was already or there is nothing to acknowledge." } + "400": { description: user_id is missing. } + "403": { description: not_admin. } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/company-profile: get: summary: The tenant's company profile (Unternehmensprofil), current revision. @@ -2914,6 +2998,39 @@ components: expires_at: { type: string, format: date-time, nullable: true } reason: { type: string, enum: [unknown_product, unknown_addon, tenant_not_found, tenant_archived, tenant_halted, entitlement_disabled, entitlement_expired, preview_expired, addon_not_purchased, not_entitled, member_blocked, user_unknown] } preview: { type: boolean, description: "allowed through a staff preview grant; usage under it is not invoiced" } + branding: + description: | + The workspace's branding (#155). Sent only when allowed is true + and there is a colour or a logo; a missing field means no frame, + no logo and no notice. + type: object + required: [color, logo_etag, notice] + properties: + color: { type: string, nullable: true, pattern: "^#[0-9a-f]{6}$", description: "the 6 px frame, exactly this colour" } + logo_etag: { type: string, nullable: true, description: "lowercase sha256 hex of the stored PNG (GET …/branding/logo)" } + notice: { type: boolean, description: "a derived branding not acknowledged yet; show only to IT_ADMIN and OWNER" } + domain: { type: string, description: "the domain it was derived from; only when notice is true" } + name: { type: string, description: "the workspace's display name" } + + Branding: + type: object + required: [tenant_id, color, logo_etag, manual, derive_state, notice, derive_enabled] + properties: + tenant_id: { type: string, format: uuid } + color: { type: string, nullable: true, pattern: "^#[0-9a-f]{6}$" } + logo_etag: { type: string, nullable: true } + manual: { type: boolean, description: "set by an admin; never derived over" } + domain: { type: string, description: "the domain of the last derivation" } + color_source: { type: string, enum: ["", theme-color, manifest, logo, manual] } + logo_source: { type: string, description: "URL of the derived logo; empty when uploaded or none" } + derived_at: { type: string, format: date-time, nullable: true } + derive_state: { type: string, enum: [none, pending, done, failed] } + derive_error: { type: string } + notice: { type: boolean } + notice_ack_at: { type: string, format: date-time, nullable: true } + updated_by: { type: string } + updated_at: { type: string, format: date-time, nullable: true } + derive_enabled: { type: boolean, description: "this registry may fetch the home page (BRANDING_DERIVE)" } ProductAddon: type: object -- 2.54.1 From d64fc342d16ca6bed399d510b5db4f29797294cf Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:15:28 +0100 Subject: [PATCH 2/4] test(migrations): expect the Monitor SKU after 0034 TestMigrate_productsSeedMatchesDefaults still expected the SKU list before 0034 (#152). CI does not run the migrations package, so it went unnoticed. Co-Authored-By: Claude Opus 5.5 --- migrations/migrations_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 3f4a956..607a043 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -627,7 +627,8 @@ func TestMigrate_productsSeedMatchesDefaults(t *testing.T) { if _, err := db.Exec(string(up)); err != nil { t.Fatal(err) } - if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN CRA-CSA-CLD-TGT CRA-CSA-CLD-DAY]" { + // 0034 (Monitor) is applied too. + if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN CRA-CSA-CLD-TGT CRA-CSA-CLD-DAY CRA-CSA-CLD-MON]" { t.Errorf("0026 twice: %v", skus) } if err := m.Migrate(25); err != nil { -- 2.54.1 From fb86a78324cf6e3ba049b428a8abfbee6f7f6174 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:14:32 +0100 Subject: [PATCH 3/4] feat(branding): derive colour and logo from the signup domain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Customer branding (#155), steps 1–6: the registry reads the home page of the workspace's company domain and stores its CI colour and logo. - Domain: the admin's address, else the most frequent member domain (tie: alphabetical); free mail never counts; no domain, no branding. - Fetch (internal/branding): own transport (no proxy, no trace headers, no cookies), https on 443 only, public IPs only, checked on every dial after DNS, ≤ 5 redirects within the registrable domain, 10 s per request, HTML ≤ 2 MB, images ≤ 1 MB, User-Agent BreakpilotBranding/1.0. - Colour: theme-color without media, the manifest's theme_color, else the logo's dominant colour; white, black and grey are skipped. - Logo: manifest PNG ≥ 128 px, apple-touch-icon, PNG/ICO/JPEG icon, /favicon.ico; stored as a 256×256 PNG, never SVG. - POST /v1/tenants/{id}/branding/derive ("Neu ermitteln"): synchronous, replaces a manual choice and counts as acknowledged. - Background: tenant creation and trial requests queue the workspace; RunBranding derives queued ones every minute, retries network failures twice, 6 h apart. Audit branding.derived / branding.failed. - Switches: BRANDING_DERIVE=on (off by default), BRANDING_BACKFILL=on queues every customer workspace without branding once at start. Co-Authored-By: Claude Opus 5.5 --- cmd/server/main.go | 2 + go.mod | 2 +- internal/branding/color.go | 140 +++++++++++ internal/branding/derive.go | 300 ++++++++++++++++++++++++ internal/branding/derive_test.go | 250 ++++++++++++++++++++ internal/branding/domain.go | 101 ++++++++ internal/branding/fetch.go | 221 +++++++++++++++++ internal/config/config.go | 4 + internal/server/branding_derive.go | 218 +++++++++++++++++ internal/server/branding_derive_test.go | 155 ++++++++++++ internal/server/catalog.go | 1 + internal/server/openapi_test.go | 1 + internal/server/server.go | 5 + internal/server/tenants.go | 2 + openapi.yaml | 20 ++ 15 files changed, 1421 insertions(+), 1 deletion(-) create mode 100644 internal/branding/color.go create mode 100644 internal/branding/derive.go create mode 100644 internal/branding/derive_test.go create mode 100644 internal/branding/domain.go create mode 100644 internal/branding/fetch.go create mode 100644 internal/server/branding_derive.go create mode 100644 internal/server/branding_derive_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 5cb66d0..9b68636 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -231,6 +231,8 @@ func main() { go app.RunMail(ctx, 20*time.Second) // Module users (t81): once per Europe/Berlin day. go app.RunModuleUserCount(ctx, 15*time.Minute) + // Customer branding (#155): queued workspaces, when BRANDING_DERIVE=on. + go app.RunBranding(ctx, time.Minute) go func() { slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", kind) diff --git a/go.mod b/go.mod index 026abc9..68cada2 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( go.opentelemetry.io/otel/trace v1.47.0 golang.org/x/crypto v0.58.0 golang.org/x/image v0.48.0 + golang.org/x/net v0.62.0 ) require ( @@ -88,7 +89,6 @@ require ( go.opentelemetry.io/otel/metric v1.47.0 // indirect go.opentelemetry.io/proto/otlp v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect diff --git a/internal/branding/color.go b/internal/branding/color.go new file mode 100644 index 0000000..2639fd4 --- /dev/null +++ b/internal/branding/color.go @@ -0,0 +1,140 @@ +package branding + +import ( + "fmt" + "image" + "image/color" + "image/draw" + "math" + "strconv" + "strings" + + xdraw "golang.org/x/image/draw" +) + +// Bounds a usable brand colour lies within (#155): anything less saturated, +// darker or lighter reads as white, black or grey and is skipped. +const ( + minSaturation = 0.25 + minLightness = 0.12 + maxLightness = 0.92 +) + +// usable reports whether an opaque colour is a brand colour, not white, +// black or grey. +func usable(r, g, b uint8) bool { + s, l := satLight(r, g, b) + return s >= minSaturation && l >= minLightness && l <= maxLightness +} + +// satLight is HSL saturation and lightness in [0, 1]. +func satLight(r, g, b uint8) (s, l float64) { + rf, gf, bf := float64(r)/255, float64(g)/255, float64(b)/255 + hi, lo := math.Max(rf, math.Max(gf, bf)), math.Min(rf, math.Min(gf, bf)) + l = (hi + lo) / 2 + if hi == lo { + return 0, l + } + return (hi - lo) / (1 - math.Abs(2*l-1)), l +} + +func hexColor(r, g, b uint8) string { return fmt.Sprintf("#%02x%02x%02x", r, g, b) } + +// parseCSSColor reads the colour forms sites put in theme-color and +// theme_color: #rgb, #rgba, #rrggbb, #rrggbbaa and rgb()/rgba(). Alpha is +// ignored. Named colours and other functions are not read (ok=false). +func parseCSSColor(v string) (r, g, b uint8, ok bool) { + v = strings.ToLower(strings.TrimSpace(v)) + if strings.HasPrefix(v, "#") { + h := v[1:] + switch len(h) { + case 3, 4: + h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]}) + case 6, 8: + h = h[:6] + default: + return 0, 0, 0, false + } + n, err := strconv.ParseUint(h, 16, 32) + if err != nil { + return 0, 0, 0, false + } + return uint8(n >> 16), uint8(n >> 8), uint8(n), true + } + inner, found := strings.CutPrefix(v, "rgba(") + if !found { + inner, found = strings.CutPrefix(v, "rgb(") + } + if !found || !strings.HasSuffix(inner, ")") { + return 0, 0, 0, false + } + inner = strings.TrimSuffix(inner, ")") + if i := strings.Index(inner, "/"); i >= 0 { + inner = inner[:i] // "rgb(1 2 3 / 50%)" + } + parts := strings.FieldsFunc(inner, func(c rune) bool { return c == ',' || c == ' ' }) + if len(parts) != 3 && len(parts) != 4 { + return 0, 0, 0, false + } + var ch [3]uint8 + for i := 0; i < 3; i++ { + p := parts[i] + pct := strings.HasSuffix(p, "%") + f, err := strconv.ParseFloat(strings.TrimSuffix(p, "%"), 64) + if err != nil || math.IsNaN(f) { + return 0, 0, 0, false + } + if pct { + f = f * 255 / 100 + } + ch[i] = uint8(math.Round(math.Max(0, math.Min(255, f)))) + } + return ch[0], ch[1], ch[2], true +} + +// CSSBrandColor returns a usable theme colour as "#rrggbb", or "". +func CSSBrandColor(v string) string { + r, g, b, ok := parseCSSColor(v) + if !ok || !usable(r, g, b) { + return "" + } + return hexColor(r, g, b) +} + +// DominantColor is the logo's brand colour (#155 step 3): scaled to 64×64, +// pixels that are transparent (alpha < 128), white, black or grey dropped, +// the rest quantised to 5 bits per channel; the most frequent bucket wins +// (a tie goes to the lowest packed value) and the colour is the rounded +// mean of its pixels. "" when no pixel is left. +func DominantColor(img image.Image) string { + small := image.NewNRGBA(image.Rect(0, 0, 64, 64)) + xdraw.CatmullRom.Scale(small, small.Bounds(), img, img.Bounds(), draw.Src, nil) + type acc struct{ n, r, g, b int } + var buckets [1 << 15]acc + for y := 0; y < 64; y++ { + for x := 0; x < 64; x++ { + c := color.NRGBAModel.Convert(small.At(x, y)).(color.NRGBA) + if c.A < 128 || !usable(c.R, c.G, c.B) { + continue + } + k := int(c.R>>3)<<10 | int(c.G>>3)<<5 | int(c.B>>3) + a := &buckets[k] + a.n++ + a.r += int(c.R) + a.g += int(c.G) + a.b += int(c.B) + } + } + best := -1 + for k := range buckets { + if buckets[k].n > 0 && (best < 0 || buckets[k].n > buckets[best].n) { + best = k // ascending k: a tie keeps the lower packed value + } + } + if best < 0 { + return "" + } + a := buckets[best] + mean := func(sum int) uint8 { return uint8((sum + a.n/2) / a.n) } + return hexColor(mean(a.r), mean(a.g), mean(a.b)) +} diff --git a/internal/branding/derive.go b/internal/branding/derive.go new file mode 100644 index 0000000..c8af056 --- /dev/null +++ b/internal/branding/derive.go @@ -0,0 +1,300 @@ +package branding + +import ( + "bytes" + "context" + "encoding/json" + "net/url" + "path" + "sort" + "strconv" + "strings" + + "golang.org/x/net/html" +) + +// Result is one derivation. Color and Logo may both be empty: the page was +// read but has neither (the product then looks as today). +type Result struct { + Domain string + Color string // "#rrggbb" or "" + ColorSource string // theme-color | manifest | logo | "" + Logo []byte // 256×256 PNG or nil + LogoETag string + LogoSource string // URL the logo came from + LogoSHA256 string // of the fetched bytes + HTMLSHA256 string +} + +// page is what the home page declares. +type page struct { + themeColors []themeColor + manifest string + icons []iconRef // rel=icon / shortcut icon + apple []iconRef // rel=apple-touch-icon +} + +type themeColor struct { + content string + hasMedia bool +} + +type iconRef struct { + href string + size int // largest edge in sizes, 0 when unknown + typ string + order int +} + +// Derive reads domain's home page and returns its branding. The same +// fetched bytes always give the same result. +func (f *Fetcher) Derive(ctx context.Context, domain string) (*Result, error) { + domain = RegistrableDomain(domain) + if domain == "" { + return nil, ErrOffDomain + } + home, err := f.home(ctx, domain) + if err != nil { + return nil, err + } + res := &Result{Domain: domain, HTMLSHA256: sha256Hex(home.body)} + pg := parsePage(home.body) + + var man *manifest + if pg.manifest != "" { + if u, err := home.url.Parse(pg.manifest); err == nil { + if m, err := f.get(ctx, u, domain, MaxImageBytes, "application/manifest+json,application/json"); err == nil { + man = parseManifest(m.body, m.url) + } + } + } + + // Colour 1 and 2: the first theme-color without a media query, then + // the manifest's theme_color; white, black and grey are skipped. + for _, tc := range pg.themeColors { + if !tc.hasMedia { + if c := CSSBrandColor(tc.content); c != "" { + res.Color, res.ColorSource = c, "theme-color" + } + break + } + } + if res.Color == "" && man != nil { + if c := CSSBrandColor(man.themeColor); c != "" { + res.Color, res.ColorSource = c, "manifest" + } + } + + // The logo: the first candidate that can be fetched and decoded. + for _, u := range logoCandidates(pg, man, home.url) { + img, err := f.get(ctx, u, domain, MaxImageBytes+1, "image/png,image/x-icon,image/jpeg;q=0.9,image/*;q=0.5") + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + continue + } + png, etag, err := NormalizeLogo(img.body) + if err != nil { + continue // SVG, too large or not an image: the next candidate + } + res.Logo, res.LogoETag, res.LogoSource, res.LogoSHA256 = png, etag, img.url.String(), sha256Hex(img.body) + break + } + // Colour 3: the logo's dominant brand colour. + if res.Color == "" && res.Logo != nil { + if img, err := DecodeImage(res.Logo); err == nil { + if c := DominantColor(img); c != "" { + res.Color, res.ColorSource = c, "logo" + } + } + } + return res, nil +} + +// logoCandidates in the order of #155 step 4: the manifest's largest PNG +// icon of at least 128 px, apple-touch-icon, the largest PNG/ICO/JPEG +// rel=icon, /favicon.ico. Within a step, larger first. +func logoCandidates(pg page, man *manifest, base *url.URL) []*url.URL { + var out []*url.URL + seen := map[string]bool{} + add := func(refBase *url.URL, refs []iconRef) { + sort.SliceStable(refs, func(i, j int) bool { + if refs[i].size != refs[j].size { + return refs[i].size > refs[j].size + } + return refs[i].order < refs[j].order + }) + for _, r := range refs { + u, err := refBase.Parse(strings.TrimSpace(r.href)) + if err != nil || seen[u.String()] { + continue + } + seen[u.String()] = true + out = append(out, u) + } + } + if man != nil { + var pngs []iconRef + for _, ic := range man.icons { + if ic.size >= 128 && isType(ic, "png") { + pngs = append(pngs, ic) + } + } + add(man.url, pngs) + } + add(base, slicesClone(pg.apple)) + var icons []iconRef + for _, ic := range pg.icons { + if isType(ic, "png") || isType(ic, "ico") || isType(ic, "jpeg") { + icons = append(icons, ic) + } + } + add(base, icons) + add(base, []iconRef{{href: "/favicon.ico"}}) + return out +} + +func slicesClone(in []iconRef) []iconRef { return append([]iconRef(nil), in...) } + +// isType matches an icon by its type attribute, else by its file +// extension. +func isType(ic iconRef, kind string) bool { + t := strings.ToLower(strings.TrimSpace(ic.typ)) + if t != "" { + switch kind { + case "png": + return t == "image/png" + case "ico": + return t == "image/x-icon" || t == "image/vnd.microsoft.icon" || t == "image/ico" + case "jpeg": + return t == "image/jpeg" || t == "image/jpg" + } + return false + } + p := strings.ToLower(ic.href) + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + switch ext := path.Ext(p); kind { + case "png": + return ext == ".png" + case "ico": + return ext == ".ico" + case "jpeg": + return ext == ".jpg" || ext == ".jpeg" + } + return false +} + +// parsePage collects theme-color, the manifest link and icon links. +func parsePage(body []byte) page { + var pg page + z := html.NewTokenizer(bytes.NewReader(body)) + order := 0 + for { + tt := z.Next() + if tt == html.ErrorToken { + return pg + } + if tt != html.StartTagToken && tt != html.SelfClosingTagToken { + continue + } + name, hasAttr := z.TagName() + if !hasAttr { + continue + } + attrs := map[string]string{} + for { + k, v, more := z.TagAttr() + key := strings.ToLower(string(k)) + if _, dup := attrs[key]; !dup { + attrs[key] = string(v) + } + if !more { + break + } + } + switch string(name) { + case "meta": + if strings.EqualFold(strings.TrimSpace(attrs["name"]), "theme-color") { + _, media := attrs["media"] + pg.themeColors = append(pg.themeColors, themeColor{content: attrs["content"], hasMedia: media && strings.TrimSpace(attrs["media"]) != ""}) + } + case "link": + href := strings.TrimSpace(attrs["href"]) + if href == "" { + continue + } + rels := strings.Fields(strings.ToLower(attrs["rel"])) + ref := iconRef{href: href, size: largestSize(attrs["sizes"]), typ: attrs["type"], order: order} + order++ + switch { + case contains(rels, "manifest"): + if pg.manifest == "" { + pg.manifest = href + } + case contains(rels, "apple-touch-icon"), contains(rels, "apple-touch-icon-precomposed"): + pg.apple = append(pg.apple, ref) + case contains(rels, "icon"): + pg.icons = append(pg.icons, ref) + } + } + } +} + +func contains(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +// largestSize reads sizes="16x16 32x32" as its largest edge; "any" and +// unreadable values count 0. +func largestSize(sizes string) int { + best := 0 + for _, s := range strings.Fields(strings.ToLower(sizes)) { + w, h, ok := strings.Cut(s, "x") + if !ok { + continue + } + wi, err1 := strconv.Atoi(w) + hi, err2 := strconv.Atoi(h) + if err1 != nil || err2 != nil { + continue + } + best = max(best, min(wi, hi)) + } + return best +} + +type manifest struct { + themeColor string + icons []iconRef + url *url.URL +} + +func parseManifest(body []byte, u *url.URL) *manifest { + var raw struct { + ThemeColor string `json:"theme_color"` + Icons []struct { + Src string `json:"src"` + Sizes string `json:"sizes"` + Type string `json:"type"` + } `json:"icons"` + } + if json.Unmarshal(body, &raw) != nil { + return nil + } + m := &manifest{themeColor: raw.ThemeColor, url: u} + for i, ic := range raw.Icons { + if strings.TrimSpace(ic.Src) == "" { + continue + } + m.icons = append(m.icons, iconRef{href: ic.Src, size: largestSize(ic.Sizes), typ: ic.Type, order: i}) + } + return m +} diff --git a/internal/branding/derive_test.go b/internal/branding/derive_test.go new file mode 100644 index 0000000..1a62e8b --- /dev/null +++ b/internal/branding/derive_test.go @@ -0,0 +1,250 @@ +package branding + +import ( + "context" + "crypto/tls" + "errors" + "image" + "image/color" + "net/http" + "net/http/httptest" + "net/netip" + "strings" + "sync/atomic" + "testing" +) + +// site serves pages by host and path; every connection lands on it. +type site struct { + srv *httptest.Server + pages map[string]func(w http.ResponseWriter, r *http.Request) + hits atomic.Int32 +} + +func newSite(t *testing.T) *site { + t.Helper() + s := &site{pages: map[string]func(http.ResponseWriter, *http.Request){}} + s.srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.hits.Add(1) + if r.Header.Get("User-Agent") != UserAgent || r.Header.Get("Cookie") != "" { + http.Error(w, "bad client", 400) + return + } + if h, ok := s.pages[r.Host+r.URL.Path]; ok { + h(w, r) + return + } + http.NotFound(w, r) + })) + t.Cleanup(s.srv.Close) + return s +} + +func (s *site) html(key, body string) { + s.pages[key] = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte(body)) + } +} + +func (s *site) bytes(key, ctype string, body []byte) { + s.pages[key] = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", ctype) + _, _ = w.Write(body) + } +} + +func (s *site) fetcher(allowLoopback bool) *Fetcher { + cfg := FetchConfig{DialAddr: s.srv.Listener.Addr().String(), TLS: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec // test server + if allowLoopback { + cfg.AllowIP = func(a netip.Addr) bool { return a.IsLoopback() } + } + return NewFetcher(cfg) +} + +func icoOf(t *testing.T, c color.NRGBA) []byte { + return ico(32, 32, 32, encodePNG(t, solid(32, 32, c))) +} + +func TestDerive(t *testing.T) { + ctx := context.Background() + blue := color.NRGBA{R: 0x1a, G: 0x5f, B: 0xb4, A: 255} + + t.Run("theme-color and apple-touch-icon", func(t *testing.T) { + s := newSite(t) + s.html("example.com/", ` + + + + + Hello`) + s.bytes("example.com/apple.png", "image/png", encodePNG(t, solid(180, 180, blue))) + s.bytes("example.com/fav.png", "image/png", encodePNG(t, solid(32, 32, blue))) + res, err := s.fetcher(true).Derive(ctx, "example.com") + if err != nil { + t.Fatal(err) + } + if res.Color != "#1a5fb4" || res.ColorSource != "theme-color" || res.Domain != "example.com" { + t.Fatalf("colour: %+v", res) + } + if res.Logo == nil || !strings.HasSuffix(res.LogoSource, "/apple.png") || len(res.HTMLSHA256) != 64 || len(res.LogoSHA256) != 64 { + t.Fatalf("logo: %+v", res) + } + again, _ := s.fetcher(true).Derive(ctx, "example.com") + if again.LogoETag != res.LogoETag || again.Color != res.Color || again.HTMLSHA256 != res.HTMLSHA256 { + t.Fatal("not deterministic") + } + }) + + t.Run("grey theme-color, manifest colour and icon, www fallback", func(t *testing.T) { + s := newSite(t) + // example.com/ is a 404: the www host serves the page. + s.html("www.example.com/", ` + `) + s.bytes("www.example.com/site.webmanifest", "application/manifest+json", []byte(`{ + "theme_color": "rgb(10, 125, 62)", + "icons": [{"src": "/i-96.png", "sizes": "96x96", "type": "image/png"}, + {"src": "/i-512.png", "sizes": "512x512", "type": "image/png"}, + {"src": "/i.svg", "sizes": "any", "type": "image/svg+xml"}]}`)) + s.bytes("www.example.com/i-512.png", "image/png", encodePNG(t, solid(512, 512, blue))) + res, err := s.fetcher(true).Derive(ctx, "example.com") + if err != nil { + t.Fatal(err) + } + if res.Color != "#0a7d3e" || res.ColorSource != "manifest" || !strings.HasSuffix(res.LogoSource, "/i-512.png") { + t.Fatalf("%+v", res) + } + }) + + t.Run("colour from the favicon", func(t *testing.T) { + s := newSite(t) + s.html("example.com/", `No hints`) + s.bytes("example.com/favicon.ico", "image/x-icon", icoOf(t, color.NRGBA{R: 200, G: 20, B: 30, A: 255})) + res, err := s.fetcher(true).Derive(ctx, "example.com") + if err != nil { + t.Fatal(err) + } + if res.ColorSource != "logo" || res.Color != "#c8141e" || !strings.HasSuffix(res.LogoSource, "/favicon.ico") { + t.Fatalf("%+v", res) + } + }) + + t.Run("SVG only: no logo, no colour", func(t *testing.T) { + s := newSite(t) + s.html("example.com/", ``) + s.bytes("example.com/favicon.ico", "image/svg+xml", []byte(``)) + res, err := s.fetcher(true).Derive(ctx, "example.com") + if err != nil { + t.Fatal(err) + } + if res.Logo != nil || res.Color != "" { + t.Fatalf("%+v", res) + } + }) + + t.Run("a redirect off the domain is refused", func(t *testing.T) { + s := newSite(t) + s.pages["example.com/"] = func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "https://evil.test/", http.StatusFound) + } + s.pages["www.example.com/"] = s.pages["example.com/"] + if _, err := s.fetcher(true).Derive(ctx, "example.com"); !errors.Is(err, ErrOffDomain) { + t.Fatalf("err = %v", err) + } + }) + + t.Run("too many redirects", func(t *testing.T) { + s := newSite(t) + s.pages["example.com/"] = func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "https://example.com/", http.StatusFound) + } + s.pages["www.example.com/"] = s.pages["example.com/"] + _, err := s.fetcher(true).Derive(ctx, "example.com") + if err == nil || ReasonOf(err) != "redirects" { + t.Fatalf("err = %v (%s)", err, ReasonOf(err)) + } + }) + + t.Run("private addresses are never dialled", func(t *testing.T) { + s := newSite(t) + s.html("example.com/", ``) + _, err := s.fetcher(false).Derive(ctx, "example.com") + if !errors.Is(err, ErrBlockedAddress) || ReasonOf(err) != "blocked_address" { + t.Fatalf("err = %v", err) + } + if s.hits.Load() != 0 { + t.Fatalf("the server was reached %d times", s.hits.Load()) + } + }) + + t.Run("no registrable domain", func(t *testing.T) { + if _, err := NewFetcher(FetchConfig{}).Derive(ctx, "localhost"); !errors.Is(err, ErrOffDomain) { + t.Fatalf("err = %v", err) + } + }) +} + +func TestPublicIP(t *testing.T) { + for addr, want := range map[string]bool{ + "8.8.8.8": true, "2a00:1450:4001:80b::200e": true, + "10.0.0.1": false, "172.16.5.4": false, "192.168.1.1": false, "127.0.0.1": false, + "169.254.169.254": false, "100.64.0.1": false, "0.0.0.0": false, "::1": false, + "fe80::1": false, "fd00::1": false, "64:ff9b::a00:1": false, "224.0.0.1": false, + } { + if got := PublicIP(netip.MustParseAddr(addr)); got != want { + t.Errorf("%s: %v", addr, got) + } + } +} + +func TestPickDomain(t *testing.T) { + cases := []struct { + admin string + members []string + want string + }{ + {"it@Firma.de", nil, "firma.de"}, + {"it@mail.firma.co.uk", nil, "firma.co.uk"}, + {"chef@gmail.com", []string{"a@b-firma.de", "b@a-firma.de", "c@a-firma.de", "d@web.de"}, "a-firma.de"}, + {"", []string{"a@b-firma.de", "b@a-firma.de"}, "a-firma.de"}, // tie: alphabetical + {"x@outlook.de", []string{"y@yahoo.co.uk", "z@gmx.net"}, ""}, + {"not an address", nil, ""}, + } + for _, c := range cases { + if got := PickDomain(c.admin, c.members); got != c.want { + t.Errorf("PickDomain(%q, %v) = %q, want %q", c.admin, c.members, got, c.want) + } + } + if RegistrableDomain("user.github.io") != "" { + t.Error("a private suffix counted as a company domain") + } +} + +func TestColours(t *testing.T) { + for in, want := range map[string]string{ + "#1A5FB4": "#1a5fb4", "#c00": "#cc0000", "#1a5fb4cc": "#1a5fb4", "rgb(10,125,62)": "#0a7d3e", + "rgba(10, 125, 62, 0.5)": "#0a7d3e", "rgb(4% 49% 24% / 1)": "#0a7d3d", + "#ffffff": "", "#000": "", "#808080": "", "red": "", "hsl(0,100%,50%)": "", "#12": "", + } { + if got := CSSBrandColor(in); got != want { + t.Errorf("CSSBrandColor(%q) = %q, want %q", in, got, want) + } + } + // Two equal halves: the tie goes to the lower packed value (the blue). + img := image.NewNRGBA(image.Rect(0, 0, 64, 64)) + for y := 0; y < 64; y++ { + for x := 0; x < 64; x++ { + c := color.NRGBA{R: 0x1a, G: 0x5f, B: 0xb4, A: 255} + if x >= 32 { + c = color.NRGBA{R: 0xc8, G: 0x14, B: 0x1e, A: 255} + } + img.SetNRGBA(x, y, c) + } + } + if got := DominantColor(img); got != "#1a5fb4" { + t.Errorf("tie: %s", got) + } + if got := DominantColor(solid(8, 8, color.NRGBA{R: 250, G: 250, B: 250, A: 255})); got != "" { + t.Errorf("white logo: %s", got) + } +} diff --git a/internal/branding/domain.go b/internal/branding/domain.go new file mode 100644 index 0000000..5687187 --- /dev/null +++ b/internal/branding/domain.go @@ -0,0 +1,101 @@ +package branding + +import ( + "net/mail" + "sort" + "strings" + + "golang.org/x/net/publicsuffix" +) + +// freeMailExact and freeMailLabel are the free-mail providers (#155): an +// address there says nothing about the company. A label matches the +// provider under any public suffix (outlook.de, yahoo.co.uk, …). +var ( + freeMailExact = map[string]bool{ + "gmail.com": true, "googlemail.com": true, "web.de": true, "t-online.de": true, + "icloud.com": true, "me.com": true, "mac.com": true, "mail.de": true, "posteo.de": true, + "posteo.net": true, "mailbox.org": true, "proton.me": true, "pm.me": true, "freenet.de": true, + "arcor.de": true, "online.de": true, "email.de": true, "vodafone.de": true, "1und1.de": true, + "mail.ru": true, "zoho.com": true, "tutanota.com": true, "tutanota.de": true, "tuta.io": true, + "tuta.com": true, "fastmail.com": true, "hey.com": true, "qq.com": true, "163.com": true, + "126.com": true, "rocketmail.com": true, "ymail.com": true, "msn.com": true, "bluewin.ch": true, + "gmx.com": true, "gmx.de": true, "gmx.net": true, "gmx.at": true, "gmx.ch": true, + } + freeMailLabel = map[string]bool{ + "outlook": true, "hotmail": true, "live": true, "yahoo": true, "protonmail": true, + "aol": true, "gmx": true, "yandex": true, + } +) + +// RegistrableDomain is host's eTLD+1, lowercase, or "" when host has none. +func RegistrableDomain(host string) string { + host = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(host)), ".") + if host == "" || strings.ContainsAny(host, "/:@ ") { + return "" + } + d, err := publicsuffix.EffectiveTLDPlusOne(host) + if err != nil { + return "" + } + if _, icann := publicsuffix.PublicSuffix(host); !icann { + return "" // a private suffix (github.io, …) is not a company domain + } + return d +} + +// IsFreeMail reports whether domain is a free-mail provider. +func IsFreeMail(domain string) bool { + d := RegistrableDomain(domain) + if d == "" { + return false + } + if freeMailExact[d] { + return true + } + label, _, _ := strings.Cut(d, ".") + return freeMailLabel[label] +} + +// EmailDomain is the registrable domain of an address, or "". +func EmailDomain(email string) string { + addr, err := mail.ParseAddress(strings.TrimSpace(email)) + if err != nil { + return "" + } + _, host, ok := strings.Cut(addr.Address, "@") + if !ok { + return "" + } + return RegistrableDomain(host) +} + +// PickDomain chooses the domain to derive from (#155 step 1): the admin +// address's domain unless it is empty or free mail; else the most frequent +// company domain among the members (a tie goes to the alphabetically +// first); "" when there is none. +func PickDomain(adminEmail string, memberEmails []string) string { + if d := EmailDomain(adminEmail); d != "" && !IsFreeMail(d) { + return d + } + counts := map[string]int{} + for _, e := range memberEmails { + if d := EmailDomain(e); d != "" && !IsFreeMail(d) { + counts[d]++ + } + } + domains := make([]string, 0, len(counts)) + for d := range counts { + domains = append(domains, d) + } + sort.Slice(domains, func(i, j int) bool { + if counts[domains[i]] != counts[domains[j]] { + return counts[domains[i]] > counts[domains[j]] + } + return domains[i] < domains[j] + }) + if len(domains) == 0 { + return "" + } + return domains[0] +} diff --git a/internal/branding/fetch.go b/internal/branding/fetch.go new file mode 100644 index 0000000..39620ec --- /dev/null +++ b/internal/branding/fetch.go @@ -0,0 +1,221 @@ +package branding + +import ( + "context" + "crypto/sha256" + "crypto/tls" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "syscall" + "time" +) + +// Fetch rules (#155 step 2): https only on port 443, home page only, no +// JavaScript, no cookies, at most 5 redirects and only within the same +// registrable domain, only public IP addresses (checked on every dial, so +// on every hop and after DNS), 10 s per request, HTML ≤ 2 MB, images and +// the manifest ≤ 1 MB, a neutral User-Agent and nothing about the customer. +const ( + UserAgent = "BreakpilotBranding/1.0" + maxHTMLBytes = 2 << 20 + maxRedirects = 5 + requestTimeout = 10 * time.Second + responseHeaders = 64 << 10 +) + +var ( + ErrBlockedAddress = errors.New("address is not public") + ErrOffDomain = errors.New("URL leaves the domain") + ErrNotHTTPS = errors.New("only https on port 443") + ErrHTTPStatus = errors.New("unexpected HTTP status") +) + +// FetchConfig: the zero value is production. Tests point every connection +// at their own TLS server (DialAddr, TLS) and allow its loopback address. +type FetchConfig struct { + DialAddr string + TLS *tls.Config + AllowIP func(netip.Addr) bool +} + +// Fetcher reads public web pages under the rules above. It has its own +// transport: never the process default, which carries trace headers. +type Fetcher struct { + client *http.Client +} + +func NewFetcher(cfg FetchConfig) *Fetcher { + allow := cfg.AllowIP + if allow == nil { + allow = PublicIP + } + dialer := &net.Dialer{ + Timeout: 5 * time.Second, + // Control sees the address actually dialled, after DNS: a name that + // resolves to a private address is refused on every hop. + Control: func(_, address string, _ syscall.RawConn) error { + ap, err := netip.ParseAddrPort(address) + if err != nil || !allow(ap.Addr().Unmap()) { + return ErrBlockedAddress + } + return nil + }, + } + tr := &http.Transport{ + Proxy: nil, + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + if cfg.DialAddr != "" { + addr = cfg.DialAddr + } + return dialer.DialContext(ctx, network, addr) + }, + TLSClientConfig: cfg.TLS, + TLSHandshakeTimeout: 5 * time.Second, + ResponseHeaderTimeout: requestTimeout, + MaxResponseHeaderBytes: responseHeaders, + DisableKeepAlives: true, + ForceAttemptHTTP2: true, + } + return &Fetcher{client: &http.Client{ + Transport: tr, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) > maxRedirects { + return fmt.Errorf("more than %d redirects", maxRedirects) + } + return checkURL(req.URL, RegistrableDomain(via[0].URL.Hostname())) + }, + }} +} + +// PublicIP: a global unicast address outside every private, shared, +// loopback, link-local, documentation and translation range. +func PublicIP(a netip.Addr) bool { + if !a.IsValid() || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() || a.IsLinkLocalUnicast() { + return false + } + for _, p := range blockedPrefixes { + if p.Contains(a) { + return false + } + } + return true +} + +var blockedPrefixes = func() []netip.Prefix { + var out []netip.Prefix + for _, s := range []string{ + "0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", + "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", + "64:ff9b::/96", "64:ff9b:1::/48", "100::/64", "2001::/32", "2001:db8::/32", "2002::/16", "fc00::/7", + } { + out = append(out, netip.MustParsePrefix(s)) + } + return out +}() + +// checkURL: https on port 443 and, when domain is set, within it. +func checkURL(u *url.URL, domain string) error { + if u.Scheme != "https" || (u.Port() != "" && u.Port() != "443") || u.User != nil { + return ErrNotHTTPS + } + if domain != "" && RegistrableDomain(u.Hostname()) != domain { + return ErrOffDomain + } + return nil +} + +// fetched is one response body with the URL it came from after redirects. +type fetched struct { + body []byte + url *url.URL +} + +// get fetches u (within domain) and reads at most limit bytes; a longer +// body is cut there. +func (f *Fetcher) get(ctx context.Context, u *url.URL, domain string, limit int64, accept string) (*fetched, error) { + if err := checkURL(u, domain); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", UserAgent) + req.Header.Set("Accept", accept) + resp, err := f.client.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%w %d", ErrHTTPStatus, resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, limit)) + if err != nil { + return nil, err + } + return &fetched{body: body, url: resp.Request.URL}, nil +} + +func sha256Hex(b []byte) string { + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} + +// home fetches https:///, else https://www./. +func (f *Fetcher) home(ctx context.Context, domain string) (*fetched, error) { + var first error + for _, host := range []string{domain, "www." + domain} { + page, err := f.get(ctx, &url.URL{Scheme: "https", Host: host, Path: "/"}, domain, maxHTMLBytes, + "text/html,application/xhtml+xml;q=0.9") + if err == nil { + return page, nil + } + if first == nil { + first = err + } + if ctx.Err() != nil { + break + } + } + return nil, first +} + +// ReasonOf is a short, content-free reason for an audit row. +func ReasonOf(err error) string { + var dnsErr *net.DNSError + switch { + case err == nil: + return "" + case errors.Is(err, ErrBlockedAddress): + return "blocked_address" + case errors.Is(err, ErrOffDomain): + return "off_domain" + case errors.Is(err, ErrHTTPStatus): + return "http_" + strings.TrimPrefix(err.Error(), ErrHTTPStatus.Error()+" ") + case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled): + return "timeout" + case errors.As(err, &dnsErr): + return "dns" + } + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + return "timeout" + } + if strings.Contains(err.Error(), "tls") || strings.Contains(err.Error(), "x509") { + return "tls" + } + if strings.Contains(err.Error(), "redirects") { + return "redirects" + } + return "fetch_failed" +} diff --git a/internal/config/config.go b/internal/config/config.go index 8c5a007..201400a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -118,6 +118,9 @@ type Config struct { // page of a workspace's signup domain to derive its colour and logo // (#155). Off by default: the privacy notice has to name the fetch first. BrandingDerive bool + // BrandingBackfill (BRANDING_BACKFILL=on, with BRANDING_DERIVE) queues + // every customer workspace without branding once at start. + BrandingBackfill bool // SMTPTLS is how the relay connection is secured: "starttls", "tls" // (implicit, port 465) or "none" (a plain internal relay; no AUTH then). @@ -234,6 +237,7 @@ func Load() (*Config, error) { PruefwerkPlatformURL: os.Getenv("PRUEFWERK_PLATFORM_URL"), PruefwerkURL: os.Getenv("PRUEFWERK_URL"), BrandingDerive: getenv("BRANDING_DERIVE", "off") == "on", + BrandingBackfill: getenv("BRANDING_BACKFILL", "off") == "on", LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"), LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"), diff --git a/internal/server/branding_derive.go b/internal/server/branding_derive.go new file mode 100644 index 0000000..5782151 --- /dev/null +++ b/internal/server/branding_derive.go @@ -0,0 +1,218 @@ +package server + +import ( + "context" + "errors" + "net/http" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/branding" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Deriving a workspace's branding from the home page of its signup domain +// (#155 steps 1–6). Only with BRANDING_DERIVE=on: the fetch reads a page +// the customer named by signing up, so the privacy notice names it first. +// +// POST /v1/tenants/{id}/branding/derive (tenants.write) "Neu ermitteln" +// +// New workspaces (tenant creation, trial request) are queued and derived in +// the background; signup never waits. BRANDING_BACKFILL=on queues every +// customer workspace without branding once at start. + +// deriveBudget bounds one derivation: the home page, the manifest and a few +// logo candidates at 10 s each, under the server's 30 s write timeout. +const deriveBudget = 25 * time.Second + +// brandingRetries: a derivation that failed on the network is tried again +// this many times in the background, brandingRetryAfter apart. +const ( + brandingRetries = 3 + brandingRetryAfter = 6 * time.Hour +) + +var errNoDomain = errors.New("no company domain") + +func (s *Server) brandingFetcher() *branding.Fetcher { + if s.BrandingFetcher != nil { + return s.BrandingFetcher + } + return branding.NewFetcher(branding.FetchConfig{}) +} + +// enqueueBranding queues a new customer workspace for the background +// derivation. Best effort: a failure only means no branding yet. +func (s *Server) enqueueBranding(ctx context.Context, t *store.Tenant) { + if !s.brandingDeriveEnabled() || t == nil || t.Kind != "customer" || t.Status == store.StatusDemo || t.Status == store.StatusArchived { + return + } + if _, err := s.Store.EnqueueBranding(ctx, t.ID, s.now()); err != nil { + s.Log.Warn("branding enqueue failed", "tenant_id", t.ID, "err", err) + } +} + +// brandingDomain is the domain to derive from (#155 step 1). +func (s *Server) brandingDomain(ctx context.Context, t *store.Tenant) (string, error) { + if d := branding.EmailDomain(t.AdminEmail); d != "" && !branding.IsFreeMail(d) { + return d, nil + } + members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) + if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) { + return "", err + } + emails := make([]string, 0, len(members)) + for _, m := range members { + emails = append(emails, m.Email) + } + if d := branding.PickDomain(t.AdminEmail, emails); d != "" { + return d, nil + } + return "", errNoDomain +} + +// deriveBranding runs one derivation for t and records it. force: an admin +// asked ("Neu ermitteln"); it replaces a manual choice and counts as +// acknowledged. r is nil in the background. +func (s *Server) deriveBranding(ctx context.Context, r *http.Request, t *store.Tenant, force bool, by string) error { + ctx, cancel := context.WithTimeout(ctx, deriveBudget) + defer cancel() + domain, err := s.brandingDomain(ctx, t) + var res *branding.Result + if err == nil { + res, err = s.brandingFetcher().Derive(ctx, domain) + } + if err != nil { + reason := branding.ReasonOf(err) + final := force || errors.Is(err, errNoDomain) + if errors.Is(err, errNoDomain) { + reason = "no_domain" + } + var next *time.Time + if cur, gerr := s.Store.GetTenantBranding(ctx, t.ID); !final && (gerr != nil || cur.DeriveAttempts+1 < brandingRetries) { + n := s.now().Add(brandingRetryAfter) + next = &n + } + if ferr := s.Store.FailBranding(context.WithoutCancel(ctx), t.ID, reason, next, s.now()); ferr != nil { + s.Log.Warn("branding: recording the failure failed", "tenant_id", t.ID, "err", ferr) + } + s.Log.Info("branding derivation failed", "tenant_id", t.ID, "reason", reason, "retry", next != nil) + s.emitAudit(context.WithoutCancel(ctx), r, store.AuditEvent{ + TenantID: t.ID, Action: "branding.failed", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", + ActorType: brandingActorType(r, s), ActorName: by, + Metadata: map[string]interface{}{"domain": domain, "reason": reason, "retry": next != nil}, + }) + return err + } + d := store.DerivedBranding{ + TenantID: t.ID, Logo: res.Logo, LogoETag: res.LogoETag, Domain: res.Domain, + ColorSource: res.ColorSource, LogoSource: res.LogoSource, HTMLSHA256: res.HTMLSHA256, LogoSHA256: res.LogoSHA256, + At: s.now(), Force: force, By: by, + } + if res.Color != "" { + c := res.Color + d.Color = &c + } + applied, err := s.Store.SaveDerivedBranding(context.WithoutCancel(ctx), d) + if err != nil { + return err + } + if !applied { + return nil // an admin set it by hand meanwhile + } + s.Log.Info("branding derived", "tenant_id", t.ID, "color_source", res.ColorSource, "logo", res.Logo != nil) + s.emitAudit(context.WithoutCancel(ctx), r, store.AuditEvent{ + TenantID: t.ID, Action: "branding.derived", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", + ActorType: brandingActorType(r, s), ActorName: by, + Metadata: map[string]interface{}{ + "domain": res.Domain, "color_source": res.ColorSource, "logo": res.Logo != nil, "forced": force, + }, + }) + return nil +} + +func brandingActorType(r *http.Request, s *Server) string { + if r == nil { + return "system" + } + return s.projectActorType(r) +} + +// deriveTenantBranding is POST /v1/tenants/{id}/branding/derive. It answers +// with the branding as it is afterwards; a failed run shows as +// derive_state "failed" with the reason, and what was shown stays. +func (s *Server) deriveTenantBranding(w http.ResponseWriter, r *http.Request) { + if !s.brandingDeriveEnabled() { + writeError(w, http.StatusServiceUnavailable, "derive_disabled", "branding derivation is switched off for this registry") + return + } + ctx, cancel := context.WithTimeout(r.Context(), deriveBudget+2*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + if t.Status == store.StatusDemo { + writeError(w, http.StatusConflict, "demo_tenant", "demo workspaces get no derived branding") + return + } + _ = s.deriveBranding(ctx, r, t, true, s.projectActor(r)) + b, err := s.Store.GetTenantBranding(ctx, t.ID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, s.brandingView(t.ID, b)) +} + +// RunBranding derives queued workspaces in the background, a few at a time, +// every `every`. With BRANDING_BACKFILL=on it first queues every customer +// workspace that has no branding yet. Off unless BRANDING_DERIVE=on. +func (s *Server) RunBranding(ctx context.Context, every time.Duration) { + if !s.brandingDeriveEnabled() { + s.Log.Info("branding derivation off (BRANDING_DERIVE)") + return + } + if every <= 0 { + every = time.Minute + } + if s.Cfg.BrandingBackfill { + n, err := s.Store.EnqueueMissingBranding(ctx, s.now()) + s.Log.Info("branding backfill queued", "tenants", n, "err", err) + } + t := time.NewTicker(every) + defer t.Stop() + for { + s.DeriveDueBranding(ctx, 5) + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +// DeriveDueBranding derives up to limit queued workspaces, one after the +// other, and returns how many it tried. +func (s *Server) DeriveDueBranding(ctx context.Context, limit int) int { + ids, err := s.Store.DueBranding(ctx, s.now(), limit) + if err != nil { + s.Log.Warn("branding queue read failed", "err", err) + return 0 + } + for _, id := range ids { + if ctx.Err() != nil { + return 0 + } + t, err := s.Store.GetTenant(ctx, id) + if err != nil { + continue + } + if t.Status == store.StatusDemo || t.Status == store.StatusArchived { + _ = s.Store.FailBranding(ctx, t.ID, "skipped_"+t.Status, nil, s.now()) + continue + } + _ = s.deriveBranding(ctx, nil, t, false, "") + } + return len(ids) +} diff --git a/internal/server/branding_derive_test.go b/internal/server/branding_derive_test.go new file mode 100644 index 0000000..c2cee8d --- /dev/null +++ b/internal/server/branding_derive_test.go @@ -0,0 +1,155 @@ +package server_test + +import ( + "bytes" + "context" + "crypto/tls" + "image" + "image/png" + "net/http" + "net/http/httptest" + "net/netip" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/branding" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// brandSite is a company home page every derivation lands on. +type brandSite struct { + srv *httptest.Server + down bool +} + +func newBrandSite(t *testing.T) *brandSite { + t.Helper() + bs := &brandSite{} + img := image.NewNRGBA(image.Rect(0, 0, 180, 180)) + for i := range img.Pix { + img.Pix[i] = []byte{0x0a, 0x7d, 0x3e, 0xff}[i%4] + } + var logo bytes.Buffer + _ = png.Encode(&logo, img) + bs.srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if bs.down { + http.Error(w, "down", http.StatusServiceUnavailable) + return + } + switch r.URL.Path { + case "/": + _, _ = w.Write([]byte(``)) + case "/a.png": + _, _ = w.Write(logo.Bytes()) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(bs.srv.Close) + return bs +} + +func (bs *brandSite) wire(h *testHarness) { + h.app.Cfg.BrandingDerive = true + h.app.BrandingFetcher = branding.NewFetcher(branding.FetchConfig{ + DialAddr: bs.srv.Listener.Addr().String(), + TLS: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // test server + AllowIP: func(a netip.Addr) bool { return a.IsLoopback() }, + }) +} + +func TestBrandingDerive(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + site := newBrandSite(t) + + // Switched off: nothing is queued and the endpoint refuses. + _, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": "off-co", "name": "Off Co", "admin_email": "it@example.com"}) + off := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, raw).Tenant + if _, err := h.store.GetTenantBranding(ctx, off.ID); err == nil { + t.Fatal("queued while switched off") + } + if resp, _ := h.do("POST", "/v1/tenants/"+off.ID+"/branding/derive", map[string]any{}); resp.StatusCode != 503 { + t.Fatalf("derive while off: %d", resp.StatusCode) + } + + site.wire(h) + _, raw = h.do("POST", "/v1/tenants", map[string]any{"slug": "derive-co", "name": "Derive Co", "admin_email": "derive@example.com"}) + tn := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, raw).Tenant + if b, err := h.store.GetTenantBranding(ctx, tn.ID); err != nil || b.DeriveState != store.BrandingPending { + t.Fatalf("not queued at creation: %+v %v", b, err) + } + if resp, _ := h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); resp.StatusCode != 201 { + t.Fatal("trial") + } + + // The background run derives it: logo and its colour, with a notice. + if n := h.app.DeriveDueBranding(ctx, 5); n != 1 { + t.Fatalf("derived %d", n) + } + got := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}) + if got.Branding == nil || got.Branding.Color == nil || *got.Branding.Color != "#0a7d3e" || got.Branding.LogoETag == nil || + !got.Branding.Notice || got.Branding.Domain != "example.com" { + t.Fatalf("derived: %+v", got.Branding) + } + if b, _ := h.store.GetTenantBranding(ctx, tn.ID); b.ColorSource != "logo" || b.LogoSource == "" || b.DeriveAttempts != 1 { + t.Fatalf("provenance: %+v", b) + } + events, _, _ := h.store.ListAudit(ctx, store.AuditFilter{TenantID: tn.ID, Action: "branding.derived"}) + if len(events) != 1 || events[0].Metadata["domain"] != "example.com" { + t.Fatalf("audit: %+v", events) + } + + // "Neu ermitteln" over a manual colour: replaced, no notice. + if resp, _ := h.do("PUT", "/v1/tenants/"+tn.ID+"/branding", map[string]any{"color": "#123456"}); resp.StatusCode != 200 { + t.Fatal("manual put") + } + resp, raw := h.do("POST", "/v1/tenants/"+tn.ID+"/branding/derive", map[string]any{}) + b := decode[brandingResp](t, raw) + if resp.StatusCode != 200 || b.Manual || b.Notice || b.Color == nil || *b.Color != "#0a7d3e" || !b.DeriveEnabled { + t.Fatalf("forced: %d %+v", resp.StatusCode, b) + } + + // A failed run keeps what is shown and says why. + site.down = true + resp, raw = h.do("POST", "/v1/tenants/"+tn.ID+"/branding/derive", map[string]any{}) + b = decode[brandingResp](t, raw) + if resp.StatusCode != 200 || b.DeriveState != "failed" || b.Color == nil { + t.Fatalf("failed run: %d %s", resp.StatusCode, raw) + } + + // In the background a failure is tried again later. + _, raw = h.do("POST", "/v1/tenants", map[string]any{"slug": "retry-co", "name": "Retry Co", "admin_email": "retry@example.com"}) + retry := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, raw).Tenant + h.app.DeriveDueBranding(ctx, 5) + if b, _ := h.store.GetTenantBranding(ctx, retry.ID); b.DeriveState != store.BrandingPending || b.NextAttemptAt == nil || b.DeriveError != "http_503" { + t.Fatalf("retry: %+v", b) + } + + // Free-mail admin: the members' company domain; none: no_domain. + site.down = false + _, raw = h.do("POST", "/v1/tenants", map[string]any{"slug": "free-co", "name": "Free Co", "admin_email": "chef@gmail.com"}) + free := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, raw).Tenant + h.kcMock.Members["free-co"] = []keycloak.OrgMember{{UserID: "m1", Email: "chef@gmail.com"}, {UserID: "m2", Email: "a@example.com"}} + _, raw = h.do("POST", "/v1/tenants/"+free.ID+"/branding/derive", map[string]any{}) + if b := decode[brandingResp](t, raw); b.Domain != "example.com" || b.Color == nil { + t.Fatalf("member domain: %s", raw) + } + h.kcMock.Members["free-co"] = []keycloak.OrgMember{{UserID: "m1", Email: "chef@gmail.com"}} + _, raw = h.do("POST", "/v1/tenants/"+free.ID+"/branding/derive", map[string]any{}) + if b := decode[struct { + DeriveState string `json:"derive_state"` + DeriveError string `json:"derive_error"` + }](t, raw); b.DeriveState != "failed" || b.DeriveError != "no_domain" { + t.Fatalf("no domain: %s", raw) + } + }) +} diff --git a/internal/server/catalog.go b/internal/server/catalog.go index 096bc7b..b5e0941 100644 --- a/internal/server/catalog.go +++ b/internal/server/catalog.go @@ -181,6 +181,7 @@ func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) { Metadata: map[string]interface{}{"product": in.Product, "expires_at": expiresAt.Format(time.RFC3339)}, }) s.provisionProduct(ctx, r, t, entry, tp) + s.enqueueBranding(ctx, t) writeJSON(w, http.StatusCreated, tp) } diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index a17eb2d..2482274 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -54,6 +54,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding/logo"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding/ack"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/branding/derive"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities"}, {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities/portal:billing.view"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests"}, diff --git a/internal/server/server.go b/internal/server/server.go index d396e40..d6a478b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -16,6 +16,7 @@ import ( "time" "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/branding" "git.breakpilot.com/platform/tenant-registry/internal/buildinfo" "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/erp" @@ -49,6 +50,9 @@ type Server struct { Mail mail.Sender // nil ⇒ notifications queue up unsent (F3) Gitea *gitea.Client // Managed Git user lists (t81); nil ⇒ http.DefaultClient Now func() time.Time // injectable clock (tests); nil ⇒ time.Now + // BrandingFetcher reads customers' home pages (#155); nil ⇒ the + // production fetcher. Tests point it at their own server. + BrandingFetcher *branding.Fetcher // Contracts are the released contract documents; nil ⇒ the committed // ones (contractdocs.Default). Tests pass their own. Contracts *contractdocs.Catalogue @@ -180,6 +184,7 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("PUT /v1/tenants/{id}/branding", s.putTenantBranding) mux.HandleFunc("GET /v1/tenants/{id}/branding/logo", s.getTenantBrandingLogo) mux.HandleFunc("POST /v1/tenants/{id}/branding/ack", s.ackTenantBranding) + mux.HandleFunc("POST /v1/tenants/{id}/branding/derive", s.deriveTenantBranding) mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile) mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile) // Rollen- und Befugnisdatensatz (0024): the GET is a {sub} of tenantSubresource. diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 28c1f5c..7c20c18 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -221,6 +221,8 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat if in.Kind != "demo" { s.EnqueueCustomerUpsert(ctx, t) } + // Customer branding (#155): derived in the background, never waited on. + s.enqueueBranding(ctx, t) return t, invite, nil } diff --git a/openapi.yaml b/openapi.yaml index 101d64c..0391b60 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -513,6 +513,26 @@ paths: "304": { description: Not modified. } "404": { description: The tenant does not exist or has no logo (no_logo). } + /v1/tenants/{id}/branding/derive: + post: + summary: Derive the branding again from the signup domain ("Neu ermitteln"). + description: | + Synchronous, at most about 25 s. Reads the home page of the + workspace's company domain (the admin's address, else the most + frequent member domain; never free mail). Replaces a manual choice + and counts as acknowledged. A failed run answers 200 with + derive_state "failed" and the reason; what was shown stays. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The branding afterwards. + content: + application/json: { schema: { $ref: "#/components/schemas/Branding" } } + "404": { $ref: "#/components/responses/NotFound" } + "409": { description: "demo_tenant: demo workspaces get no derived branding." } + "503": { description: "derive_disabled: BRANDING_DERIVE is off." } + /v1/tenants/{id}/branding/ack: post: summary: Acknowledge the branding notice ("Passt"). -- 2.54.1 From 31916175021f58d70a5337cf9d279758de492b6a Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:29:48 +0100 Subject: [PATCH 4/4] fix(branding): stop background retries once the budget ran out When the 25 s budget was what failed, the attempt count was read with the expired context; Postgres refused, and a retry was scheduled every 6 h without end. The failure is now recorded with a context that has not ended. README: BRANDING_DERIVE, BRANDING_BACKFILL and the branding route groups. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + internal/server/branding_derive.go | 13 ++-- internal/server/branding_internal_test.go | 92 +++++++++++++++++++++++ 3 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 internal/server/branding_internal_test.go diff --git a/README.md b/README.md index 3602646..7e62d33 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Env vars (override at the shell): | `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret | | `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route | | `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` | +| `BRANDING_DERIVE` | `off` | `on` ⇒ derive a workspace's colour and logo from its signup domain's home page (#155): queued at tenant creation and trial request, derived in the background, and `POST …/branding/derive`. Product clients and the portal need the route groups `branding.read` (the logo) and `branding.ack` ("Passt") | +| `BRANDING_BACKFILL` | `off` | `on` (with `BRANDING_DERIVE`) ⇒ queue every customer workspace without branding once at start; their admins then see the notice | | `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) | diff --git a/internal/server/branding_derive.go b/internal/server/branding_derive.go index 5782151..89f758f 100644 --- a/internal/server/branding_derive.go +++ b/internal/server/branding_derive.go @@ -22,8 +22,9 @@ import ( // customer workspace without branding once at start. // deriveBudget bounds one derivation: the home page, the manifest and a few -// logo candidates at 10 s each, under the server's 30 s write timeout. -const deriveBudget = 25 * time.Second +// logo candidates at 10 s each, under the server's 30 s write timeout. A +// variable for the tests. +var deriveBudget = 25 * time.Second // brandingRetries: a derivation that failed on the network is tried again // this many times in the background, brandingRetryAfter apart. @@ -88,16 +89,18 @@ func (s *Server) deriveBranding(ctx context.Context, r *http.Request, t *store.T if errors.Is(err, errNoDomain) { reason = "no_domain" } + // The budget may be what ran out: record with a context that has not. + rec := context.WithoutCancel(ctx) var next *time.Time - if cur, gerr := s.Store.GetTenantBranding(ctx, t.ID); !final && (gerr != nil || cur.DeriveAttempts+1 < brandingRetries) { + if cur, gerr := s.Store.GetTenantBranding(rec, t.ID); !final && (errors.Is(gerr, store.ErrNotFound) || (gerr == nil && cur.DeriveAttempts+1 < brandingRetries)) { n := s.now().Add(brandingRetryAfter) next = &n } - if ferr := s.Store.FailBranding(context.WithoutCancel(ctx), t.ID, reason, next, s.now()); ferr != nil { + if ferr := s.Store.FailBranding(rec, t.ID, reason, next, s.now()); ferr != nil { s.Log.Warn("branding: recording the failure failed", "tenant_id", t.ID, "err", ferr) } s.Log.Info("branding derivation failed", "tenant_id", t.ID, "reason", reason, "retry", next != nil) - s.emitAudit(context.WithoutCancel(ctx), r, store.AuditEvent{ + s.emitAudit(rec, r, store.AuditEvent{ TenantID: t.ID, Action: "branding.failed", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", ActorType: brandingActorType(r, s), ActorName: by, Metadata: map[string]interface{}{"domain": domain, "reason": reason, "retry": next != nil}, diff --git a/internal/server/branding_internal_test.go b/internal/server/branding_internal_test.go new file mode 100644 index 0000000..e956740 --- /dev/null +++ b/internal/server/branding_internal_test.go @@ -0,0 +1,92 @@ +package server + +import ( + "context" + "crypto/tls" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/netip" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/branding" + "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ctxStore answers like Postgres does once a context has ended. +type ctxStore struct{ store.Store } + +func (c ctxStore) GetTenantBranding(ctx context.Context, id string) (*store.TenantBranding, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return c.Store.GetTenantBranding(ctx, id) +} + +func (c ctxStore) FailBranding(ctx context.Context, id, msg string, next *time.Time, at time.Time) error { + if err := ctx.Err(); err != nil { + return err + } + return c.Store.FailBranding(ctx, id, msg, next, at) +} + +// A site slower than the whole budget: the failure is still recorded, and +// the background stops retrying after brandingRetries attempts. +func TestDeriveBranding_budgetRunsOut(t *testing.T) { + old := deriveBudget + deriveBudget = 100 * time.Millisecond + t.Cleanup(func() { deriveBudget = old }) + + release := make(chan struct{}) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(func() { close(release); srv.Close() }) + + mem := store.NewMemory() + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + s := &Server{ + Cfg: &config.Config{BrandingDerive: true}, Log: slog.New(slog.NewTextHandler(io.Discard, nil)), + Store: ctxStore{mem}, Keycloak: keycloak.NewMock(), Now: func() time.Time { return now }, + BrandingFetcher: branding.NewFetcher(branding.FetchConfig{ + DialAddr: srv.Listener.Addr().String(), + TLS: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // test server + AllowIP: func(a netip.Addr) bool { return a.IsLoopback() }, + }), + } + ctx := context.Background() + tn, err := mem.CreateTenant(ctx, store.TenantCreate{Slug: "slow-co", Name: "Slow Co", AdminEmail: "it@example.com"}) + if err != nil { + t.Fatal(err) + } + if _, err := mem.EnqueueBranding(ctx, tn.ID, now); err != nil { + t.Fatal(err) + } + for attempt := 1; attempt <= brandingRetries; attempt++ { + if n := s.DeriveDueBranding(ctx, 5); n != 1 { + t.Fatalf("attempt %d: derived %d", attempt, n) + } + b, err := mem.GetTenantBranding(ctx, tn.ID) + if err != nil { + t.Fatal(err) + } + if b.DeriveAttempts != attempt || b.DeriveError != "timeout" { + t.Fatalf("attempt %d: %+v", attempt, b) + } + wantRetry := attempt < brandingRetries + if (b.DeriveState == store.BrandingPending) != wantRetry || (b.NextAttemptAt != nil) != wantRetry { + t.Fatalf("attempt %d: state %s, next %v", attempt, b.DeriveState, b.NextAttemptAt) + } + now = now.Add(brandingRetryAfter + time.Minute) + } + if n := s.DeriveDueBranding(ctx, 5); n != 0 { + t.Fatalf("retried after the last attempt: %d", n) + } +} -- 2.54.1