diff --git a/README.md b/README.md index 3602646..7e62d33 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Env vars (override at the shell): | `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret | | `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route | | `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` | +| `BRANDING_DERIVE` | `off` | `on` ⇒ derive a workspace's colour and logo from its signup domain's home page (#155): queued at tenant creation and trial request, derived in the background, and `POST …/branding/derive`. Product clients and the portal need the route groups `branding.read` (the logo) and `branding.ack` ("Passt") | +| `BRANDING_BACKFILL` | `off` | `on` (with `BRANDING_DERIVE`) ⇒ queue every customer workspace without branding once at start; their admins then see the notice | | `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing | | `DOCUMENTS_MAX_MB` | `200` | Upload limit per document | | `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) | diff --git a/internal/server/branding_derive.go b/internal/server/branding_derive.go index 5782151..89f758f 100644 --- a/internal/server/branding_derive.go +++ b/internal/server/branding_derive.go @@ -22,8 +22,9 @@ import ( // customer workspace without branding once at start. // deriveBudget bounds one derivation: the home page, the manifest and a few -// logo candidates at 10 s each, under the server's 30 s write timeout. -const deriveBudget = 25 * time.Second +// logo candidates at 10 s each, under the server's 30 s write timeout. A +// variable for the tests. +var deriveBudget = 25 * time.Second // brandingRetries: a derivation that failed on the network is tried again // this many times in the background, brandingRetryAfter apart. @@ -88,16 +89,18 @@ func (s *Server) deriveBranding(ctx context.Context, r *http.Request, t *store.T if errors.Is(err, errNoDomain) { reason = "no_domain" } + // The budget may be what ran out: record with a context that has not. + rec := context.WithoutCancel(ctx) var next *time.Time - if cur, gerr := s.Store.GetTenantBranding(ctx, t.ID); !final && (gerr != nil || cur.DeriveAttempts+1 < brandingRetries) { + if cur, gerr := s.Store.GetTenantBranding(rec, t.ID); !final && (errors.Is(gerr, store.ErrNotFound) || (gerr == nil && cur.DeriveAttempts+1 < brandingRetries)) { n := s.now().Add(brandingRetryAfter) next = &n } - if ferr := s.Store.FailBranding(context.WithoutCancel(ctx), t.ID, reason, next, s.now()); ferr != nil { + if ferr := s.Store.FailBranding(rec, t.ID, reason, next, s.now()); ferr != nil { s.Log.Warn("branding: recording the failure failed", "tenant_id", t.ID, "err", ferr) } s.Log.Info("branding derivation failed", "tenant_id", t.ID, "reason", reason, "retry", next != nil) - s.emitAudit(context.WithoutCancel(ctx), r, store.AuditEvent{ + s.emitAudit(rec, r, store.AuditEvent{ TenantID: t.ID, Action: "branding.failed", TargetID: t.ID, TargetType: "branding", TargetName: "Erscheinungsbild", ActorType: brandingActorType(r, s), ActorName: by, Metadata: map[string]interface{}{"domain": domain, "reason": reason, "retry": next != nil}, diff --git a/internal/server/branding_internal_test.go b/internal/server/branding_internal_test.go new file mode 100644 index 0000000..e956740 --- /dev/null +++ b/internal/server/branding_internal_test.go @@ -0,0 +1,92 @@ +package server + +import ( + "context" + "crypto/tls" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/netip" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/branding" + "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ctxStore answers like Postgres does once a context has ended. +type ctxStore struct{ store.Store } + +func (c ctxStore) GetTenantBranding(ctx context.Context, id string) (*store.TenantBranding, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return c.Store.GetTenantBranding(ctx, id) +} + +func (c ctxStore) FailBranding(ctx context.Context, id, msg string, next *time.Time, at time.Time) error { + if err := ctx.Err(); err != nil { + return err + } + return c.Store.FailBranding(ctx, id, msg, next, at) +} + +// A site slower than the whole budget: the failure is still recorded, and +// the background stops retrying after brandingRetries attempts. +func TestDeriveBranding_budgetRunsOut(t *testing.T) { + old := deriveBudget + deriveBudget = 100 * time.Millisecond + t.Cleanup(func() { deriveBudget = old }) + + release := make(chan struct{}) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(func() { close(release); srv.Close() }) + + mem := store.NewMemory() + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + s := &Server{ + Cfg: &config.Config{BrandingDerive: true}, Log: slog.New(slog.NewTextHandler(io.Discard, nil)), + Store: ctxStore{mem}, Keycloak: keycloak.NewMock(), Now: func() time.Time { return now }, + BrandingFetcher: branding.NewFetcher(branding.FetchConfig{ + DialAddr: srv.Listener.Addr().String(), + TLS: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // test server + AllowIP: func(a netip.Addr) bool { return a.IsLoopback() }, + }), + } + ctx := context.Background() + tn, err := mem.CreateTenant(ctx, store.TenantCreate{Slug: "slow-co", Name: "Slow Co", AdminEmail: "it@example.com"}) + if err != nil { + t.Fatal(err) + } + if _, err := mem.EnqueueBranding(ctx, tn.ID, now); err != nil { + t.Fatal(err) + } + for attempt := 1; attempt <= brandingRetries; attempt++ { + if n := s.DeriveDueBranding(ctx, 5); n != 1 { + t.Fatalf("attempt %d: derived %d", attempt, n) + } + b, err := mem.GetTenantBranding(ctx, tn.ID) + if err != nil { + t.Fatal(err) + } + if b.DeriveAttempts != attempt || b.DeriveError != "timeout" { + t.Fatalf("attempt %d: %+v", attempt, b) + } + wantRetry := attempt < brandingRetries + if (b.DeriveState == store.BrandingPending) != wantRetry || (b.NextAttemptAt != nil) != wantRetry { + t.Fatalf("attempt %d: state %s, next %v", attempt, b.DeriveState, b.NextAttemptAt) + } + now = now.Add(brandingRetryAfter + time.Minute) + } + if n := s.DeriveDueBranding(ctx, 5); n != 0 { + t.Fatalf("retried after the last attempt: %d", n) + } +}