feat: add bounded anonymous demo admission
15 files changed,
+1,671
−55
cmd/console/main.go+6 −0internal/console/apidemo.go+370 −0internal/console/apidemo_test.go+322 −0internal/console/authcli.go+1 −0internal/console/demo_store.go+339 −0internal/console/demo_store_test.go+257 −0internal/console/expirypass.go+7 −0internal/console/server.go+61 −50internal/console/store.go+7 −2internal/console/store_gate.go+4 −1internal/console/tempstore.go+3 −2internal/demo/config.go+109 −0internal/demo/config_test.go+86 −0internal/demo/identity.go+59 −0internal/demo/names.go+40 −0
CI failed — run details
Intent
Attributed to this commit: 46.0 g CO₂e (4,282,873 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/cmd/console/main.go b/cmd/console/main.go| index a4d133646..19c88ad10 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -146,6 +146,7 @@ import ( |
| "github.com/carlosframework/platform/internal/alerting" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/geo" |
| @@ -465,7 +466,12 @@ func serve() { |
| if err != nil { |
| log.Fatal(err) |
| } |
| + demoConfig, err := demo.LoadConfig(os.Getenv) |
| + if err != nil { |
| + log.Fatal(console.DemoConfigError()) |
| + } |
| cfg := console.Config{ |
| + Demo: demoConfig, |
| Origin: origin, |
| Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"), |
| Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| new file mode 100644 |
| index 000000000..d33a52039 |
| --- /dev/null |
| +++ b/internal/console/apidemo.go |
| @@ -0,0 +1,370 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// DRAFT pending copy review. Keep this surface's human-facing text here. |
| +var demoCopy = map[string]string{ |
| + "DEMO-CONFIG": "Demo settings are incomplete or inconsistent. Check the holding account, fleet and domain.", |
| + "DEMO-CREATE-LIMIT": "The daily demo creation limit has been reached. Try again after 24 hours.", |
| + "DEMO-LIVE-LIMIT": "All demo places are in use. Existing demos are kept. Try again later.", |
| + "DEMO-TOKEN": "This demo credential is invalid or no longer available.", |
| + "DEMO-UPDATE": "A build is already active or this demo has used its update limit. Updates do not extend expiry.", |
| + "DEMO-BUILD": "Demo builds are unavailable. Try again later.", |
| + "DEMO-SOURCE": "Send a gzip tarball no larger than 5,000,000 bytes within 30 seconds.", |
| + "DEMO-CLAIM-LATER": "Claiming is not available yet.", |
| + "DEMO-STATUS-LIMIT": "Status requests are too frequent. Try again in two seconds.", |
| + "DEMO-NOT-FOUND": "This demo job is not available.", |
| +} |
| + |
| +// DemoConfigError is shared with console startup so operator copy stays here. |
| +func DemoConfigError() error { return errors.New("DEMO-CONFIG: " + demoCopy["DEMO-CONFIG"]) } |
| + |
| +func demoOverlap(a, b string) bool { |
| + return a != "" && b != "" && (a == b || strings.HasSuffix(a, "."+b) || strings.HasSuffix(b, "."+a)) |
| +} |
| +func validateDemoConfig(cfg Config, st *Store) error { |
| + if !cfg.Demo.Enabled { |
| + return nil |
| + } |
| + if cfg.Demo.Validate() != nil || cfg.HostClaim || st.claimGated() || cfg.Releases == nil || cfg.Registry == "" { |
| + return DemoConfigError() |
| + } |
| + origin, err := url.Parse(cfg.Origin) |
| + if err != nil || origin.Hostname() == "" || (origin.Scheme != "https" && origin.Scheme != "http") || demoOverlap(cfg.Demo.Domain, strings.ToLower(origin.Hostname())) || demoOverlap(cfg.Demo.Domain, strings.ToLower(cfg.AppsDomain)) { |
| + return DemoConfigError() |
| + } |
| + acct, err := st.AccountBySqid(cfg.Demo.Account) |
| + if err != nil || acct == nil || acct.ID == OpsAccountID { |
| + return DemoConfigError() |
| + } |
| + var n int |
| + for _, query := range []string{ |
| + `SELECT count(*) FROM memberships WHERE account_id=?`, |
| + `SELECT count(*) FROM cli_tokens WHERE account_id=? AND revoked_at=0`, |
| + `SELECT count(*) FROM apps WHERE account_id=? AND demo_id=''`, |
| + } { |
| + if err = st.db.QueryRow(query, acct.ID).Scan(&n); err != nil || n != 0 { |
| + return DemoConfigError() |
| + } |
| + } |
| + reg, err := openRegistry(cfg.Registry) |
| + if err != nil { |
| + return DemoConfigError() |
| + } |
| + fleets, err := reg.ListFleets() |
| + if err != nil { |
| + return DemoConfigError() |
| + } |
| + found := false |
| + for _, f := range fleets { |
| + if f.Account == acct.Sqid { |
| + if f.Name != cfg.Demo.Fleet { |
| + return DemoConfigError() |
| + } |
| + found = true |
| + } |
| + } |
| + if !found { |
| + return DemoConfigError() |
| + } |
| + routes, err := reg.List() |
| + if err != nil { |
| + return DemoConfigError() |
| + } |
| + for _, rt := range routes { |
| + if rt.Region == "fleet/"+cfg.Demo.Fleet || release.RouteAccount(rt) == acct.Sqid { |
| + life, err := st.AppLife(acct.ID, rt.App) |
| + if err != nil || life == nil || life.DemoID == "" || release.RouteAccount(rt) != acct.Sqid { |
| + return DemoConfigError() |
| + } |
| + } |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + // Check keys rather than the forgiving ListClaims fold: an unreadable claim |
| + // must still reserve its domain, including a parent or child of the demo zone. |
| + keys, err := cfg.Releases.List(ctx, domains.ClaimsPrefix) |
| + if err != nil { |
| + return DemoConfigError() |
| + } |
| + for _, key := range keys { |
| + host := strings.TrimSuffix(strings.TrimPrefix(key, domains.ClaimsPrefix), ".json") |
| + if !demo.ValidDomain(host) || demoOverlap(cfg.Demo.Domain, host) { |
| + return DemoConfigError() |
| + } |
| + } |
| + // An empty holding account must not adopt orphaned release/instance objects. |
| + keys, err = cfg.Releases.List(ctx, "apps/"+acct.Sqid+"/") |
| + if err != nil { |
| + return DemoConfigError() |
| + } |
| + for _, key := range keys { |
| + rest := strings.TrimPrefix(key, "apps/"+acct.Sqid+"/") |
| + app, _, ok := strings.Cut(rest, "/") |
| + if !ok { |
| + return DemoConfigError() |
| + } |
| + life, err := st.AppLife(acct.ID, app) |
| + if err != nil || life == nil || life.DemoID == "" { |
| + return DemoConfigError() |
| + } |
| + } |
| + return validateDemoBuildReadinessPending(cfg) |
| +} |
| + |
| +// Task 5 replaces this hook with capability, worker, bundle and policy-writer |
| +// readiness checks. Until then publish always refuses before reservation. |
| +func validateDemoBuildReadinessPending(Config) error { return nil } |
| + |
| +func (s *Server) registerDemoRoutes() { |
| + if !s.cfg.Demo.Enabled { |
| + return |
| + } |
| + s.registerRoute("POST /api/demo/apps", s.handleDemoPublish) |
| + s.registerRoute("GET /api/demo/jobs/{jobID}", s.handleDemoStatus) |
| + s.registerRoute("GET /demo/claim", func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-CLAIM-LATER"]) |
| + }) |
| +} |
| +func demoError(w http.ResponseWriter, err error) { |
| + switch { |
| + case errors.Is(err, ErrDemoCreateLimit): |
| + w.Header().Set("Retry-After", "86400") |
| + jsonError(w, 429, demoCopy["DEMO-CREATE-LIMIT"]) |
| + case errors.Is(err, ErrDemoLiveLimit): |
| + w.Header().Set("Retry-After", "2") |
| + jsonError(w, 429, demoCopy["DEMO-LIVE-LIMIT"]) |
| + case errors.Is(err, ErrDemoToken): |
| + jsonError(w, 401, demoCopy["DEMO-TOKEN"]) |
| + case errors.Is(err, ErrDemoBusy): |
| + jsonError(w, 409, demoCopy["DEMO-UPDATE"]) |
| + case errors.Is(err, ErrDemoUpdateLimit): |
| + jsonError(w, 429, demoCopy["DEMO-UPDATE"]) |
| + default: |
| + jsonError(w, 503, demoCopy["DEMO-BUILD"]) |
| + } |
| +} |
| + |
| +func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if !s.cfg.Demo.Enabled { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + // Rejected uploads do not need a reusable connection. Keep the deadline |
| + // through Body.Close too, since net/http may drain unread request bytes. |
| + w.Header().Set("Connection", "close") |
| + controller := http.NewResponseController(w) |
| + if err := controller.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil { |
| + demoError(w, err) |
| + return |
| + } |
| + var err error |
| + // Presence, not validity, selects update. Duplicate or empty credentials |
| + // cannot fall through to anonymous create. |
| + if auth, present := r.Header["Authorization"]; present { |
| + if len(auth) != 1 { |
| + demoError(w, ErrDemoToken) |
| + return |
| + } |
| + parts := strings.Fields(auth[0]) |
| + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| + demoError(w, ErrDemoToken) |
| + return |
| + } |
| + row, lookupErr := s.store.LookupDemoToken(r.Context(), parts[1]) |
| + if lookupErr != nil { |
| + demoError(w, lookupErr) |
| + return |
| + } |
| + err = s.withDemoLocked(r.Context(), row.ID, func(row DemoRow, _ AppLife) error { return s.store.SpendDemoUpdate(r.Context(), row.ID, time.Now()) }) |
| + } else { |
| + err = s.store.SpendDemoCreate(r.Context(), s.clientIP(r), time.Now(), s.cfg.Demo) |
| + } |
| + if err != nil { |
| + demoError(w, err) |
| + return |
| + } |
| + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || media != "application/gzip" { |
| + jsonError(w, 415, demoCopy["DEMO-SOURCE"]) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, demo.SourceMaxBytes) |
| + defer r.Body.Close() |
| + if r.ContentLength > demo.SourceMaxBytes { |
| + jsonError(w, 413, demoCopy["DEMO-SOURCE"]) |
| + return |
| + } |
| + // Task 2 will validate a bounded spool. Task 1 retains no archive and never |
| + // creates a job, but still consumes the bounded request as controller R2 asks. |
| + hash := sha256.New() |
| + if _, err = io.Copy(hash, r.Body); err != nil { |
| + var tooLarge *http.MaxBytesError |
| + if errors.As(err, &tooLarge) { |
| + jsonError(w, 413, demoCopy["DEMO-SOURCE"]) |
| + } else { |
| + jsonError(w, 400, demoCopy["DEMO-SOURCE"]) |
| + } |
| + return |
| + } |
| + jsonError(w, 503, demoCopy["DEMO-BUILD"]) |
| +} |
| + |
| +type demoStatusEntry struct { |
| + at time.Time |
| + count int |
| +} |
| +type demoStatusLimiter struct { |
| + mu sync.Mutex |
| + entries map[string]demoStatusEntry |
| +} |
| + |
| +func (l *demoStatusLimiter) allow(ip string, now time.Time) bool { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.entries == nil { |
| + l.entries = make(map[string]demoStatusEntry) |
| + } |
| + for key, e := range l.entries { |
| + if !now.Before(e.at.Add(time.Minute)) { |
| + delete(l.entries, key) |
| + } |
| + } |
| + e, ok := l.entries[ip] |
| + if !ok { |
| + if len(l.entries) >= 8192 { |
| + return false |
| + } |
| + e.at = now |
| + } |
| + if e.count >= 60 { |
| + return false |
| + } |
| + e.count++ |
| + l.entries[ip] = e |
| + return true |
| +} |
| +func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", "2") |
| + if !s.cfg.Demo.Enabled { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + ip, err := demo.CanonicalIP(s.clientIP(r)) |
| + if err != nil { |
| + jsonError(w, 400, demoCopy["DEMO-NOT-FOUND"]) |
| + return |
| + } |
| + if !s.demoStatus.allow(ip, time.Now()) { |
| + jsonError(w, 429, demoCopy["DEMO-STATUS-LIMIT"]) |
| + return |
| + } |
| + // Task 5 supplies the DB job read and state mapping. There are no jobs yet; |
| + // an unknown ID must never disclose app rows, credentials or bucket state. |
| + jsonError(w, 404, demoCopy["DEMO-NOT-FOUND"]) |
| +} |
| + |
| +// checkDemoFreshName shares the ordinary claim's prefix occupancy check and |
| +// also refuses a pre-existing row, route or apex hold. It never adopts a name. |
| +func (s *Server) checkDemoFreshName(ctx context.Context, acct *Account, name string) error { |
| + if !strings.HasPrefix(name, demo.AppPrefix) || !demo.ValidPublicName(strings.TrimPrefix(name, demo.AppPrefix)) { |
| + return demo.ErrConfig |
| + } |
| + has, err := s.store.HasAppIn(acct.ID, name) |
| + if err != nil { |
| + return err |
| + } |
| + if has { |
| + return ErrDemoNameTaken |
| + } |
| + wired, err := s.accountAppHasRoutes(acct.Sqid, name) |
| + if err != nil { |
| + return err |
| + } |
| + if wired { |
| + return ErrDemoNameTaken |
| + } |
| + hold, err := s.apexHolder(ctx, acct, name) |
| + if err != nil { |
| + return err |
| + } |
| + if hold != nil { |
| + return ErrDemoNameTaken |
| + } |
| + // Refuse stale policy instead of adopting or clearing another lifetime's |
| + // authority. A collision retry can choose another random name. |
| + present, err := s.appPolicyPresent(ctx, acct, name) |
| + if err != nil { |
| + return err |
| + } |
| + if present { |
| + return ErrDemoNameTaken |
| + } |
| + outcome, _ := s.claimNamePrefixes(ctx, acct, name, false) |
| + if outcome == claimTaken { |
| + return ErrDemoNameTaken |
| + } |
| + if outcome != claimOK { |
| + return demo.ErrConfig |
| + } |
| + return nil |
| +} |
| + |
| +// reserveFreshDemo is the internal workflow's bounded collision retry. Task 5 |
| +// adds its outbox write inside ReserveDemo before wiring this to the HTTP door. |
| +func (s *Server) reserveFreshDemo(ctx context.Context, in DemoAdmission) (DemoRow, demo.Identity, error) { |
| + var zero DemoRow |
| + acct, err := s.store.AccountBySqid(in.Config.Account) |
| + if err != nil { |
| + return zero, demo.Identity{}, err |
| + } |
| + if acct == nil { |
| + return zero, demo.Identity{}, demo.ErrConfig |
| + } |
| + defer s.lockAccount(acct.Sqid)() |
| + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| + defer cancel() |
| + for range demo.NameAttempts { |
| + id, err := demo.NewIdentity(rand.Reader) |
| + if err != nil { |
| + return zero, demo.Identity{}, err |
| + } |
| + in.Identity = id |
| + in.AccountID = acct.ID |
| + in.AccountSqid = acct.Sqid |
| + in.Host = id.Name + "." + in.Config.Domain |
| + in.Fleet = in.Config.Fleet |
| + var row DemoRow |
| + func() { |
| + defer s.lockApp(acct.Sqid, id.App)() |
| + err = s.checkDemoFreshName(ctx, acct, id.App) |
| + if err == nil { |
| + row, err = s.store.ReserveDemo(ctx, in) |
| + } |
| + }() |
| + if errors.Is(err, ErrDemoNameTaken) { |
| + continue |
| + } |
| + return row, id, err |
| + } |
| + return zero, demo.Identity{}, ErrDemoNameTaken |
| +} |
diff --git a/internal/console/apidemo_test.go b/internal/console/apidemo_test.go| new file mode 100644 |
| index 000000000..12ad3a57e |
| --- /dev/null |
| +++ b/internal/console/apidemo_test.go |
| @@ -0,0 +1,322 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func demoTestServer(t *testing.T) *Server { |
| + t.Helper() |
| + st, _ := demoTestStore(t) |
| + s := &Server{store: st, cfg: Config{Demo: demoTestConfig(t)}, mux: http.NewServeMux()} |
| + s.registerDemoRoutes() |
| + return s |
| +} |
| +func demoRequest(s *Server, token, ip string) *demoRecorder { |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader("not an archive")) |
| + r.RemoteAddr = ip + ":1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + if token != "" { |
| + r.Header.Set("Authorization", token) |
| + } |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + return w |
| +} |
| +func TestDemoAdmissionHTTP(t *testing.T) { |
| + s := demoTestServer(t) |
| + for i := 0; i < 31; i++ { |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader("invalid")) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("X-Forwarded-For", fmt.Sprintf("198.51.100.%d", i)) |
| + r.Header.Set("Content-Type", "application/gzip") |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + want := 503 |
| + if i == 30 { |
| + want = 429 |
| + } |
| + if w.Code != want || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("attempt%d: %d %s", i+1, w.Code, w.Body.String()) |
| + } |
| + } |
| + var count int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_apps`).Scan(&count) |
| + if count != 0 { |
| + t.Fatal("unwired handler reserved demo") |
| + } |
| + for i := 0; i < 70; i++ { |
| + w := demoRequest(s, "", fmt.Sprintf("198.51.100.%d", i+1)) |
| + if w.Code != 503 { |
| + t.Fatalf("global attempt%d: %d", i+31, w.Code) |
| + } |
| + } |
| + if w := demoRequest(s, "", "203.0.113.1"); w.Code != 429 { |
| + t.Fatalf("global101=%d", w.Code) |
| + } |
| +} |
| +func TestDemoUpdateAuthority(t *testing.T) { |
| + s := demoTestServer(t) |
| + for _, token := range []string{"Bearer invalid", "Basic abc", "Bearer ", "Bearer a b"} { |
| + if w := demoRequest(s, token, "192.0.2.1"); w.Code != 401 { |
| + t.Fatalf("invalid auth: %d", w.Code) |
| + } |
| + } |
| + var count int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&count) |
| + if count != 0 { |
| + t.Fatal("invalid bearer fell back to create") |
| + } |
| + in := demoTestAdmission(t, s.cfg.Demo) |
| + row, err := s.store.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := demoRequest(s, "Bearer "+in.Identity.Token, "192.0.2.1") |
| + if w.Code != 503 { |
| + t.Fatalf("update %d %s", w.Code, w.Body.String()) |
| + } |
| + got, err := s.store.LookupDemoToken(t.Context(), in.Identity.Token) |
| + if err != nil || got.ID != row.ID || got.UpdateAttempts != 1 { |
| + t.Fatalf("update: %+v %v", got, err) |
| + } |
| + life, _ := s.store.AppLife(42, row.App) |
| + if life.ExpiresAt != in.Now.Add(24*time.Hour).Unix() { |
| + t.Fatal("expiry changed") |
| + } |
| + s.store.db.Exec(`UPDATE demo_apps SET active_job_id='job' WHERE demo_id=?`, row.ID) |
| + if w := demoRequest(s, "Bearer "+in.Identity.Token, "192.0.2.1"); w.Code != 409 { |
| + t.Fatalf("active update: %d", w.Code) |
| + } |
| +} |
| +func TestDemoConfigOff(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.cfg.Demo.Enabled = false |
| + if w := demoRequest(s, "", "192.0.2.1"); w.Code != 404 { |
| + t.Fatalf("off=%d", w.Code) |
| + } |
| + var count int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&count) |
| + if count != 0 { |
| + t.Fatal("off spent budget") |
| + } |
| + if temporaryAppCap != 20 || cliTemporaryCreateBurst != 50 { |
| + t.Fatal("ordinary bounds changed") |
| + } |
| +} |
| +func TestDemoIdentityStatus(t *testing.T) { |
| + s := demoTestServer(t) |
| + in := demoTestAdmission(t, s.cfg.Demo) |
| + if _, err := s.store.ReserveDemo(t.Context(), in); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 61; i++ { |
| + r := httptest.NewRequest("GET", "/api/demo/jobs/unknown", nil) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + want := 404 |
| + if i == 60 { |
| + want = 429 |
| + } |
| + if w.Code != want || strings.Contains(w.Body.String(), in.Identity.Token) || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Retry-After") != "2" { |
| + t.Fatalf("status%d: %d %v %s", i, w.Code, w.Header(), w.Body.String()) |
| + } |
| + } |
| +} |
| + |
| +type demoUnreadBody struct{ read bool } |
| + |
| +func (b *demoUnreadBody) Read([]byte) (int, error) { b.read = true; return 0, io.EOF } |
| +func (b *demoUnreadBody) Close() error { return nil } |
| +func TestDemoAdmissionBodyBounds(t *testing.T) { |
| + s := demoTestServer(t) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader(strings.Repeat("a", 5_000_001))) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 413 { |
| + t.Fatalf("oversize=%d", w.Code) |
| + } |
| + s.cfg.Demo.CreatePerIPDay = 1 |
| + b := new(demoUnreadBody) |
| + r = httptest.NewRequest("POST", "/api/demo/apps", nil) |
| + r.Body = b |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + w = newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 429 || b.read { |
| + t.Fatalf("budget before body: %d read=%v", w.Code, b.read) |
| + } |
| +} |
| + |
| +type demoRecorder struct{ *httptest.ResponseRecorder } |
| + |
| +func newDemoRecorder() *demoRecorder { return &demoRecorder{httptest.NewRecorder()} } |
| +func (w *demoRecorder) SetReadDeadline(time.Time) error { return nil } |
| + |
| +func TestDemoConfigStartup(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + regPath := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + regMu.Lock() |
| + if cached := regCache[regPath]; cached != nil { |
| + cached.Close() |
| + delete(regCache, regPath) |
| + } |
| + regMu.Unlock() |
| + reg.Close() |
| + }) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "demo", Account: "shop", Bucket: "demo-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := Config{Demo: demoTestConfig(t), Origin: "https://console.example.com", AppsDomain: "apps.example.com", Registry: regPath, Releases: release.NewDirStore(t.TempDir())} |
| + if err := validateDemoConfig(cfg, st); err != nil { |
| + t.Fatalf("valid: %v", err) |
| + } |
| + for _, domain := range []string{"example.com", "console.example.com", "apps.example.com", "x.apps.example.com"} { |
| + bad := cfg |
| + bad.Demo.Domain = domain |
| + if err := validateDemoConfig(bad, st); err == nil { |
| + t.Errorf("overlap accepted: %s", domain) |
| + } |
| + } |
| + bad := cfg |
| + bad.Demo.Account = "ops" |
| + if err := validateDemoConfig(bad, st); err == nil { |
| + t.Fatal("ops accepted") |
| + } |
| + bad = cfg |
| + bad.Demo.Fleet = "missing" |
| + if err := validateDemoConfig(bad, st); err == nil { |
| + t.Fatal("missing fleet accepted") |
| + } |
| + bad = cfg |
| + bad.HostClaim = true |
| + if err := validateDemoConfig(bad, st); err == nil { |
| + t.Fatal("claims accepted") |
| + } |
| + if _, err := st.db.Exec(`INSERT INTO memberships(account_id,address,role,added_at) VALUES(42,'owner@example.com','owner',0)`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := validateDemoConfig(cfg, st); err == nil { |
| + t.Fatal("holding account member accepted") |
| + } |
| + st.db.Exec(`DELETE FROM memberships WHERE account_id=42`) |
| + if _, err := cfg.Releases.Put(t.Context(), "domains/demo.example.com.json", []byte("unreadable"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := validateDemoConfig(cfg, st); err == nil { |
| + t.Fatal("customer claim overlap accepted") |
| + } |
| + cfg.Demo.Enabled = false |
| + cfg.Releases = demoFailStore{} |
| + if err := validateDemoConfig(cfg, st); err != nil { |
| + t.Fatalf("disabled consulted deployment: %v", err) |
| + } |
| +} |
| + |
| +type demoFailStore struct{ release.Store } |
| + |
| +func (demoFailStore) List(context.Context, string) ([]string, error) { |
| + return nil, errors.New("injected") |
| +} |
| + |
| +func TestDemoAdmissionFailsClosed(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.store.Close() |
| + b := new(demoUnreadBody) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", nil) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Body = b |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 503 || b.read { |
| + t.Fatalf("DB failure=%d, read=%v", w.Code, b.read) |
| + } |
| +} |
| + |
| +func TestDemoAdmissionReadDeadline(t *testing.T) { |
| + s := demoTestServer(t) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader("archive")) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + w := &demoDeadlineRecorder{demoRecorder: newDemoRecorder()} |
| + before := time.Now() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 503 || len(w.deadlines) != 1 || w.deadlines[0].Sub(before) < 29*time.Second || w.deadlines[0].Sub(before) > 31*time.Second { |
| + t.Fatalf("deadline: %d %v", w.Code, w.deadlines) |
| + } |
| +} |
| + |
| +type demoDeadlineRecorder struct { |
| + *demoRecorder |
| + deadlines []time.Time |
| +} |
| + |
| +func (w *demoDeadlineRecorder) SetReadDeadline(at time.Time) error { |
| + w.deadlines = append(w.deadlines, at) |
| + return nil |
| +} |
| + |
| +func TestDemoAdmissionFreshNamespace(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.cfg.Registry = filepath.Join(t.TempDir(), "registry.db") |
| + s.cfg.Releases = release.NewDirStore(t.TempDir()) |
| + t.Cleanup(func() { |
| + regMu.Lock() |
| + defer regMu.Unlock() |
| + if reg := regCache[s.cfg.Registry]; reg != nil { |
| + reg.Close() |
| + delete(regCache, s.cfg.Registry) |
| + } |
| + }) |
| + acct, err := s.store.AccountBySqid("shop") |
| + if err != nil || acct == nil { |
| + t.Fatal(acct, err) |
| + } |
| + name := "tmp-demo-bright-otter-42" |
| + if !reservedAppName(acct, name) { |
| + t.Fatal("demo namespace available to ordinary create") |
| + } |
| + if err := s.checkDemoFreshName(t.Context(), acct, name); err != nil { |
| + t.Fatalf("fresh name: %v", err) |
| + } |
| + if _, err := s.cfg.Releases.Put(t.Context(), "control/app-policy/shop/"+name+".json", []byte("stale policy"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.checkDemoFreshName(t.Context(), acct, name); err == nil { |
| + t.Fatal("fresh demo could inherit old policy") |
| + } |
| + if got, _, _ := s.claimAppWith(t.Context(), acct, "shop", "owner@example.com", "fleet/demo", false, regionReq{}, time.Time{}); got != claimReserved { |
| + t.Fatalf("ordinary creation on demo fleet: %v", got) |
| + } |
| +} |
| + |
| +func TestDemoAdmissionChunkedBodyCap(t *testing.T) { |
| + s := demoTestServer(t) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader(strings.Repeat("a", 5_000_001))) |
| + r.ContentLength = -1 |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 413 { |
| + t.Fatalf("chunked cap=%d", w.Code) |
| + } |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 6c4607db8..2c8884e19 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -528,6 +528,7 @@ func (s *Server) cliGateRefused(allow svcrole.Set, h http.HandlerFunc, refused f |
| // Every /api/cli/ door goes through cliRoute and names its roles. Pinned by |
| // TestEveryCLIDoorNamesItsRoles. |
| func (s *Server) registerCLIRoutes() { |
| + s.registerDemoRoutes() |
| s.registerRoute("POST /api/fleet/replicas/{account}/{app}/{host}/coordinator", s.handleReplicaCoordinator) |
| s.registerRoute("POST /api/fleet/replicas/{account}/{app}/{host}/release", s.handleReplicaRelease) |
| s.registerRoute("POST /auth/cli/start", s.handleCLIStart) |
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go| new file mode 100644 |
| index 000000000..846a10434 |
| --- /dev/null |
| +++ b/internal/console/demo_store.go |
| @@ -0,0 +1,339 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "database/sql" |
| + "encoding/base64" |
| + "errors" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +var ( |
| + ErrDemoCreateLimit = errors.New("demo: create budget exhausted") |
| + ErrDemoLiveLimit = errors.New("demo: live ceiling reached") |
| + ErrDemoToken = errors.New("demo: unavailable credential") |
| + ErrDemoUpdateLimit = errors.New("demo: update budget exhausted") |
| + ErrDemoBusy = errors.New("demo: job already active") |
| + ErrDemoNameTaken = errors.New("demo: name already reserved") |
| +) |
| + |
| +// DemoRow contains no claim token or hash. apps remains the lifecycle authority. |
| +// ActiveJobID is Task 5's single job slot; admission alone never fills it. |
| +type DemoRow struct { |
| + ID, AccountSqid, App, Name, Host, Fleet string |
| + AccountID, CreatedAt, Generation int64 |
| + State, AssignedBox, ActiveJobID string |
| + UpdateAttempts int |
| + CreatingIP string `json:"-"` |
| + SourceSHA256 [32]byte `json:"-"` |
| + Client string `json:"-"` |
| + PurgedAt int64 |
| +} |
| + |
| +type DemoAdmission struct { |
| + Identity demo.Identity |
| + AccountID int64 |
| + AccountSqid, Host, Fleet, IP string |
| + Now time.Time |
| + Config demo.Config |
| + SourceSHA256 [32]byte |
| + Client string |
| +} |
| + |
| +func (s *Store) migrateDemo() error { |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS demo_settings ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), ip_salt BLOB NOT NULL CHECK(length(ip_salt)=32) |
| +); |
| +CREATE TABLE IF NOT EXISTS demo_admissions (ip_hash BLOB NOT NULL, attempted_at INTEGER NOT NULL); |
| +CREATE INDEX IF NOT EXISTS demo_admissions_time ON demo_admissions(attempted_at); |
| +CREATE INDEX IF NOT EXISTS demo_admissions_ip_time ON demo_admissions(ip_hash, attempted_at); |
| +CREATE TABLE IF NOT EXISTS demo_apps ( |
| + demo_id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, account_sqid TEXT NOT NULL, |
| + app TEXT NOT NULL, name TEXT NOT NULL, host TEXT UNIQUE, fleet TEXT NOT NULL, |
| + claim_token_hash BLOB NOT NULL UNIQUE CHECK(length(claim_token_hash)=32), |
| + created_at INTEGER NOT NULL, generation INTEGER NOT NULL DEFAULT 1, |
| + state TEXT NOT NULL DEFAULT 'anonymous' CHECK(state IN ('anonymous','retiring','retired')), |
| + assigned_box TEXT NOT NULL DEFAULT '', active_job_id TEXT NOT NULL DEFAULT '', |
| + update_attempts INTEGER NOT NULL DEFAULT 0 CHECK(update_attempts BETWEEN 0 AND 60), |
| + creating_ip TEXT NOT NULL, source_sha256 BLOB NOT NULL, client TEXT NOT NULL, |
| + purged_at INTEGER NOT NULL DEFAULT 0, |
| + UNIQUE(account_id, app) |
| +);`) |
| + if err != nil { |
| + return err |
| + } |
| + salt := make([]byte, 32) |
| + if _, err := rand.Read(salt); err != nil { |
| + return err |
| + } |
| + _, err = s.db.Exec(`INSERT INTO demo_settings(id,ip_salt) VALUES(1,?) ON CONFLICT(id) DO NOTHING`, salt) |
| + return err |
| +} |
| + |
| +// demoTx takes SQLite's writer lock before any admission reads. It serialises |
| +// count-and-reserve even when two Store handles open the same database. |
| +func (s *Store) demoTx(ctx context.Context) (*sql.Tx, error) { |
| + if s.claimGated() { |
| + return nil, demo.ErrConfig |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + res, err := tx.ExecContext(ctx, `UPDATE demo_settings SET ip_salt=ip_salt WHERE id=1`) |
| + if err == nil { |
| + var n int64 |
| + n, err = res.RowsAffected() |
| + if err == nil && n != 1 { |
| + err = demo.ErrConfig |
| + } |
| + } |
| + if err != nil { |
| + tx.Rollback() |
| + return nil, err |
| + } |
| + return tx, nil |
| +} |
| + |
| +// SpendDemoCreate charges attempts before reading the body. A refusal spends |
| +// nothing; pruning removes only attempts outside the rolling 24-hour window. |
| +func (s *Store) SpendDemoCreate(ctx context.Context, ip string, now time.Time, cfg demo.Config) error { |
| + if !cfg.Enabled || cfg.Validate() != nil { |
| + return demo.ErrConfig |
| + } |
| + ip, err := demo.CanonicalIP(ip) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + 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 { |
| + return err |
| + } |
| + if len(salt) != 32 { |
| + return 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 total >= cfg.CreateGlobalDay || atIP >= cfg.CreatePerIPDay { |
| + return 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() |
| +} |
| + |
| +// ReserveDemo is the SQL half of a fresh claim. The internal workflow must |
| +// first validate the source and run checkDemoFreshName under the account/app |
| +// locks. No handler calls it until Task 5 adds the first job to this transaction. |
| +func (s *Store) ReserveDemo(ctx context.Context, in DemoAdmission) (DemoRow, error) { |
| + var zero DemoRow |
| + c := in.Config |
| + ip, err := demo.CanonicalIP(in.IP) |
| + if err != nil { |
| + return zero, err |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(in.Identity.Token) |
| + if err != nil || len(raw) != 32 { |
| + return zero, ErrDemoToken |
| + } |
| + hash := sha256.Sum256(raw) |
| + id, err := base64.RawURLEncoding.Strict().DecodeString(in.Identity.ID) |
| + if err != nil || len(id) != 16 || !c.Enabled || c.Validate() != nil || in.AccountID == OpsAccountID || in.AccountSqid != c.Account || in.Fleet != c.Fleet || in.Host != in.Identity.Name+"."+c.Domain || !demo.ValidPublicName(in.Identity.Name) || in.Identity.App != demo.AppPrefix+in.Identity.Name || subtle.ConstantTimeCompare(hash[:], in.Identity.TokenHash[:]) != 1 || in.Now.IsZero() { |
| + return zero, demo.ErrConfig |
| + } |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return zero, err |
| + } |
| + defer tx.Rollback() |
| + var account string |
| + if err = tx.QueryRowContext(ctx, `SELECT sqid FROM accounts WHERE id=? AND deleted_at=0`, in.AccountID).Scan(&account); err != nil { |
| + return zero, err |
| + } |
| + if account != in.AccountSqid { |
| + return zero, demo.ErrConfig |
| + } |
| + var count int |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM demo_apps WHERE purged_at=0`).Scan(&count); err != nil { |
| + return zero, err |
| + } |
| + if count >= c.MaxLive { |
| + return zero, ErrDemoLiveLimit |
| + } |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM demo_apps WHERE host=? OR demo_id=? OR (account_id=? AND app=?)`, in.Host, in.Identity.ID, in.AccountID, in.Identity.App).Scan(&count); err != nil { |
| + return zero, err |
| + } |
| + if count != 0 { |
| + return zero, ErrDemoNameTaken |
| + } |
| + created, err := insertAppRow(tx, newAppRow{AccountID: in.AccountID, App: in.Identity.App, CreatedBy: "demo", CreatedAt: in.Now.Unix(), ExpiresAt: in.Now.Add(24 * time.Hour).Unix()}) |
| + if err != nil { |
| + return zero, err |
| + } |
| + if !created { |
| + return zero, ErrDemoNameTaken |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE apps SET demo_id=?, placement=? WHERE account_id=? AND app=?`, in.Identity.ID, "fleet/"+in.Fleet, in.AccountID, in.Identity.App); err != nil { |
| + return zero, err |
| + } |
| + client := strings.ToValidUTF8(strings.TrimSpace(in.Client), "") |
| + if len(client) > 100 { |
| + client = strings.ToValidUTF8(client[:100], "") |
| + } |
| + _, err = tx.ExecContext(ctx, `INSERT INTO demo_apps(demo_id,account_id,account_sqid,app,name,host,fleet,claim_token_hash,created_at,creating_ip,source_sha256,client) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, in.Identity.ID, in.AccountID, in.AccountSqid, in.Identity.App, in.Identity.Name, in.Host, in.Fleet, hash[:], in.Now.Unix(), ip, in.SourceSHA256[:], client) |
| + if err != nil { |
| + return zero, err |
| + } |
| + row, err := scanDemo(tx.QueryRowContext(ctx, `SELECT `+demoCols+` FROM demo_apps WHERE demo_id=?`, in.Identity.ID)) |
| + if err != nil { |
| + return zero, err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return zero, err |
| + } |
| + return row, nil |
| +} |
| + |
| +const demoCols = `demo_id, account_id, account_sqid, app, name, coalesce(host,''), fleet, created_at, generation, state, assigned_box, active_job_id, update_attempts, creating_ip, source_sha256, client, purged_at` |
| + |
| +func scanDemo(sc interface{ Scan(...any) error }) (DemoRow, error) { |
| + var r DemoRow |
| + var hash []byte |
| + err := sc.Scan(&r.ID, &r.AccountID, &r.AccountSqid, &r.App, &r.Name, &r.Host, &r.Fleet, &r.CreatedAt, &r.Generation, &r.State, &r.AssignedBox, &r.ActiveJobID, &r.UpdateAttempts, &r.CreatingIP, &hash, &r.Client, &r.PurgedAt) |
| + copy(r.SourceSHA256[:], hash) |
| + return r, err |
| +} |
| +func (s *Store) demoByID(ctx context.Context, id string) (DemoRow, error) { |
| + return scanDemo(s.db.QueryRowContext(ctx, `SELECT `+demoCols+` FROM demo_apps WHERE demo_id=?`, id)) |
| +} |
| + |
| +func (s *Store) LookupDemoToken(ctx context.Context, token string) (DemoRow, error) { |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(token) |
| + if err != nil || len(raw) != 32 { |
| + return DemoRow{}, ErrDemoToken |
| + } |
| + hash := sha256.Sum256(raw) |
| + var id string |
| + var stored []byte |
| + err = s.db.QueryRowContext(ctx, `SELECT demo_id,claim_token_hash FROM demo_apps WHERE claim_token_hash=?`, hash[:]).Scan(&id, &stored) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return DemoRow{}, ErrDemoToken |
| + } |
| + if err != nil { |
| + return DemoRow{}, err |
| + } |
| + if subtle.ConstantTimeCompare(hash[:], stored) != 1 { |
| + return DemoRow{}, ErrDemoToken |
| + } |
| + row, err := s.demoByID(ctx, id) |
| + if err != nil { |
| + return DemoRow{}, err |
| + } |
| + life, err := s.AppLife(row.AccountID, row.App) |
| + if err != nil { |
| + return DemoRow{}, err |
| + } |
| + if !demoLifeValid(row, life, time.Now()) { |
| + return DemoRow{}, ErrDemoToken |
| + } |
| + return row, nil |
| +} |
| +func demoLifeValid(row DemoRow, life *AppLife, now time.Time) bool { |
| + return life != nil && life.DemoID == row.ID && life.Lifetime != "" && life.DeletedAt == 0 && !life.Restoring && life.ExpiresAt > now.Unix() && row.State == "anonymous" && row.PurgedAt == 0 |
| +} |
| + |
| +// SpendDemoUpdate does not acquire a job slot: Task 5 must check the slot again |
| +// and occupy it in its enqueue transaction. Refused Task 1 uploads never queue. |
| +func (s *Store) SpendDemoUpdate(ctx context.Context, id string, now time.Time) error { |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + row, err := scanDemo(tx.QueryRowContext(ctx, `SELECT `+demoCols+` FROM demo_apps WHERE demo_id=?`, id)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrDemoToken |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + life, err := scanAppLife(tx.QueryRowContext(ctx, `SELECT `+appLifeCols+` FROM apps WHERE account_id=? AND app=?`, row.AccountID, row.App)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrDemoToken |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if !demoLifeValid(row, &life, now) { |
| + return ErrDemoToken |
| + } |
| + if row.ActiveJobID != "" { |
| + return ErrDemoBusy |
| + } |
| + if row.UpdateAttempts >= demo.MaxUpdateAttempts { |
| + return ErrDemoUpdateLimit |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET update_attempts=update_attempts+1 WHERE demo_id=?`, id); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +func (s *Server) withDemoLocked(ctx context.Context, id string, fn func(DemoRow, AppLife) error) error { |
| + row, err := s.store.demoByID(ctx, id) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrDemoToken |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + locked := row |
| + defer s.lockApp(locked.AccountSqid, locked.App)() |
| + row, err = s.store.demoByID(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if row.AccountID != locked.AccountID || row.AccountSqid != locked.AccountSqid || row.App != locked.App { |
| + return ErrDemoToken |
| + } |
| + life, err := s.store.AppLife(row.AccountID, row.App) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoLifeValid(row, life, time.Now()) { |
| + return ErrDemoToken |
| + } |
| + if err = ctx.Err(); err != nil { |
| + return err |
| + } |
| + return fn(row, *life) |
| +} |
| + |
| +// WipeDemoAbuse removes identifying metadata seven days after confirmed purge. |
| +// Task 8 sets purged_at only after the assigned box acknowledges removal, releases |
| +// the host reservation in that transaction. The existing expiry pass calls this. |
| +func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error { |
| + _, err := s.db.ExecContext(ctx, `UPDATE demo_apps SET creating_ip='',source_sha256=X'',client='' WHERE purged_at>0 AND purged_at<=? AND (creating_ip!='' OR length(source_sha256)>0 OR client!='')`, now.Add(-7*24*time.Hour).Unix()) |
| + return err |
| +} |
diff --git a/internal/console/demo_store_test.go b/internal/console/demo_store_test.go| new file mode 100644 |
| index 000000000..c0aa0e906 |
| --- /dev/null |
| +++ b/internal/console/demo_store_test.go |
| @@ -0,0 +1,257 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +func demoTestConfig(t *testing.T) demo.Config { |
| + t.Helper() |
| + env := map[string]string{"CARLOS_DEMO_APPS": "1", "CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "demo.example.com"} |
| + cfg, err := demo.LoadConfig(func(k string) string { return env[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return cfg |
| +} |
| +func demoTestStore(t *testing.T) (*Store, string) { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "demo.db") |
| + st, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { st.Close() }) |
| + if _, err := st.EnsureAccount(42, "shop", "shop", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + return st, path |
| +} |
| +func demoTestAdmission(t *testing.T, cfg demo.Config) DemoAdmission { |
| + t.Helper() |
| + id, err := demo.NewIdentity(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return DemoAdmission{Identity: id, AccountID: 42, AccountSqid: "shop", Host: id.Name + "." + cfg.Domain, Fleet: cfg.Fleet, IP: "192.0.2.1", Now: time.Now(), Config: cfg, SourceSHA256: sha256.Sum256([]byte("archive")), Client: strings.Repeat("x", 120)} |
| +} |
| +func TestDemoAdmissionDurableAndAtomic(t *testing.T) { |
| + t.Run("ceiling", func(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + other, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + cfg := demoTestConfig(t) |
| + var accepted atomic.Int32 |
| + var wg sync.WaitGroup |
| + for i := 0; i < 40; i++ { |
| + in := demoTestAdmission(t, cfg) |
| + db := st |
| + if i%2 != 0 { |
| + db = other |
| + } |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + _, err := db.ReserveDemo(t.Context(), in) |
| + if err == nil { |
| + accepted.Add(1) |
| + } else if !errors.Is(err, ErrDemoLiveLimit) { |
| + t.Errorf("reserve: %v", err) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if accepted.Load() != 20 { |
| + t.Fatalf("acceptedConcurrentCreates=%d", accepted.Load()) |
| + } |
| + var apps, demos int |
| + st.db.QueryRow(`SELECT count(*) FROM apps WHERE demo_id != ''`).Scan(&apps) |
| + st.db.QueryRow(`SELECT count(*) FROM demo_apps`).Scan(&demos) |
| + if apps != 20 || demos != 20 { |
| + t.Fatalf("ceiling evicted/leaked rows: apps=%d demos=%d", apps, demos) |
| + } |
| + }) |
| + t.Run("rolling durable attempts", func(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + cfg := demoTestConfig(t) |
| + now := time.Now() |
| + for i := 0; i < 30; i++ { |
| + if err := st.SpendDemoCreate(t.Context(), "::ffff:192.0.2.1", now, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := st.SpendDemoCreate(t.Context(), "192.0.2.1", now, cfg); !errors.Is(err, ErrDemoCreateLimit) { |
| + t.Fatalf("IP31: %v", err) |
| + } |
| + if err := st.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + if err := st.SpendDemoCreate(t.Context(), "192.0.2.1", now, cfg); !errors.Is(err, ErrDemoCreateLimit) { |
| + t.Fatalf("restart reset IP budget: %v", err) |
| + } |
| + for i := 0; i < 70; i++ { |
| + if err := st.SpendDemoCreate(t.Context(), fmt.Sprintf("198.51.100.%d", i+1), now, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := st.SpendDemoCreate(t.Context(), "203.0.113.1", now, cfg); !errors.Is(err, ErrDemoCreateLimit) { |
| + t.Fatalf("global101: %v", err) |
| + } |
| + var count int |
| + st.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&count) |
| + if count != 100 { |
| + t.Fatalf("refusal spent row: %d", count) |
| + } |
| + if err := st.SpendDemoCreate(t.Context(), "192.0.2.1", now.Add(24*time.Hour), cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + st.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&count) |
| + if count != 1 { |
| + t.Fatalf("prune: %d", count) |
| + } |
| + }) |
| + t.Run("rollback", func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + in := demoTestAdmission(t, demoTestConfig(t)) |
| + if _, err := st.db.Exec(`CREATE TRIGGER refuse_demo BEFORE INSERT ON demo_apps BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.ReserveDemo(t.Context(), in); err == nil { |
| + t.Fatal("injected failure accepted") |
| + } |
| + life, err := st.AppLife(in.AccountID, in.Identity.App) |
| + if err != nil || life != nil { |
| + t.Fatalf("partial app: %+v %v", life, err) |
| + } |
| + }) |
| +} |
| +func TestDemoIdentityStored(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + in := demoTestAdmission(t, demoTestConfig(t)) |
| + row, err := st.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := base64.RawURLEncoding.DecodeString(in.Identity.Token) |
| + hash := sha256.Sum256(raw) |
| + var stored []byte |
| + st.db.QueryRow(`SELECT claim_token_hash FROM demo_apps WHERE demo_id=?`, row.ID).Scan(&stored) |
| + if string(stored) != string(hash[:]) || string(stored) == in.Identity.Token { |
| + t.Fatal("persistedToken != SHA256(rawToken)") |
| + } |
| + got, err := st.LookupDemoToken(t.Context(), in.Identity.Token) |
| + if err != nil || got.ID != row.ID { |
| + t.Fatalf("lookup: %+v %v", got, err) |
| + } |
| + life, err := st.AppLife(42, row.App) |
| + if err != nil || life == nil || life.DemoID != row.ID || life.Lifetime == "" || life.ExpiresAt != in.Now.Add(24*time.Hour).Unix() { |
| + t.Fatalf("life: %+v %v", life, err) |
| + } |
| + if row.CreatingIP != "192.0.2.1" || len(row.Client) != 100 || row.SourceSHA256 != in.SourceSHA256 { |
| + t.Fatalf("abuse metadata: %+v", row) |
| + } |
| + if temporaryAppCap != 20 || cliTemporaryCreateBurst != 50 { |
| + t.Fatal("ordinary temporary bounds changed") |
| + } |
| +} |
| +func TestDemoUpdateAuthorityStore(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + in := demoTestAdmission(t, demoTestConfig(t)) |
| + row, err := st.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 60; i++ { |
| + if err := st.SpendDemoUpdate(t.Context(), row.ID, in.Now); err != nil { |
| + t.Fatalf("update %d: %v", i, err) |
| + } |
| + } |
| + if err := st.SpendDemoUpdate(t.Context(), row.ID, in.Now); !errors.Is(err, ErrDemoUpdateLimit) { |
| + t.Fatalf("update61: %v", err) |
| + } |
| + life, _ := st.AppLife(42, row.App) |
| + if life.ExpiresAt != in.Now.Add(24*time.Hour).Unix() { |
| + t.Fatal("update extended expiry") |
| + } |
| + if _, err := st.LookupDemoToken(t.Context(), "bad"); !errors.Is(err, ErrDemoToken) { |
| + t.Fatalf("invalid token: %v", err) |
| + } |
| + if _, err := st.db.Exec(`UPDATE demo_apps SET update_attempts=0, active_job_id='job' WHERE demo_id=?`, row.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.SpendDemoUpdate(t.Context(), row.ID, in.Now); !errors.Is(err, ErrDemoBusy) { |
| + t.Fatalf("active job: %v", err) |
| + } |
| + srv := &Server{store: st} |
| + called := false |
| + if err := srv.withDemoLocked(context.Background(), row.ID, func(got DemoRow, l AppLife) error { |
| + called = true |
| + if got.ID != row.ID || l.DemoID != row.ID { |
| + t.Fatal("wrong identity") |
| + } |
| + return nil |
| + }); err != nil || !called { |
| + t.Fatalf("lock callback: %v", err) |
| + } |
| + st.db.Exec(`UPDATE apps SET expires_at=? WHERE demo_id=?`, time.Now().Add(-time.Second).Unix(), row.ID) |
| + if _, err := st.LookupDemoToken(t.Context(), in.Identity.Token); !errors.Is(err, ErrDemoToken) { |
| + t.Fatalf("expired token: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoAdmissionRetention(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + in := demoTestAdmission(t, demoTestConfig(t)) |
| + row, err := st.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now().Truncate(time.Second) |
| + if err := st.WipeDemoAbuse(t.Context(), now.Add(30*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := st.demoByID(t.Context(), row.ID) |
| + if got.CreatingIP == "" { |
| + t.Fatal("metadata removed before purge") |
| + } |
| + if _, err := st.db.Exec(`UPDATE demo_apps SET state='retired',purged_at=?,host=NULL WHERE demo_id=?`, now.Unix(), row.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.db.Exec(`DELETE FROM apps WHERE demo_id=?`, row.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.WipeDemoAbuse(t.Context(), now.Add(7*24*time.Hour-time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ = st.demoByID(t.Context(), row.ID) |
| + if got.CreatingIP == "" { |
| + t.Fatal("metadata removed too soon") |
| + } |
| + // Cleanup must run even with demo admission disabled and no app rows left. |
| + srv := &Server{store: st} |
| + srv.expiryPass(t.Context(), now.Add(7*24*time.Hour)) |
| + got, err = st.demoByID(t.Context(), row.ID) |
| + if err != nil || got.CreatingIP != "" || got.Client != "" || got.SourceSHA256 != ([32]byte{}) { |
| + t.Fatalf("retention: %+v %v", got, err) |
| + } |
| +} |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 7a9d6e210..3ec42aed2 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -47,6 +47,13 @@ func (s *Server) StartExpiryPass(ctx context.Context) { |
| // retries early purges: PurgeAppIfTrashedAt acts only on a marker whose clock |
| // matches the row, and a wrong, empty bucket has no such marker. |
| func (s *Server) expiryPass(ctx context.Context, now time.Time) { |
| + // Abuse retention continues after admission is switched off and after the |
| + // app row is gone. This reuses the existing pass; it adds no worker. |
| + if err := s.store.WipeDemoAbuse(ctx, now); err != nil { |
| + log.Printf("console: demo abuse retention: %v", err) |
| + jobFailed(ctx, fmt.Errorf("demo abuse retention: %w", err)) |
| + } |
| + |
| // The hourly store sweep runs after the pass's own work, whether or not |
| // the pass has rows: on a claims-off deployment it is the only purge of |
| // an app past its trash cooloff, headless ones included, now that boxes |
diff --git a/internal/console/server.go b/internal/console/server.go| index 1883966c3..b7d8b0a20 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -40,6 +40,7 @@ import ( |
| "github.com/carlosframework/platform/internal/apppolicy" |
| "github.com/carlosframework/platform/internal/boxid" |
| "github.com/carlosframework/platform/internal/dbreads" |
| + "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/domains" |
| @@ -527,6 +528,7 @@ const ( |
| // Config is everything the server reads its world through. |
| type Config struct { |
| + Demo demo.Config |
| Registrar registrar.Registrar |
| ZoneHost zonehost.Host |
| DomainApex zonehost.ApexSource |
| @@ -980,6 +982,7 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| + demoStatus demoStatusLimiter |
| purchaseWake chan struct{} |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| @@ -1706,6 +1709,9 @@ func normalizeDelegationZone(raw string) string { |
| // NewServer wires a server over an opened Store, loading (or minting) the |
| // console's Keymail signing key. |
| func NewServer(cfg Config, st *Store) (*Server, error) { |
| + if err := validateDemoConfig(cfg, st); err != nil { |
| + return nil, err |
| + } |
| if cfg.Billing != nil && cfg.PlanCatalog == nil { |
| return nil, errors.New("billing needs a plan catalog (CARLOS_PLAN_CATALOG)") |
| } |
| @@ -5226,7 +5232,7 @@ func ownerExempt(prefix, ownPrefix string) bool { return prefix == ownPrefix } |
| // whatever app holds the name, but an app wearing it would still read as |
| // the domain's owner everywhere else. |
| func reservedAppName(acct *Account, name string) bool { |
| - return name == "new" || (acct.Sqid == release.OpsAccount && name == consoleMailApp) |
| + return strings.HasPrefix(name, demo.AppPrefix) || name == "new" || (acct.Sqid == release.OpsAccount && name == consoleMailApp) |
| } |
| // claimApp is the permanent claim every existing door makes: claimAppWith |
| @@ -5235,6 +5241,54 @@ func (s *Server) claimApp(ctx context.Context, acct *Account, name, addr, placem |
| return s.claimAppWith(ctx, acct, name, addr, placement, ownerClaim, rq, time.Time{}) |
| } |
| +// claimNamePrefixes is shared by ordinary claims and the internal demo workflow. |
| +// ownerClaim is always false for demos and ordinary temporary creates. |
| +func (s *Server) claimNamePrefixes(ctx context.Context, acct *Account, name string, ownerClaim bool) (claimOutcome, bool) { |
| + ownPrefix := release.AppPrefix(acct.Sqid, name) |
| + prefixes := []string{ownPrefix} |
| + if acct.ID == OpsAccountID { |
| + prefixes = append(prefixes, release.LegacyAppPrefix(name)) |
| + } |
| + adoptingExistingApp := false |
| + for _, prefix := range prefixes { |
| + keys, err := s.cfg.Releases.List(ctx, prefix) |
| + if err != nil { |
| + return claimStoreFailed, false |
| + } |
| + if s.cfg.HostClaim && prefix == ownPrefix { |
| + free, err := s.claimAdmissionNameFree(ctx, acct.Sqid, name) |
| + if err != nil { |
| + return claimStoreFailed, false |
| + } |
| + if free { |
| + continue |
| + } |
| + } |
| + if len(keys) == 0 { |
| + continue |
| + } |
| + // The owner exemption is an ALLOWLIST: it NAMES the one prefix it |
| + // covers — the account's own, apps/<sqid>/<app>/ — rather than |
| + // excluding the one it doesn't. The two forms are identical over |
| + // today's two prefixes; they differ in what happens to a THIRD one |
| + // added later. Written as an exclusion, any prefix appended to the |
| + // slice above would be exempted for an owner by default, fail-open |
| + // in a guard whose whole job is refusing. Written this way a new |
| + // prefix is refused until someone deliberately adds it here. |
| + // |
| + // The legacy unqualified prefix (ops only) is therefore outside the |
| + // exemption and still refuses whoever is asking: those objects are |
| + // owed an `accounts migrate -from legacy`, and a name handed out |
| + // over them puts an app in that migration's way. |
| + if ownerClaim && ownerExempt(prefix, ownPrefix) { |
| + adoptingExistingApp = true |
| + continue |
| + } |
| + return claimTaken, false |
| + } |
| + return claimOK, adoptingExistingApp |
| +} |
| + |
| // claimAppWith claims an app name for acct — once, ever. A name is refused when |
| // the apps table has it, when ANY owner exists for it (CLI-granted apps stay |
| // claim-proof), or when the release store already holds anything under |
| @@ -5303,6 +5357,9 @@ func (s *Server) claimApp(ctx context.Context, acct *Account, name, addr, placem |
| // §3, so any object under the prefix refuses), and inserts the row with its |
| // expiry in the same statement that claims the name. |
| func (s *Server) claimAppWith(ctx context.Context, acct *Account, name, addr, placement string, ownerClaim bool, rq regionReq, expiresAt time.Time) (outcome claimOutcome, placed string, held *apexHold) { |
| + if s.cfg.Demo.Enabled && (acct.Sqid == s.cfg.Demo.Account || placement == "fleet/"+s.cfg.Demo.Fleet) { |
| + return claimReserved, "", nil |
| + } |
| if !release.ValidApp(name) { |
| return claimInvalid, "", nil |
| } |
| @@ -5339,20 +5396,6 @@ func (s *Server) claimAppWith(ctx context.Context, acct *Account, name, addr, pl |
| return claimTaken, "", nil |
| } |
| } |
| - // The account's own prefix, plus — for ops only — the legacy unqualified |
| - // one an unmigrated app's objects are still at. This one legacy read |
| - // OUTLIVES the retired read-fallback, and deliberately: it is explicit |
| - // rather than a resolution path, and a name whose legacy objects still |
| - // exist is not free. Handing it out would put a stranger's app in the way |
| - // of the `accounts migrate -from legacy` that is still owed to those |
| - // objects. For a non-ops account the legacy prefix belongs to somebody |
| - // else's app and must NOT block the name. |
| - ownPrefix := release.AppPrefix(acct.Sqid, name) |
| - adoptingExistingApp := false |
| - prefixes := []string{ownPrefix} |
| - if acct.ID == OpsAccountID { |
| - prefixes = append(prefixes, release.LegacyAppPrefix(name)) |
| - } |
| // The release-store deadline lives HERE, not in the doors, so both doors |
| // give the bucket the same ten seconds the browser form always has — |
| // and the database checks above stay outside it, as they always were. |
| @@ -5370,41 +5413,9 @@ func (s *Server) claimAppWith(ctx context.Context, acct *Account, name, addr, pl |
| } else if hold != nil { |
| return claimApexHeld, "", hold |
| } |
| - for _, prefix := range prefixes { |
| - keys, err := s.cfg.Releases.List(ctx, prefix) |
| - if err != nil { |
| - return claimStoreFailed, "", nil |
| - } |
| - if s.cfg.HostClaim && prefix == ownPrefix { |
| - free, err := s.claimAdmissionNameFree(ctx, acct.Sqid, name) |
| - if err != nil { |
| - return claimStoreFailed, "", nil |
| - } |
| - if free { |
| - continue |
| - } |
| - } |
| - if len(keys) == 0 { |
| - continue |
| - } |
| - // The owner exemption is an ALLOWLIST: it NAMES the one prefix it |
| - // covers — the account's own, apps/<sqid>/<app>/ — rather than |
| - // excluding the one it doesn't. The two forms are identical over |
| - // today's two prefixes; they differ in what happens to a THIRD one |
| - // added later. Written as an exclusion, any prefix appended to the |
| - // slice above would be exempted for an owner by default, fail-open |
| - // in a guard whose whole job is refusing. Written this way a new |
| - // prefix is refused until someone deliberately adds it here. |
| - // |
| - // The legacy unqualified prefix (ops only) is therefore outside the |
| - // exemption and still refuses whoever is asking: those objects are |
| - // owed an `accounts migrate -from legacy`, and a name handed out |
| - // over them puts an app in that migration's way. |
| - if ownerClaim && ownerExempt(prefix, ownPrefix) { |
| - adoptingExistingApp = true |
| - continue |
| - } |
| - return claimTaken, "", nil |
| + outcome, adoptingExistingApp := s.claimNamePrefixes(ctx, acct, name, ownerClaim) |
| + if outcome != claimOK { |
| + return outcome, "", nil |
| } |
| // Adopting an app whose objects already exist onto a placement is a move |
| // of its sealed values (spec §5.5): refused before the row is written, |
diff --git a/internal/console/store.go b/internal/console/store.go| index ff6039fc9..1a584d62e 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -573,6 +573,7 @@ func (s *Store) migrate() error { |
| // counts against the cap. purge_after/purge_for are fixed at trash |
| // time from whether the row was temporary then; nothing re-derives |
| // them. |
| + `ALTER TABLE apps ADD COLUMN demo_id TEXT NOT NULL DEFAULT '';`, |
| `ALTER TABLE apps ADD COLUMN expires_at INTEGER NOT NULL DEFAULT 0;`, |
| `ALTER TABLE apps ADD COLUMN restoring INTEGER NOT NULL DEFAULT 0;`, |
| `ALTER TABLE apps ADD COLUMN purge_after INTEGER NOT NULL DEFAULT 0;`, |
| @@ -682,6 +683,9 @@ func (s *Store) migrate() error { |
| if err := s.migrateAlerts(); err != nil { |
| return err |
| } |
| + if err := s.migrateDemo(); err != nil { |
| + return err |
| + } |
| return s.migrateDomains() |
| } |
| @@ -778,6 +782,7 @@ func (s *Store) migrateAppsKey() error { |
| purge_after INTEGER NOT NULL DEFAULT 0, |
| purge_for INTEGER NOT NULL DEFAULT 0, |
| lifetime TEXT NOT NULL DEFAULT '', |
| + demo_id TEXT NOT NULL DEFAULT '', |
| PRIMARY KEY (account_id, app) |
| );`, |
| // The ALTERs above run before migrateAppsKey in migrate(), so |
| @@ -791,9 +796,9 @@ func (s *Store) migrateAppsKey() error { |
| // lifetime is carried across, and minted for a row that has none (the |
| // ALTER above adds it empty); randomblob(8) is 16 hex digits, the |
| // same form insertAppRow mints. |
| - `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, lifetime) |
| + `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, lifetime, demo_id) |
| SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, |
| - CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END FROM apps;`, |
| + CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END, demo_id FROM apps;`, |
| `DROP TABLE apps;`, |
| `ALTER TABLE apps_new RENAME TO apps;`, |
| } { |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 03da3023d..51b1a7165 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -188,7 +188,10 @@ var claimAppsTerminal = map[string][]string{ |
| // cannot silently ship ungated. There is deliberately no exemption class: |
| // audit and mail telemetry are app-scoped and are gated like the rest. |
| var claimSQLTables = map[string]claimSQLTable{ |
| - "app_stars": {NonApp: "personal bookmarks keyed by account, address and app lifetime; grants no app authority"}, |
| + "demo_apps": {Account: "account_id", App: "app", Refuse: "anonymous demos require claims mode off"}, |
| + "demo_admissions": {NonApp: "anonymous attempt budget, keyed by salted IP hash and time; names no app"}, |
| + "demo_settings": {NonApp: "deployment salt for anonymous admission; names no app"}, |
| + "app_stars": {NonApp: "personal bookmarks keyed by account, address and app lifetime; grants no app authority"}, |
| // ---- app-scoped: gated ---- |
| "apps": {Account: "account_id", App: "app", AppID: "app_id", Terminal: claimAppsTerminal}, |
| // Legacy per-app grants carry no account column, so a permit for app |
diff --git a/internal/console/tempstore.go b/internal/console/tempstore.go| index a9200211a..bbe9be959 100644 |
| --- a/internal/console/tempstore.go |
| +++ b/internal/console/tempstore.go |
| @@ -23,6 +23,7 @@ const ( |
| // AppLife is one apps row's lifecycle columns, read together because every |
| // temporary-app decision needs them together. Times are Unix seconds. |
| type AppLife struct { |
| + DemoID string |
| AccountID int64 |
| App string |
| CreatedAt int64 |
| @@ -38,12 +39,12 @@ type AppLife struct { |
| func (l *AppLife) Temporary() bool { return l.ExpiresAt > 0 } |
| func (l *AppLife) Trashed() bool { return l.DeletedAt != 0 } |
| -const appLifeCols = `account_id, app, created_at, deleted_at, expires_at, restoring, purge_after, purge_for, control_plane, lifetime` |
| +const appLifeCols = `account_id, app, created_at, deleted_at, expires_at, restoring, purge_after, purge_for, control_plane, lifetime, demo_id` |
| func scanAppLife(sc interface{ Scan(...any) error }) (AppLife, error) { |
| var l AppLife |
| err := sc.Scan(&l.AccountID, &l.App, &l.CreatedAt, &l.DeletedAt, &l.ExpiresAt, &l.Restoring, |
| - &l.PurgeAfter, &l.PurgeFor, &l.ControlPlane, &l.Lifetime) |
| + &l.PurgeAfter, &l.PurgeFor, &l.ControlPlane, &l.Lifetime, &l.DemoID) |
| return l, err |
| } |
diff --git a/internal/demo/config.go b/internal/demo/config.go| new file mode 100644 |
| index 000000000..0f88980c1 |
| --- /dev/null |
| +++ b/internal/demo/config.go |
| @@ -0,0 +1,109 @@ |
| +// Package demo defines the anonymous demo admission contract. |
| +package demo |
| + |
| +import ( |
| + "errors" |
| + "net/netip" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +const ( |
| + SourceMaxBytes = 5_000_000 |
| + MaxUpdateAttempts = 60 |
| + NameAttempts = 16 |
| + AppPrefix = "tmp-demo-" |
| +) |
| + |
| +var ErrConfig = errors.New("DEMO-CONFIG") |
| + |
| +type Config struct { |
| + Enabled bool |
| + Account, Fleet, Domain string |
| + CreatePerIPDay, CreateGlobalDay, MaxLive int |
| + BuildWorker bool |
| + BuildConcurrency int |
| + ToolchainDir string |
| +} |
| + |
| +func LoadConfig(getenv func(string) string) (Config, error) { |
| + c := Config{CreatePerIPDay: 30, CreateGlobalDay: 100, MaxLive: 20, BuildConcurrency: 1} |
| + for key, dst := range map[string]*bool{"CARLOS_DEMO_APPS": &c.Enabled, "CARLOS_DEMO_BUILD_WORKER": &c.BuildWorker} { |
| + switch getenv(key) { |
| + case "": |
| + case "1": |
| + *dst = true |
| + default: |
| + return Config{}, ErrConfig |
| + } |
| + } |
| + c.Account = getenv("CARLOS_DEMO_ACCOUNT") |
| + c.Fleet = getenv("CARLOS_DEMO_FLEET") |
| + c.Domain = getenv("CARLOS_DEMO_DOMAIN") |
| + c.ToolchainDir = getenv("CARLOS_DEMO_TOOLCHAIN_DIR") |
| + for key, dst := 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, "CARLOS_DEMO_BUILD_CONCURRENCY": &c.BuildConcurrency} { |
| + if raw := getenv(key); raw != "" { |
| + n, err := strconv.Atoi(raw) |
| + if err != nil || n <= 0 { |
| + return Config{}, ErrConfig |
| + } |
| + *dst = n |
| + } |
| + } |
| + if err := c.Validate(); err != nil { |
| + return Config{}, err |
| + } |
| + return c, nil |
| +} |
| + |
| +func (c Config) Validate() error { |
| + if c.CreatePerIPDay <= 0 || c.CreateGlobalDay <= 0 || c.MaxLive <= 0 || c.BuildConcurrency < 1 || c.BuildConcurrency > 4 { |
| + return ErrConfig |
| + } |
| + if !c.Enabled && !c.BuildWorker { |
| + return nil |
| + } |
| + if !validLabel(c.Account, 32) || !validLabel(c.Fleet, 32) || !ValidDomain(c.Domain) { |
| + return ErrConfig |
| + } |
| + if c.BuildWorker && !filepath.IsAbs(c.ToolchainDir) { |
| + return ErrConfig |
| + } |
| + return nil |
| +} |
| + |
| +func validLabel(s string, max int) bool { |
| + if len(s) == 0 || len(s) > max || s[0] == '-' || s[len(s)-1] == '-' { |
| + return false |
| + } |
| + for _, b := range []byte(s) { |
| + if (b < 'a' || b > 'z') && (b < '0' || b > '9') && b != '-' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func ValidDomain(s string) bool { |
| + if len(s) > 253 || !strings.Contains(s, ".") { |
| + return false |
| + } |
| + if _, err := netip.ParseAddr(s); err == nil { |
| + return false |
| + } |
| + for _, label := range strings.Split(s, ".") { |
| + if !validLabel(label, 63) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func CanonicalIP(s string) (string, error) { |
| + addr, err := netip.ParseAddr(s) |
| + if err != nil || addr.Zone() != "" { |
| + return "", errors.New("demo: invalid IP") |
| + } |
| + return addr.Unmap().String(), nil |
| +} |
diff --git a/internal/demo/config_test.go b/internal/demo/config_test.go| new file mode 100644 |
| index 000000000..a5181c0f2 |
| --- /dev/null |
| +++ b/internal/demo/config_test.go |
| @@ -0,0 +1,86 @@ |
| +package demo |
| + |
| +import ( |
| + "bytes" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestDemoConfigOff(t *testing.T) { |
| + cfg, err := LoadConfig(func(string) string { return "" }) |
| + if err != nil || cfg.Enabled || cfg.BuildWorker { |
| + t.Fatalf("off: %+v %v", cfg, err) |
| + } |
| + env := map[string]string{"CARLOS_DEMO_APPS": "1"} |
| + get := func(k string) string { return env[k] } |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Fatal("partial enabled config accepted") |
| + } |
| + env["CARLOS_DEMO_ACCOUNT"] = "shop" |
| + env["CARLOS_DEMO_FLEET"] = "demo" |
| + env["CARLOS_DEMO_DOMAIN"] = "demo.example.com" |
| + cfg, err = LoadConfig(get) |
| + if err != nil || !cfg.Enabled || cfg.CreatePerIPDay != 30 || cfg.CreateGlobalDay != 100 || cfg.MaxLive != 20 || cfg.BuildConcurrency != 1 { |
| + t.Fatalf("defaults: %+v %v", cfg, err) |
| + } |
| + for key, value := range map[string]string{"CARLOS_DEMO_APPS": "true", "CARLOS_DEMO_CREATE_PER_IP_DAY": "0", "CARLOS_DEMO_CREATE_GLOBAL_DAY": "-1", "CARLOS_DEMO_MAX_LIVE": "bad", "CARLOS_DEMO_BUILD_CONCURRENCY": "5", "CARLOS_DEMO_DOMAIN": "https://example.com"} { |
| + old := env[key] |
| + env[key] = value |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Errorf("accepted %s=%s", key, value) |
| + } |
| + env[key] = old |
| + } |
| + env["CARLOS_DEMO_BUILD_WORKER"] = "1" |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Fatal("worker without bundle accepted") |
| + } |
| + env["CARLOS_DEMO_TOOLCHAIN_DIR"] = "relative" |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Fatal("relative bundle accepted") |
| + } |
| + env["CARLOS_DEMO_TOOLCHAIN_DIR"] = "/opt/demo-toolchain" |
| + if _, err := LoadConfig(get); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestDemoIdentity(t *testing.T) { |
| + if len(adjectives) != 128 || len(nouns) != 128 { |
| + t.Fatalf("word counts %d %d", len(adjectives), len(nouns)) |
| + } |
| + for _, words := range [][]string{adjectives[:], nouns[:]} { |
| + seen := map[string]bool{} |
| + for _, word := range words { |
| + if len(word) > 8 || len(word) == 0 || seen[word] || strings.Trim(word, "abcdefghijklmnopqrstuvwxyz") != "" { |
| + t.Errorf("word %q", word) |
| + } |
| + seen[word] = true |
| + } |
| + } |
| + ids := map[string]bool{} |
| + for range 100 { |
| + id, err := NewIdentity(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(id.Token) |
| + if err != nil || len(raw) != 32 || id.TokenHash != sha256.Sum256(raw) { |
| + t.Fatal("token encoding/hash") |
| + } |
| + rawID, err := base64.RawURLEncoding.DecodeString(id.ID) |
| + if err != nil || len(rawID) != 16 || ids[id.ID] { |
| + t.Fatal("demo ID") |
| + } |
| + ids[id.ID] = true |
| + if id.App != "tmp-demo-"+id.Name || !ValidPublicName(id.Name) || len(id.App) > 32 { |
| + t.Fatalf("name %+v", id) |
| + } |
| + } |
| + if _, err := NewIdentity(bytes.NewReader(nil)); err == nil { |
| + t.Fatal("entropy failure ignored") |
| + } |
| +} |
diff --git a/internal/demo/identity.go b/internal/demo/identity.go| new file mode 100644 |
| index 000000000..31341a3a6 |
| --- /dev/null |
| +++ b/internal/demo/identity.go |
| @@ -0,0 +1,59 @@ |
| +package demo |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "fmt" |
| + "io" |
| + "math/big" |
| + "strings" |
| +) |
| + |
| +type Identity struct { |
| + ID, Name, App string |
| + Token string `json:"-"` |
| + TokenHash [32]byte `json:"-"` |
| +} |
| + |
| +func NewIdentity(r io.Reader) (Identity, error) { |
| + var id Identity |
| + raw := make([]byte, 16) |
| + if _, err := io.ReadFull(r, raw); err != nil { |
| + return id, err |
| + } |
| + id.ID = base64.RawURLEncoding.EncodeToString(raw) |
| + raw = make([]byte, 32) |
| + if _, err := io.ReadFull(r, raw); err != nil { |
| + return Identity{}, err |
| + } |
| + id.Token = base64.RawURLEncoding.EncodeToString(raw) |
| + id.TokenHash = sha256.Sum256(raw) |
| + values := [3]int64{} |
| + for i, n := range []int64{128, 128, 100} { |
| + v, err := rand.Int(r, big.NewInt(n)) |
| + if err != nil { |
| + return Identity{}, err |
| + } |
| + values[i] = v.Int64() |
| + } |
| + id.Name = fmt.Sprintf("%s-%s-%02d", adjectives[values[0]], nouns[values[1]], values[2]) |
| + id.App = AppPrefix + id.Name |
| + return id, nil |
| +} |
| + |
| +func ValidPublicName(s string) bool { |
| + parts := strings.Split(s, "-") |
| + if len(parts) != 3 || len(parts[2]) != 2 || parts[2][0] < '0' || parts[2][0] > '9' || parts[2][1] < '0' || parts[2][1] > '9' { |
| + return false |
| + } |
| + found := func(words []string, w string) bool { |
| + for _, v := range words { |
| + if v == w { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + return found(adjectives[:], parts[0]) && found(nouns[:], parts[1]) |
| +} |
diff --git a/internal/demo/names.go b/internal/demo/names.go| new file mode 100644 |
| index 000000000..f14fd7344 |
| --- /dev/null |
| +++ b/internal/demo/names.go |
| @@ -0,0 +1,40 @@ |
| +package demo |
| + |
| +// These benign words are part of the public name format. Keep each at eight |
| +// letters or fewer so the internal name fits the existing app-name limit. |
| +var adjectives = [...]string{ |
| + "able", "active", "airy", "amber", "ample", "apricot", "aqua", "arctic", |
| + "autumn", "azure", "balmy", "beaming", "blissful", "blue", "bouncy", "brave", |
| + "breezy", "bright", "brisk", "bubbly", "calm", "candid", "careful", "cheery", |
| + "cherry", "chilly", "clear", "clever", "cloudy", "coastal", "comfy", "cool", |
| + "coral", "cosmic", "cozy", "crisp", "curious", "dainty", "dapper", "dawn", |
| + "decent", "dewy", "downy", "dreamy", "eager", "early", "earthy", "easy", |
| + "emerald", "even", "fair", "fancy", "fern", "fine", "floral", "fluffy", |
| + "foamy", "fond", "fresh", "friendly", "frosty", "gentle", "glad", "gleaming", |
| + "golden", "graceful", "grand", "grassy", "green", "happy", "hazy", "hearty", |
| + "helpful", "honey", "humble", "icy", "indigo", "ivory", "jade", "jaunty", |
| + "jolly", "joyful", "keen", "kind", "leafy", "light", "lilac", "lively", |
| + "lovely", "lucky", "lunar", "mellow", "merry", "mild", "minty", "misty", |
| + "modest", "mossy", "neat", "nimble", "noble", "opal", "orange", "pastel", |
| + "peachy", "pearly", "placid", "playful", "plucky", "polite", "proud", "quiet", |
| + "rosy", "round", "sandy", "serene", "shiny", "silver", "snowy", "soft", |
| + "solar", "spring", "steady", "sunny", "tidy", "vivid", "warm", "witty", |
| +} |
| +var nouns = [...]string{ |
| + "acorn", "alpaca", "apple", "aspen", "badger", "bamboo", "barley", "bay", |
| + "beacon", "bean", "bear", "beaver", "beech", "berry", "birch", "bird", |
| + "blossom", "bluebell", "boat", "bobcat", "brook", "bubble", "bud", "bunny", |
| + "butter", "button", "cactus", "camel", "candle", "canoe", "carrot", "cedar", |
| + "chick", "clover", "cloud", "cocoa", "comet", "cookie", "coral", "cosmos", |
| + "crane", "creek", "cricket", "daisy", "deer", "dolphin", "dove", "drake", |
| + "duck", "dune", "elm", "falcon", "fawn", "feather", "fern", "finch", |
| + "fir", "firefly", "flower", "forest", "fox", "frog", "garden", "gecko", |
| + "glade", "goat", "goose", "grove", "gull", "harbor", "hare", "hazel", |
| + "hedgehog", "heron", "hill", "honey", "iris", "island", "ivy", "jasmine", |
| + "juniper", "kiwi", "koala", "lake", "lamb", "lark", "leaf", "lemon", |
| + "lily", "lotus", "lynx", "maple", "meadow", "melon", "mint", "moon", |
| + "moss", "mouse", "nest", "oak", "ocean", "olive", "orchid", "otter", |
| + "owl", "panda", "peach", "pearl", "pebble", "penguin", "petal", "pine", |
| + "plum", "pond", "poppy", "puffin", "quail", "rabbit", "reed", "robin", |
| + "shell", "sparrow", "spruce", "star", "swan", "turtle", "whale", "willow", |
| +} |