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] 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").