carlos / platform Public

fix: demo admission review round 2

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev dd97bf20ff36a2a6b7962d4f48cae293add9c910 parent bb38485
7 files changed, +376 −31
  • internal/console/apidemo.go +47 −7
  • internal/console/apidemo_test.go +214 −2
  • internal/console/demo_store.go +34 −14
  • internal/console/demo_store_test.go +26 −0
  • internal/console/server.go +8 −2
  • internal/demo/config.go +20 −6
  • internal/demo/config_test.go +27 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>a6f3f907ea06d2fac</task-id> <tool-use-id>toolu_01FzEJ9HwuJ115Bh1qn3oChB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a6f3f907ea06d2fac.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- P2-1 ADDRESSED: `internal/console/apidemo.go:118-127`, catch-all keys go through `ParseInstanceCatchallHost` before the validity and overlap checks. - P2-2 ADDRESSED: `internal/demo/config.go:120-134` keys IPv6 by /64, and `apidemo.go:331-361` adds a shared overflow bucket of 60 per minute. - P2-3 ADDRESSED: the read-only `CheckDemoLiveCeiling` (`demo_store.go:150-161`) runs before the budget is charged (`apidemo.go:281`), and `Retry-After` is now 300 (`apidemo.go:230`). - P3-2 ADDRESSED: dynamic-state problems only log at startup (`apidemo.go:134-136`) and are rechecked on create and update (`apidemo.go:275, 285`). - P3-3 ADDRESSED: each startup check logs its name (`apidemo.go:40-49`), config errors name the setting (`internal/demo/config.go:39-79`), and `cmd/console/main.go:470` logs the error. - P3-4 ADDRESSED: `SpendDemoCreate` uses `BudgetIP` (`demo_store.go:111`). - P3-6 ADDRESSED: `demo_store.go:330-332` maps "no rows" to the invalid-credential error. New breakage from the fix: - P2-N1: every anonymous `POST /api/demo/apps` now runs a bucket LIST of `apps/&lt;holding&gt;/` and a full registry route scan (`apidemo.go:285`, via `validateDemoAdmissionState` at `:155-182`). This happens before the create budget is checked (`:289`), and nothing limits the request rate. A caller whose budget is used up still costs the server one paid S3 LIST per request. When the dynamic state is bad, each request also writes a log line (`:204`), so any anonymous caller can flood the operator log. Fault family: anonymous requests drive paid store operations without bound, against the "S3 requests cost money" rule. Fix: cache the check's result for 30 to 60 s with single-flight, log only when the result changes, and add a test that counts LIST calls. - P3: an attacker with a /48 can fill all 8,192 limiter slots and drain the overflow bucket (the implementer acknowledges this). `Validate` loops over maps, so when several settings are wrong it names a different one from run to run. The update path has the same cost as P2-N1, but only token holders can reach it. Verdict: READY AFTER FIXES The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-1-review-r2.md`.</result> <usage><subagent_tokens>81058</subagent_tokens><tool_uses>12</tool_uses><duration_ms>141498</duration_ms></usage> </task-notification>

