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/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 { 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