Customer branding (#155), the contract part: products and the portal can read and set a workspace's CI colour and logo. The derivation from the signup domain follows in a separate change. - Migration 0035: tenant_branding (colour, 256×256 PNG logo with its sha256 ETag, manual flag, provenance, derivation queue, notice ack). ON DELETE CASCADE, so a purge removes it. - Entitlements check: "branding" {color, logo_etag, notice, domain, name}, only when allowed and there is a colour or logo. A read error leaves the field out instead of failing the check. - GET/PUT /v1/tenants/{id}/branding (tenants.read/write): the portal's Erscheinungsbild page; a PUT makes the branding manual. Logos are decoded (PNG, JPEG, GIF, ICO) and re-encoded; SVG is refused. - GET /v1/tenants/{id}/branding/logo (branding.read): PNG, ETag, 304. - POST /v1/tenants/{id}/branding/ack (branding.ack): "Passt" by an IT admin or owner, checked in Keycloak; 403 not_admin otherwise. - BRANDING_DERIVE config switch (off by default), reported to the portal as derive_enabled. - CI runs the new internal/branding tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
348 lines
12 KiB
Go
348 lines
12 KiB
Go
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' }
|