Attributed to this commit: 54.6 g CO₂e (6,269,764 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index 6f43fc2b7..91379111f 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -137,11 +137,6 @@ func validateDemoConfig(cfg Config, st *Store) error {
if err := validateDemoBuildReadinessPending(cfg); err != nil {
return demoConfigFailure("build readiness", err)
}
- // Transient routes and purge leftovers refuse admission, never console boot.
- // Recheck on requests so repairs can restore admission without a restart.
- if err := validateDemoAdmissionState(ctx, cfg, st); err != nil {
- demoConfigFailure("admission unavailable at startup", err)
- }
return nil
}
@@ -199,9 +194,42 @@ func validateDemoAdmissionState(ctx context.Context, cfg Config, st *Store) erro
return nil
}
+const demoAdmissionTTL = 45 * time.Second
+
+type demoAdmissionCache struct {
+ mu sync.Mutex
+ expiresAt time.Time
+ checked bool
+ err error
+}
+
func (s *Server) demoAdmissionReady(ctx context.Context) error {
- if err := validateDemoAdmissionState(ctx, s.cfg, s.store); err != nil {
- return demoConfigFailure("admission refused", err)
+ c := &s.demoAdmission
+ // Hold the lock through refresh so concurrent requests share one verdict.
+ // Cache failures too; a store outage must not turn retries into more LISTs.
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if !c.checked || !time.Now().Before(c.expiresAt) {
+ err := validateDemoAdmissionState(ctx, s.cfg, s.store)
+ previous, current := "", ""
+ if c.err != nil {
+ previous = c.err.Error()
+ }
+ if err != nil {
+ current = err.Error()
+ }
+ if !c.checked || previous != current {
+ if err != nil {
+ demoConfigFailure("admission refused", err)
+ } else if c.checked {
+ log.Printf("console: demo admission ready")
+ }
+ }
+ c.err, c.checked = err, true
+ c.expiresAt = time.Now().Add(demoAdmissionTTL)
+ }
+ if c.err != nil {
+ return DemoConfigError()
}
return nil
}
@@ -272,6 +300,14 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) {
demoError(w, lookupErr)
return
}
+ if row.ActiveJobID != "" {
+ demoError(w, ErrDemoBusy)
+ return
+ }
+ if row.UpdateAttempts >= demo.MaxUpdateAttempts {
+ demoError(w, ErrDemoUpdateLimit)
+ return
+ }
if err := s.demoAdmissionReady(r.Context()); err != nil {
jsonError(w, 503, demoCopy["DEMO-CONFIG"])
return
@@ -282,6 +318,10 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) {
demoError(w, err)
return
}
+ if err := s.store.CheckDemoCreateBudget(r.Context(), s.clientIP(r), time.Now(), s.cfg.Demo); err != nil {
+ demoError(w, err)
+ return
+ }
if err := s.demoAdmissionReady(r.Context()); err != nil {
jsonError(w, 503, demoCopy["DEMO-CONFIG"])
return
diff --git a/internal/console/apidemo_test.go b/internal/console/apidemo_test.go
index f1bdc2cfc..d9362df49 100644
--- a/internal/console/apidemo_test.go
+++ b/internal/console/apidemo_test.go
@@ -13,6 +13,8 @@ import (
"path/filepath"
"strconv"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -501,8 +503,8 @@ func TestDemoConfigDynamicStateRefusesAdmission(t *testing.T) {
if w.Code != 503 || b.read || !strings.Contains(w.Body.String(), demoCopy["DEMO-CONFIG"]) {
t.Fatalf("admission: %d read=%v %s", w.Code, b.read, w.Body.String())
}
- if !strings.Contains(logs.String(), kind) {
- t.Errorf("admission log lacks check: %s", &logs)
+ if logs.Len() != 0 {
+ t.Errorf("unchanged startup verdict logged again: %s", &logs)
}
var n int
if err := st.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&n); err != nil || n != 0 {
@@ -528,6 +530,11 @@ func TestDemoConfigDynamicStateRefusesAdmission(t *testing.T) {
}
logs.Reset()
w = demoRequest(srv, "", "192.0.2.1")
+ if w.Code != 503 || !strings.Contains(w.Body.String(), demoCopy["DEMO-CONFIG"]) {
+ t.Fatalf("cached failure before expiry: %d %s", w.Code, w.Body.String())
+ }
+ expireDemoAdmissionCache(srv)
+ w = demoRequest(srv, "", "192.0.2.1")
if w.Code != 503 || !strings.Contains(w.Body.String(), demoCopy["DEMO-BUILD"]) {
t.Fatalf("repaired admission: %d %s", w.Code, w.Body.String())
}
@@ -574,3 +581,208 @@ func TestDemoConfigOperatorDiagnostics(t *testing.T) {
t.Fatalf("lost list error: %s", &logs)
}
}
+
+// Count only the dynamic holding-account scan, not static domain claims.
+type demoCountingListStore struct {
+ release.Store
+ calls atomic.Int64
+}
+
+func (s *demoCountingListStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if strings.HasPrefix(prefix, "apps/") {
+ s.calls.Add(1)
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func TestDemoAdmissionListBounded(t *testing.T) {
+ for _, exhausted := range []bool{false, true} {
+ t.Run(fmt.Sprintf("exhausted=%v", exhausted), func(t *testing.T) {
+ s := demoTestServer(t)
+ counted := &demoCountingListStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ if exhausted {
+ for range s.cfg.Demo.CreatePerIPDay {
+ if err := s.store.SpendDemoCreate(t.Context(), "192.0.2.1", time.Now(), s.cfg.Demo); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ var wg sync.WaitGroup
+ for range 20 {
+ wg.Go(func() {
+ for range 5 {
+ w := demoRequest(s, "", "192.0.2.1")
+ if w.Code != 429 && (exhausted || w.Code != 503) {
+ t.Errorf("response: %d %s", w.Code, w.Body.String())
+ }
+ }
+ })
+ }
+ wg.Wait()
+ want := int64(1)
+ if exhausted {
+ want = 0
+ }
+ if got := counted.calls.Load(); got != want {
+ t.Fatalf("100 requests: holding LIST calls=%d, want %d", got, want)
+ }
+ })
+ }
+}
+
+func expireDemoAdmissionCache(s *Server) {
+ s.demoAdmission.mu.Lock()
+ defer s.demoAdmission.mu.Unlock()
+ s.demoAdmission.expiresAt = time.Now().Add(-time.Second)
+}
+
+func TestDemoAdmissionCacheRefresh(t *testing.T) {
+ s := demoTestServer(t)
+ counted := &demoCountingListStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ var logs bytes.Buffer
+ previous := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(previous)
+ wave := func(wantError bool, wantCalls int64) {
+ t.Helper()
+ var wg sync.WaitGroup
+ for range 50 {
+ wg.Go(func() {
+ if err := s.demoAdmissionReady(t.Context()); (err != nil) != wantError {
+ t.Errorf("admission error=%v, wantError=%v", err, wantError)
+ }
+ })
+ }
+ wg.Wait()
+ if got := counted.calls.Load(); got != wantCalls {
+ t.Fatalf("LIST calls=%d, want %d", got, wantCalls)
+ }
+ }
+ wave(false, 1)
+ if ttl := time.Until(s.demoAdmission.expiresAt); ttl < 30*time.Second || ttl > 60*time.Second {
+ t.Fatalf("cache TTL=%s", ttl)
+ }
+ expireDemoAdmissionCache(s)
+ wave(false, 2)
+ if logs.Len() != 0 {
+ t.Fatalf("unchanged healthy verdict logged: %s", &logs)
+ }
+ counted.Store = demoFailAppListStore{counted.Store}
+ expireDemoAdmissionCache(s)
+ wave(true, 3)
+ if strings.Count(logs.String(), "orphan list failure") != 1 {
+ t.Fatalf("failure log: %s", &logs)
+ }
+ logs.Reset()
+ // Failed verdicts are cached too, including across unchanged refreshes.
+ wave(true, 3)
+ expireDemoAdmissionCache(s)
+ wave(true, 4)
+ if logs.Len() != 0 {
+ t.Fatalf("unchanged failure logged: %s", &logs)
+ }
+ counted.Store = counted.Store.(demoFailAppListStore).Store
+ wave(true, 4)
+ expireDemoAdmissionCache(s)
+ wave(false, 5)
+ wave(false, 5)
+ if strings.Count(logs.String(), "demo admission ready") != 1 {
+ t.Fatalf("recovery log: %s", &logs)
+ }
+}
+
+func TestDemoAdmissionStartupCache(t *testing.T) {
+ st, _ := demoTestStore(t)
+ cfg := demoTestDeploymentConfig(t)
+ counted := &demoCountingListStore{Store: cfg.Releases}
+ cfg.Releases = counted
+ s, err := NewServer(cfg, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range 20 {
+ if w := demoRequest(s, "", "192.0.2.1"); w.Code != 503 {
+ t.Fatalf("response=%d", w.Code)
+ }
+ }
+ if got := counted.calls.Load(); got != 1 {
+ t.Fatalf("startup plus requests: LIST calls=%d, want 1", got)
+ }
+ expireDemoAdmissionCache(s)
+ if w := demoRequest(s, "", "192.0.2.1"); w.Code != 503 {
+ t.Fatalf("response=%d", w.Code)
+ }
+ if got := counted.calls.Load(); got != 2 {
+ t.Fatalf("expired cache: LIST calls=%d, want 2", got)
+ }
+}
+
+func TestDemoAdmissionCheapRefusalsSkipList(t *testing.T) {
+ for _, kind := range []string{"global", "ceiling", "update budget", "update busy"} {
+ t.Run(kind, func(t *testing.T) {
+ s := demoTestServer(t)
+ counted := &demoCountingListStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ token := ""
+ want := 429
+ if kind == "global" {
+ s.cfg.Demo.CreateGlobalDay = 1
+ if err := s.store.SpendDemoCreate(t.Context(), "198.51.100.1", time.Now(), s.cfg.Demo); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ in := demoTestAdmission(t, s.cfg.Demo)
+ row, err := s.store.ReserveDemo(t.Context(), in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch kind {
+ case "ceiling":
+ s.cfg.Demo.MaxLive = 1
+ case "update budget":
+ token = "Bearer " + in.Identity.Token
+ _, err = s.store.db.Exec(`UPDATE demo_apps SET update_attempts=60 WHERE demo_id=?`, row.ID)
+ case "update busy":
+ token = "Bearer " + in.Identity.Token
+ want = 409
+ _, err = s.store.db.Exec(`UPDATE demo_apps SET active_job_id='job' WHERE demo_id=?`, row.ID)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for range 100 {
+ if w := demoRequest(s, token, "192.0.2.1"); w.Code != want {
+ t.Fatalf("response=%d, want %d", w.Code, want)
+ }
+ }
+ if got := counted.calls.Load(); got != 0 {
+ t.Fatalf("refused requests: LIST calls=%d, want 0", got)
+ }
+ })
+ }
+}
+
+func TestDemoAdmissionUpdateListBounded(t *testing.T) {
+ s := demoTestServer(t)
+ counted := &demoCountingListStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ in := demoTestAdmission(t, s.cfg.Demo)
+ if _, err := s.store.ReserveDemo(t.Context(), in); err != nil {
+ t.Fatal(err)
+ }
+ for i := range 61 {
+ want := 503
+ if i == 60 {
+ want = 429
+ }
+ if w := demoRequest(s, "Bearer "+in.Identity.Token, "192.0.2.1"); w.Code != want {
+ t.Fatalf("update %d: response=%d, want %d", i+1, w.Code, want)
+ }
+ }
+ if got := counted.calls.Load(); got != 1 {
+ t.Fatalf("updates: LIST calls=%d, want 1", got)
+ }
+}
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go
index 875e10d3e..d18f4fdb1 100644
--- a/internal/console/demo_store.go
+++ b/internal/console/demo_store.go
@@ -108,10 +108,6 @@ func (s *Store) SpendDemoCreate(ctx context.Context, ip string, now time.Time, c
if !cfg.Enabled || cfg.Validate() != nil {
return demo.ErrConfig
}
- ip, err := demo.BudgetIP(ip)
- if err != nil {
- return err
- }
tx, err := s.demoTx(ctx)
if err != nil {
return err
@@ -120,27 +116,51 @@ func (s *Store) SpendDemoCreate(ctx context.Context, ip string, now time.Time, c
if _, err = tx.ExecContext(ctx, `DELETE FROM demo_admissions WHERE attempted_at<=?`, now.Add(-24*time.Hour).UnixNano()); err != nil {
return err
}
- var salt []byte
- if err = tx.QueryRowContext(ctx, `SELECT ip_salt FROM demo_settings WHERE id=1`).Scan(&salt); err != nil {
+ hash, err := demoCreateBudget(ctx, tx, ip, now, cfg)
+ if err != nil {
return err
}
- if len(salt) != 32 {
+ if _, err = tx.ExecContext(ctx, `INSERT INTO demo_admissions(ip_hash,attempted_at) VALUES(?,?)`, hash, now.UnixNano()); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// CheckDemoCreateBudget is a read-only refusal before the cached store scan.
+// SpendDemoCreate rechecks under the writer lock before charging an attempt.
+func (s *Store) CheckDemoCreateBudget(ctx context.Context, ip string, now time.Time, cfg demo.Config) error {
+ if !cfg.Enabled || cfg.Validate() != nil || s.claimGated() {
return demo.ErrConfig
}
+ _, err := demoCreateBudget(ctx, s.db, ip, now, cfg)
+ return err
+}
+
+func demoCreateBudget(ctx context.Context, q interface {
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+}, ip string, now time.Time, cfg demo.Config) ([]byte, error) {
+ ip, err := demo.BudgetIP(ip)
+ if err != nil {
+ return nil, err
+ }
+ var salt []byte
+ if err := q.QueryRowContext(ctx, `SELECT ip_salt FROM demo_settings WHERE id=1`).Scan(&salt); err != nil {
+ return nil, err
+ }
+ if len(salt) != 32 {
+ return nil, demo.ErrConfig
+ }
mac := hmac.New(sha256.New, salt)
mac.Write([]byte(ip))
hash := mac.Sum(nil)
var total, atIP int
- if err = tx.QueryRowContext(ctx, `SELECT count(*), coalesce(sum(ip_hash=?),0) FROM demo_admissions`, hash).Scan(&total, &atIP); err != nil {
- return err
+ if err := q.QueryRowContext(ctx, `SELECT count(*), coalesce(sum(ip_hash=?),0) FROM demo_admissions WHERE attempted_at>?`, hash, now.Add(-24*time.Hour).UnixNano()).Scan(&total, &atIP); err != nil {
+ return nil, err
}
if total >= cfg.CreateGlobalDay || atIP >= cfg.CreatePerIPDay {
- return ErrDemoCreateLimit
+ return nil, ErrDemoCreateLimit
}
- if _, err = tx.ExecContext(ctx, `INSERT INTO demo_admissions(ip_hash,attempted_at) VALUES(?,?)`, hash, now.UnixNano()); err != nil {
- return err
- }
- return tx.Commit()
+ return hash, nil
}
// CheckDemoLiveCeiling is a read-only hint before charging a create attempt.
diff --git a/internal/console/demo_store_test.go b/internal/console/demo_store_test.go
index f67ec8729..17f7529a1 100644
--- a/internal/console/demo_store_test.go
+++ b/internal/console/demo_store_test.go
@@ -320,3 +320,29 @@ func TestDemoLockedDeletedWhileWaiting(t *testing.T) {
t.Fatalf("deleted credential status=%d", w.Code)
}
}
+
+func TestDemoCreateBudgetPrecheckReadOnly(t *testing.T) {
+ st, _ := demoTestStore(t)
+ cfg := demoTestConfig(t)
+ cfg.CreatePerIPDay = 1
+ now := time.Now()
+ if err := st.SpendDemoCreate(t.Context(), "::ffff:192.0.2.1", now, cfg); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.CheckDemoCreateBudget(t.Context(), "192.0.2.1", now.Add(24*time.Hour-time.Nanosecond), cfg); !errors.Is(err, ErrDemoCreateLimit) {
+ t.Fatalf("before rolling cutoff: %v", err)
+ }
+ if err := st.CheckDemoCreateBudget(t.Context(), "192.0.2.1", now.Add(24*time.Hour), cfg); err != nil {
+ t.Fatalf("at rolling cutoff: %v", err)
+ }
+ var count int
+ if err := st.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&count); err != nil || count != 1 {
+ t.Fatalf("precheck changed rows: count=%d err=%v", count, err)
+ }
+ if _, err := st.db.Exec(`DELETE FROM demo_settings`); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.CheckDemoCreateBudget(t.Context(), "192.0.2.1", now.Add(24*time.Hour), cfg); err == nil {
+ t.Fatal("missing salt admitted")
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index b7d8b0a20..72736458b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -982,8 +982,9 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
- demoStatus demoStatusLimiter
- purchaseWake chan struct{}
+ demoAdmission demoAdmissionCache
+ demoStatus demoStatusLimiter
+ purchaseWake chan struct{}
// manifestSeen is the sqids whose accounts/<sqid>/account.json this
// process has seen exist (read, or written by the backfill), so an app
@@ -1797,6 +1798,11 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
billing: newBillingRuntime(cfg.Billing),
seen: map[string]time.Time{},
}
+ if cfg.Demo.Enabled {
+ // Seed the same cache requests use. Transient state refuses admission,
+ // never console boot; repairs are picked up after the cache expires.
+ _ = s.demoAdmissionReady(context.Background())
+ }
if s.perf == nil {
s.perf = &perf.Recorder{}
}
diff --git a/internal/demo/config.go b/internal/demo/config.go
index c278e24df..f827d2fff 100644
--- a/internal/demo/config.go
+++ b/internal/demo/config.go
@@ -59,9 +59,16 @@ func LoadConfig(getenv func(string) string) (Config, error) {
}
func (c Config) Validate() error {
- for key, value := range map[string]int{"CARLOS_DEMO_CREATE_PER_IP_DAY": c.CreatePerIPDay, "CARLOS_DEMO_CREATE_GLOBAL_DAY": c.CreateGlobalDay, "CARLOS_DEMO_MAX_LIVE": c.MaxLive} {
- if value <= 0 {
- return fmt.Errorf("%w: %s must be positive", ErrConfig, key)
+ for _, setting := range []struct {
+ key string
+ value int
+ }{
+ {"CARLOS_DEMO_CREATE_PER_IP_DAY", c.CreatePerIPDay},
+ {"CARLOS_DEMO_CREATE_GLOBAL_DAY", c.CreateGlobalDay},
+ {"CARLOS_DEMO_MAX_LIVE", c.MaxLive},
+ } {
+ if setting.value <= 0 {
+ return fmt.Errorf("%w: %s must be positive", ErrConfig, setting.key)
}
}
if c.BuildConcurrency < 1 || c.BuildConcurrency > 4 {
@@ -70,9 +77,16 @@ func (c Config) Validate() error {
if !c.Enabled && !c.BuildWorker {
return nil
}
- for key, valid := range map[string]bool{"CARLOS_DEMO_ACCOUNT": validLabel(c.Account, 32), "CARLOS_DEMO_FLEET": validLabel(c.Fleet, 32), "CARLOS_DEMO_DOMAIN": ValidDomain(c.Domain)} {
- if !valid {
- return fmt.Errorf("%w: %s is missing or invalid", ErrConfig, key)
+ for _, setting := range []struct {
+ key string
+ valid bool
+ }{
+ {"CARLOS_DEMO_ACCOUNT", validLabel(c.Account, 32)},
+ {"CARLOS_DEMO_FLEET", validLabel(c.Fleet, 32)},
+ {"CARLOS_DEMO_DOMAIN", ValidDomain(c.Domain)},
+ } {
+ if !setting.valid {
+ return fmt.Errorf("%w: %s is missing or invalid", ErrConfig, setting.key)
}
}
if c.BuildWorker && !filepath.IsAbs(c.ToolchainDir) {
diff --git a/internal/demo/config_test.go b/internal/demo/config_test.go
index dc4882ab4..43d14a321 100644
--- a/internal/demo/config_test.go
+++ b/internal/demo/config_test.go
@@ -103,3 +103,30 @@ func TestDemoConfigErrorNamesSetting(t *testing.T) {
})
}
}
+
+func TestDemoConfigValidateOrder(t *testing.T) {
+ c := Config{Enabled: true, BuildWorker: true}
+ for _, step := range []struct {
+ key string
+ repair func()
+ }{
+ {"CARLOS_DEMO_CREATE_PER_IP_DAY", func() { c.CreatePerIPDay = 30 }},
+ {"CARLOS_DEMO_CREATE_GLOBAL_DAY", func() { c.CreateGlobalDay = 100 }},
+ {"CARLOS_DEMO_MAX_LIVE", func() { c.MaxLive = 20 }},
+ {"CARLOS_DEMO_BUILD_CONCURRENCY", func() { c.BuildConcurrency = 1 }},
+ {"CARLOS_DEMO_ACCOUNT", func() { c.Account = "shop" }},
+ {"CARLOS_DEMO_FLEET", func() { c.Fleet = "demo" }},
+ {"CARLOS_DEMO_DOMAIN", func() { c.Domain = "demo.example.com" }},
+ {"CARLOS_DEMO_TOOLCHAIN_DIR", func() { c.ToolchainDir = "/opt/demo-toolchain" }},
+ } {
+ for range 100 {
+ if err := c.Validate(); !errors.Is(err, ErrConfig) || !strings.Contains(err.Error(), step.key) {
+ t.Fatalf("want first invalid setting %s, got %v", step.key, err)
+ }
+ }
+ step.repair()
+ }
+ if err := c.Validate(); err != nil {
+ t.Fatal(err)
+ }
+}