Files
tenant-registry/internal/branding/fetch.go
T
Sharang ParnerkarandClaude Opus 5.5 fb86a78324
ci / shared (pull_request) Successful in 30s
ci / test (pull_request) Successful in 8m49s
ci / image (pull_request) Skipped
feat(branding): derive colour and logo from the signup domain
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 <noreply@anthropic.com>
2026-12-01 13:15:31 +01:00

222 lines
6.1 KiB
Go

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://<domain>/, else https://www.<domain>/.
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"
}