feat: expire and promptly purge anonymous demos
34 files changed,
+1,923
−63
internal/console/apidemo.go+13 −7internal/console/apidemobox.go+14 −2internal/console/claim_invariant_test.go+6 −4internal/console/demo_expiry.go+353 −0internal/console/demo_expiry_test.go+336 −0internal/console/demo_gate_test.go+6 −0internal/console/demo_store.go+29 −5internal/console/expirypass.go+3 −2internal/console/lifetimes_purge.go+5 −2internal/console/settle.go+3 −0internal/console/store.go+3 −3internal/console/store_gate.go+2 −0internal/console/tempstore.go+5 −5internal/demobuild/job.go+3 −2internal/demobuild/purge.go+92 −0internal/demobuild/retirement.go+62 −0internal/demobuild/retirement_test.go+96 −0internal/demobuild/worker.go+35 −19internal/host/agent.go+3 −1internal/host/claimstop_run.go+35 −1internal/host/claimunit.go+1 −0internal/host/demo_cleanup.go+117 −0internal/host/demo_cleanup_test.go+107 −0internal/host/demo_jobs.go+16 −2internal/instancectl/demo_cleanup.go+227 −0internal/instancectl/demo_cleanup_test.go+154 −0internal/instancectl/demo_policy.go+13 −0internal/instancectl/demo_versions.go+100 −0internal/instancectl/rootfs.go+5 −2internal/instancectl/server.go+28 −4internal/provision/demo_census_test.go+5 −0internal/provision/demo_routing_test.go+36 −0internal/provision/reconcile.go+5 −0internal/release/trash.go+5 −2
CI failed — run details
Intent
Attributed to this commit: 28.4 g CO₂e (3,596,580 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 4fe69305e..8c8f0e350 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -28,6 +28,7 @@ import ( |
| // DEMO-LIVE-LIMIT uses a read-only pre-check before spending an attempt and |
| // a five-minute retry; ReserveDemo still enforces the ceiling transactionally. |
| var demoCopy = map[string]string{ |
| + "DEMO-EXPIRED": "This demo has expired and is being permanently removed.", |
| "DEMO-POLICY": "This operation is not available for anonymous demos. Their restrictions and 24-hour expiry cannot be changed.", |
| "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.", |
| @@ -246,9 +247,10 @@ func (s *Server) demoAdmissionReady(ctx context.Context) error { |
| } |
| func (s *Server) registerDemoRoutes() { |
| - if !s.cfg.Demo.Enabled { |
| + if !s.cfg.Demo.Enabled && !s.cfg.Demo.BoxMode() { |
| return |
| } |
| + s.registerRoute("POST /api/box/demo-retirements/ack", s.handleDemoRetirementAck) |
| s.registerRoute("POST /api/demo/apps", s.handleDemoPublish) |
| s.registerRoute("GET /api/box/demo-builds", s.handleDemoBuildStream) |
| s.registerRoute("POST /api/box/demo-builds/{jobID}/pickup", s.handleDemoPickup) |
| @@ -470,10 +472,6 @@ func (l *demoStatusLimiter) allow(ip string, now time.Time) bool { |
| 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"]) |
| @@ -493,6 +491,11 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, 404, demoCopy["DEMO-NOT-FOUND"]) |
| return |
| } |
| + d, err := s.store.demoByID(r.Context(), row.Job.DemoID) |
| + if err == nil && d.State != "anonymous" { |
| + jsonError(w, 410, demoCopy["DEMO-EXPIRED"]) |
| + return |
| + } |
| state := "failed" |
| currentJob := false |
| if err := s.withDemoLocked(r.Context(), row.Job.DemoID, func(d DemoRow, life AppLife) error { |
| @@ -601,6 +604,9 @@ func (s *Server) checkDemoFreshName(ctx context.Context, acct *Account, name str |
| // reserveFreshDemo retries collisions under the account/app locks. ReserveDemo |
| // writes the job and its outbox in the admission transaction. |
| func (s *Server) reserveFreshDemo(ctx context.Context, in DemoAdmission) (DemoRow, demo.Identity, error) { |
| + return s.reserveFreshDemoWith(ctx, in, func() (demo.Identity, error) { return demo.NewIdentity(rand.Reader) }) |
| +} |
| +func (s *Server) reserveFreshDemoWith(ctx context.Context, in DemoAdmission, generate func() (demo.Identity, error)) (DemoRow, demo.Identity, error) { |
| var zero DemoRow |
| acct, err := s.store.AccountBySqid(in.Config.Account) |
| if err != nil { |
| @@ -613,7 +619,7 @@ func (s *Server) reserveFreshDemo(ctx context.Context, in DemoAdmission) (DemoRo |
| ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| defer cancel() |
| for range demo.NameAttempts { |
| - id, err := demo.NewIdentity(rand.Reader) |
| + id, err := generate() |
| if err != nil { |
| return zero, demo.Identity{}, err |
| } |
| @@ -635,5 +641,5 @@ func (s *Server) reserveFreshDemo(ctx context.Context, in DemoAdmission) (DemoRo |
| } |
| return row, id, err |
| } |
| - return zero, demo.Identity{}, ErrDemoNameTaken |
| + return zero, demo.Identity{}, ErrDemoLiveLimit |
| } |
diff --git a/internal/console/apidemobox.go b/internal/console/apidemobox.go| index 3638a2532..a115e255f 100644 |
| --- a/internal/console/apidemobox.go |
| +++ b/internal/console/apidemobox.go |
| @@ -28,7 +28,7 @@ type demoPeer struct { |
| func (p *demoPeer) box() string { _, box, _ := strings.Cut(p.name, "/"); return box } |
| func (s *Server) demoPeerOK(p *demoPeer) bool { |
| - if !s.cfg.Demo.Enabled || s.cfg.HostClaim || !p.ready.Valid() || time.Since(p.seen) > 30*time.Second { |
| + if !s.cfg.Demo.BoxMode() || s.cfg.HostClaim || !p.ready.Valid() || time.Since(p.seen) > 30*time.Second { |
| return false |
| } |
| reg, err := openRegistry(s.cfg.Registry) |
| @@ -91,7 +91,7 @@ func (s *Server) revalidateDemoPeers() { |
| } |
| } |
| func (s *Server) demoBoxAuth(r *http.Request) (name, token string, ok bool) { |
| - if !s.cfg.Demo.Enabled || s.cfg.HostClaim { |
| + if !s.cfg.Demo.BoxMode() || s.cfg.HostClaim { |
| return "", "", false |
| } |
| if len(r.Header.Values("Authorization")) != 1 || len(r.Header.Values("Carlos-Tunnel-Name")) != 1 { |
| @@ -197,9 +197,21 @@ func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer) error { |
| _ = p.ws.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| return websocket.JSON.Send(p.ws, m) |
| } |
| + retirements, err := s.pendingDemoRetirements(ctx, p.name) |
| + if err != nil { |
| + return err |
| + } |
| + for _, wire := range retirements { |
| + if err := send(demobuild.StreamMessage{Retirement: wire}); err != nil { |
| + return err |
| + } |
| + } |
| if err := send(demobuild.StreamMessage{Reconcile: hint}); err != nil { |
| return err |
| } |
| + if !s.cfg.Demo.Enabled { |
| + return nil |
| + } |
| rows, err := s.store.db.QueryContext(ctx, `SELECT j.id FROM demo_jobs j WHERE j.box=? AND j.state='queued' AND NOT EXISTS (SELECT 1 FROM demo_job_outbox o WHERE o.job_id=j.id) ORDER BY j.deadline LIMIT ?`, p.box(), demobuild.QueueLimit) |
| if err != nil { |
| return err |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index f6655379a..c1a65af30 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -182,10 +182,12 @@ type claimWindow struct { |
| // every writer is reached. A new boundary method or gated table fails the |
| // coverage step until a door reaches it or a reason is written here. |
| var claimWriterReasons = map[string]string{ |
| - "sql/demo_apps": "anonymous demo admission refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| - "sql/demo_jobs": "anonymous demo build work refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| - "sql/demo_job_outbox": "anonymous demo dispatch refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| - "bucket/PutFrom": "the only console streaming caller is geoippublish.go, which writes deployment GeoIP blobs, not app state; app-prefixed fallback writes are checked by Put and the streaming new-door witness", |
| + "sql/demo_retirements": "anonymous demo retirement refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_host_tombstones": "anonymous demo host reservation refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_apps": "anonymous demo admission refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_jobs": "anonymous demo build work refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_job_outbox": "anonymous demo dispatch refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "bucket/PutFrom": "the only console streaming caller is geoippublish.go, which writes deployment GeoIP blobs, not app state; app-prefixed fallback writes are checked by Put and the streaming new-door witness", |
| "bucket/Delete": "the data boundary never sends an unconditional delete: Delete reads the exact revision, " + |
| "authorizes it and issues DeleteIfMatch, which bucket/DeleteIfMatch counts", |
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go| new file mode 100644 |
| index 000000000..72c5f6f7f |
| --- /dev/null |
| +++ b/internal/console/demo_expiry.go |
| @@ -0,0 +1,353 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func (s *Store) migrateDemoRetirement() error { |
| + // SQLite cannot drop a NOT NULL constraint. Preserve the complete existing |
| + // schema and rows while permitting a retired credential to become NULL. |
| + var ddl string |
| + if err := s.db.QueryRow(`SELECT sql FROM sqlite_master WHERE name='demo_apps'`).Scan(&ddl); err != nil { |
| + return err |
| + } |
| + if strings.Contains(ddl, "claim_token_hash BLOB NOT NULL") { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + ddl = strings.Replace(ddl, "demo_apps", "demo_apps_nullable", 1) |
| + ddl = strings.Replace(ddl, "claim_token_hash BLOB NOT NULL", "claim_token_hash BLOB", 1) |
| + for _, q := range []string{ddl, `INSERT INTO demo_apps_nullable SELECT * FROM demo_apps`, `DROP TABLE demo_apps`, `ALTER TABLE demo_apps_nullable RENAME TO demo_apps`} { |
| + if _, err = tx.Exec(q); err != nil { |
| + return err |
| + } |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + } |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS demo_host_tombstones(host TEXT PRIMARY KEY, demo_id TEXT NOT NULL, purged_at INTEGER NOT NULL); |
| + CREATE TABLE IF NOT EXISTS demo_retirements(demo_id TEXT PRIMARY KEY, wire BLOB NOT NULL, delivered INTEGER NOT NULL DEFAULT 0, acknowledged INTEGER NOT NULL DEFAULT 0, purging INTEGER NOT NULL DEFAULT 0, initialized_clean INTEGER NOT NULL DEFAULT 0);`) |
| + return err |
| +} |
| + |
| +type demoRetirementRow struct { |
| + Wire []byte |
| + Delivered, Acknowledged, Purging, InitializedClean bool |
| +} |
| + |
| +func (s *Server) demoRetirement(ctx context.Context, id string) (demoRetirementRow, error) { |
| + var r demoRetirementRow |
| + err := s.store.db.QueryRowContext(ctx, `SELECT wire,delivered,acknowledged,purging,initialized_clean FROM demo_retirements WHERE demo_id=?`, id).Scan(&r.Wire, &r.Delivered, &r.Acknowledged, &r.Purging, &r.InitializedClean) |
| + return r, err |
| +} |
| + |
| +func (s *Server) expireDemos(ctx context.Context, now time.Time, evidence bool) { |
| + if s.cfg.Releases == nil || s.cfg.HostClaim { |
| + return |
| + } |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT demo_id FROM demo_apps WHERE purged_at=0`) |
| + if err != nil { |
| + jobFailed(ctx, err) |
| + return |
| + } |
| + var ids []string |
| + for rows.Next() { |
| + var id string |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + ids = append(ids, id) |
| + } |
| + err = errors.Join(err, rows.Err(), rows.Close()) |
| + if err != nil { |
| + jobFailed(ctx, err) |
| + return |
| + } |
| + if len(ids) == 0 { |
| + return |
| + } |
| + for _, id := range ids { |
| + d, err := s.store.demoByID(ctx, id) |
| + if err != nil { |
| + jobFailed(ctx, err) |
| + continue |
| + } |
| + func() { |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + if d.State == "anonymous" && !evidence { |
| + return |
| + } |
| + if err := s.expireDemoLocked(ctx, d, now); err != nil { |
| + jobFailed(ctx, err) |
| + } |
| + }() |
| + } |
| +} |
| + |
| +// expireDemoLocked shares publication's app mutex. The SQL fence commits |
| +// before any retirement object; retries retain its original signed lifetime. |
| +func (s *Server) expireDemoLocked(ctx context.Context, d DemoRow, now time.Time) error { |
| + var err error |
| + d, err = s.store.demoByID(ctx, d.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if d.PurgedAt != 0 { |
| + return nil |
| + } |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + if life == nil || life.DemoID != d.ID || life.ControlPlane || life.Restoring { |
| + return demo.ErrPolicy |
| + } |
| + if now.Unix() < life.ExpiresAt { |
| + return nil |
| + } |
| + r, err := s.demoRetirement(ctx, d.ID) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + receipt := demobuild.Retirement{Demo: demo.Descriptor{ID: d.ID, Host: d.Host, Lifetime: life.Lifetime, ExpiresAt: life.ExpiresAt}, Account: d.AccountSqid, App: d.App, Fleet: d.Fleet, Box: d.AssignedBox, Tombstone: now.Unix()} |
| + jobs, err := s.store.db.QueryContext(ctx, `SELECT id FROM demo_jobs WHERE demo_id=? ORDER BY id`, d.ID) |
| + if err != nil { |
| + return err |
| + } |
| + for jobs.Next() { |
| + var id string |
| + if err = jobs.Scan(&id); err != nil { |
| + break |
| + } |
| + receipt.Jobs = append(receipt.Jobs, id) |
| + } |
| + err = errors.Join(err, jobs.Err(), jobs.Close()) |
| + if err != nil { |
| + return err |
| + } |
| + r.Wire, err = demobuild.SignRetirement(s.cfg.Key, receipt) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO demo_retirements(demo_id,wire,acknowledged,initialized_clean) VALUES(?,?,?,?)`, d.ID, r.Wire, d.AssignedBox == "", d.AssignedBox == ""); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET state='retiring',generation=generation+1,claim_token_hash=NULL,active_job_id='' WHERE demo_id=? AND state='anonymous'`, d.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_jobs SET state='failed',publish_stage='retired' WHERE demo_id=?`, d.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_job_outbox WHERE job_id IN (SELECT id FROM demo_jobs WHERE demo_id=?)`, d.ID); err != nil { |
| + return err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + r.Acknowledged = d.AssignedBox == "" |
| + r.InitializedClean = r.Acknowledged |
| + } else if err != nil { |
| + return err |
| + } |
| + receipt, err := demobuild.VerifyRetirement(s.cfg.ReleasePub, r.Wire) |
| + if err != nil { |
| + return err |
| + } |
| + if receipt.Demo.Lifetime != life.Lifetime || receipt.Demo.ID != d.ID || receipt.Demo.Host != d.Host { |
| + return demo.ErrPolicy |
| + } |
| + if err = s.cleanDemoSpools(ctx, false); err != nil { |
| + return err |
| + } |
| + tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, d.AccountSqid, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + if tomb == nil && r.Purging { |
| + // A committed deletion followed by an interrupted SQL write can finish, |
| + // after the contents-purged SQL checkpoint and a readable empty prefix. |
| + keys, err := s.cfg.Releases.List(ctx, release.AppPrefix(d.AccountSqid, d.App)) |
| + if err != nil { |
| + return err |
| + } |
| + if len(keys) != 0 { |
| + return errNoMarker |
| + } |
| + return s.finishDemoPurge(ctx, d, now) |
| + } |
| + at := time.Unix(receipt.Tombstone, 0) |
| + if tomb == nil { |
| + if r.Delivered { |
| + return errNoMarker |
| + } |
| + if err = release.TrashApp(ctx, s.cfg.Releases, d.AccountSqid, d.App, expiryActor, at); err != nil { |
| + return err |
| + } |
| + tomb, err = release.ReadAppTombstone(ctx, s.cfg.Releases, d.AccountSqid, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + if tomb == nil || tomb.DeletedAt.Unix() != receipt.Tombstone { |
| + return release.ErrTrashClockMismatch |
| + } |
| + if _, err = s.store.ExpireAppRowContext(ctx, d.AccountID, d.App, at); err != nil { |
| + return err |
| + } |
| + if !r.Delivered { |
| + if err = s.putDemoObject(ctx, release.AppPrefix(d.AccountSqid, d.App)+"demo-retire.json", r.Wire, false); err != nil { |
| + return err |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_retirements SET delivered=1 WHERE demo_id=?`, d.ID); err != nil { |
| + return err |
| + } |
| + } |
| + s.bumpSerial(ctx) |
| + s.NotifyDemoBox(d.AssignedBox) |
| + if !r.Acknowledged || !r.InitializedClean { |
| + return nil |
| + } |
| + if estate, err := s.mailEstate(ctx, &Account{ID: d.AccountID, Sqid: d.AccountSqid}, d.App); err != nil { |
| + return err |
| + } else if estate { |
| + return demo.ErrPolicy |
| + } |
| + if err = release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, at, now); err != nil { |
| + return err |
| + } |
| + if !r.Purging { |
| + // Keep the matching marker until SQL records successful content removal. |
| + // No absence-based inference is needed if final row deletion then fails. |
| + if lifetimesUnit(ctx) { |
| + err = s.purgeAppWithLifetimes(ctx, d.AccountSqid, d.App, at, now, true) |
| + } else { |
| + err = release.PurgeAppExcept(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, at, now, func(key string) bool { return key == release.AppTombstoneKey(d.AccountSqid, d.App) }) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_retirements SET purging=1 WHERE demo_id=? AND acknowledged=1 AND initialized_clean=1`, d.ID); err != nil { |
| + return err |
| + } |
| + } |
| + if err = s.cfg.Releases.Delete(ctx, release.AppTombstoneKey(d.AccountSqid, d.App)); err != nil { |
| + return err |
| + } |
| + return s.finishDemoPurge(ctx, d, now) |
| +} |
| + |
| +func (s *Server) finishDemoPurge(ctx context.Context, d DemoRow, now time.Time) error { |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + for _, q := range []struct { |
| + sql string |
| + args []any |
| + }{ |
| + {`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,?) ON CONFLICT(host) DO NOTHING`, []any{d.Host, d.ID, now.Unix()}}, |
| + {`DELETE FROM apps WHERE account_id=? AND app=? AND demo_id=? AND deleted_at!=0`, []any{d.AccountID, d.App, d.ID}}, |
| + {`UPDATE demo_apps SET state='retired',purged_at=? WHERE demo_id=?`, []any{now.Unix(), d.ID}}, |
| + {`DELETE FROM demo_retirements WHERE demo_id=?`, []any{d.ID}}, |
| + } { |
| + if _, err = tx.ExecContext(ctx, q.sql, q.args...); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +func (s *Server) ackDemoRetirement(ctx context.Context, name string, wire []byte) error { |
| + receipt, err := demobuild.VerifyRetirement(s.cfg.ReleasePub, wire) |
| + if err != nil { |
| + return err |
| + } |
| + if receipt.Box == "" || name != receipt.Fleet+"/"+receipt.Box { |
| + return demo.ErrPolicy |
| + } |
| + d, err := s.store.demoByID(ctx, receipt.Demo.ID) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + r, err := s.demoRetirement(ctx, d.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if !r.Delivered || !bytes.Equal(r.Wire, wire) || d.AssignedBox != receipt.Box { |
| + return demo.ErrPolicy |
| + } |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_retirements SET acknowledged=1 WHERE demo_id=?`, d.ID) |
| + return err |
| +} |
| +func (s *Server) handleDemoRetirementAck(w http.ResponseWriter, r *http.Request) { |
| + name, _, ok := s.demoBoxAuth(r) |
| + if !ok { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + defer r.Body.Close() |
| + b, err := io.ReadAll(io.LimitReader(r.Body, demobuild.MaxJobWire+1)) |
| + if err != nil || s.ackDemoRetirement(r.Context(), name, b) != nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if r.URL.Query().Get("complete") == "1" { |
| + if err = s.completeDemoRetirement(r.Context(), name, b); err != nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +func (s *Server) pendingDemoRetirements(ctx context.Context, name string) ([][]byte, error) { |
| + fleet, box, ok := strings.Cut(name, "/") |
| + if !ok { |
| + return nil, demo.ErrPolicy |
| + } |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT r.wire FROM demo_retirements r JOIN demo_apps d ON d.demo_id=r.demo_id WHERE d.fleet=? AND d.assigned_box=? AND r.delivered=1 AND r.initialized_clean=0 ORDER BY d.created_at`, fleet, box) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out [][]byte |
| + for rows.Next() { |
| + var b []byte |
| + if err = rows.Scan(&b); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, b) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func (s *Server) completeDemoRetirement(ctx context.Context, name string, wire []byte) error { |
| + if err := s.ackDemoRetirement(ctx, name, wire); err != nil { |
| + return err |
| + } |
| + r, err := demobuild.VerifyRetirement(s.cfg.ReleasePub, wire) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_retirements SET initialized_clean=1 WHERE demo_id=? AND acknowledged=1`, r.Demo.ID) |
| + return err |
| +} |
diff --git a/internal/console/demo_expiry_test.go b/internal/console/demo_expiry_test.go| new file mode 100644 |
| index 000000000..e6790fa4d |
| --- /dev/null |
| +++ b/internal/console/demo_expiry_test.go |
| @@ -0,0 +1,336 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestDemoExpiryRaces(t *testing.T) { |
| + s, d, j, out := demoPublishFixture(t) |
| + life, _ := s.store.AppLife(d.AccountID, d.App) |
| + if life.ExpiresAt != d.CreatedAt+86400 { |
| + t.Fatal("expiry drift") |
| + } |
| + now := time.Unix(life.ExpiresAt, 0) |
| + if err := s.store.SpendDemoUpdate(t.Context(), d.ID, now); !errors.Is(err, ErrDemoToken) { |
| + t.Fatalf("update at expiry: %v", err) |
| + } |
| + s.cfg.Demo.Enabled = false |
| + s.expiryPass(t.Context(), now) |
| + got, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil || got.State != "retiring" || got.Generation != d.Generation+1 { |
| + t.Fatalf("retirement: %+v %v", got, err) |
| + } |
| + life, _ = s.store.AppLife(d.AccountID, d.App) |
| + if life.PurgeAfter != life.DeletedAt || life.DeletedAt != now.Unix() { |
| + t.Fatalf("prompt purge: %+v", life) |
| + } |
| + var hash []byte |
| + if err = s.store.db.QueryRow(`SELECT claim_token_hash FROM demo_apps WHERE demo_id=?`, d.ID).Scan(&hash); err != nil || len(hash) != 0 { |
| + t.Fatalf("token not wiped: %v", err) |
| + } |
| + if err = s.publishDemo(t.Context(), d, j, out); err == nil { |
| + t.Fatal("late result published") |
| + } |
| + if ok, err := s.store.KeepApp(d.AccountID, d.App); err != nil || ok { |
| + t.Fatalf("keep: %v %v", ok, err) |
| + } |
| + if ok, err := s.store.SetRestoring(d.AccountID, d.App, true); err != nil || ok { |
| + t.Fatalf("restore: %v %v", ok, err) |
| + } |
| + req := httptest.NewRequest("GET", "/api/demo/jobs/"+j.ID, nil) |
| + req.RemoteAddr = "192.0.2.1:1234" |
| + req.SetPathValue("jobID", j.ID) |
| + w := httptest.NewRecorder() |
| + s.handleDemoStatus(w, req) |
| + if w.Code != 410 { |
| + t.Fatalf("status=%d %s", w.Code, w.Body.String()) |
| + } |
| + if _, err = s.store.CreateTemporaryAppIn(d.AccountID, "tmp-shop", "test", now, now.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.ExpireAppRow(d.AccountID, "tmp-shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + ordinary, _ := s.store.AppLife(d.AccountID, "tmp-shop") |
| + if ordinary.PurgeAfter-ordinary.DeletedAt != 3*86400 { |
| + t.Fatalf("ordinary grace: %+v", ordinary) |
| + } |
| +} |
| + |
| +func TestDemoPurgeRecovery(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + life, _ := s.store.AppLife(d.AccountID, d.App) |
| + now := time.Unix(life.ExpiresAt, 0) |
| + s.expiryPass(t.Context(), now) |
| + r, err := s.demoRetirement(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.ackDemoRetirement(t.Context(), d.Fleet+"/wrong", r.Wire); err == nil { |
| + t.Fatal("wrong box ack") |
| + } |
| + if err = s.ackDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, r.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A local acknowledgment alone retains the slot and initialization proof. |
| + s.expiryPass(t.Context(), now.Add(time.Second)) |
| + held, _ := s.store.demoByID(t.Context(), d.ID) |
| + if held.PurgedAt != 0 { |
| + t.Fatal("slot released before initialization cleanup") |
| + } |
| + if err = s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, r.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A different marker must never authorize deletion. |
| + if err = s.cfg.Releases.Delete(t.Context(), release.AppTombstoneKey(d.AccountSqid, d.App)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = release.TrashApp(t.Context(), s.cfg.Releases, d.AccountSqid, d.App, "test", now.Add(time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.expiryPass(t.Context(), now.Add(time.Minute)) |
| + after, _ := s.store.demoByID(t.Context(), d.ID) |
| + if after.PurgedAt != 0 { |
| + t.Fatal("wrong marker purged") |
| + } |
| + if err = s.cfg.Releases.Delete(t.Context(), release.AppTombstoneKey(d.AccountSqid, d.App)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = release.TrashApp(t.Context(), s.cfg.Releases, d.AccountSqid, d.App, "test", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.expiryPass(t.Context(), now.Add(2*time.Minute)) |
| + after, _ = s.store.demoByID(t.Context(), d.ID) |
| + if after.PurgedAt == 0 { |
| + t.Fatal("matching purge did not finish") |
| + } |
| + var host, id string |
| + var at int64 |
| + if err = s.store.db.QueryRow(`SELECT host,demo_id,purged_at FROM demo_host_tombstones WHERE host=?`, d.Host).Scan(&host, &id, &at); err != nil || id != d.ID || at == 0 { |
| + t.Fatalf("permanent tombstone: %v", err) |
| + } |
| + keys, err := s.cfg.Releases.List(t.Context(), release.AppPrefix(d.AccountSqid, d.App)) |
| + if err != nil || len(keys) != 0 { |
| + t.Fatalf("objects remain: %v %v", keys, err) |
| + } |
| + if err = s.store.WipeDemoAbuse(t.Context(), now.Add(8*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.demoByID(t.Context(), d.ID); !errors.Is(err, sql.ErrNoRows) { |
| + t.Fatalf("history retained: %v", err) |
| + } |
| + in := demoTestAdmission(t, s.cfg.Demo) |
| + in.AccountSqid = d.AccountSqid |
| + in.Identity.Name = d.Name |
| + in.Identity.App = d.App |
| + in.Host = d.Host |
| + if _, err = s.store.ReserveDemo(t.Context(), in); !errors.Is(err, ErrDemoNameTaken) { |
| + t.Fatalf("purged host handed out again: %v", err) |
| + } |
| + |
| +} |
| + |
| +func TestDemoPurgedHostNeverReused(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + cfg := demoTestConfig(t) |
| + in := demoTestAdmission(t, cfg) |
| + if _, err := st.db.Exec(`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,?)`, in.Host, "previous", time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.ReserveDemo(t.Context(), in); !errors.Is(err, ErrDemoNameTaken) { |
| + t.Fatalf("purged host reused: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoDenseTombstoneRetries(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + cfg := s.cfg.Demo |
| + candidates := make([]demo.Identity, 16) |
| + for i := range candidates { |
| + candidates[i] = demoTestAdmission(t, cfg).Identity |
| + if _, err := s.store.db.Exec(`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,1)`, candidates[i].Name+"."+cfg.Domain, candidates[i].ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + fresh := demoTestAdmission(t, cfg).Identity |
| + for _, exhaust := range []bool{false, true} { |
| + calls := 0 |
| + gen := func() (demo.Identity, error) { |
| + i := calls |
| + calls++ |
| + if !exhaust && i == 15 { |
| + return fresh, nil |
| + } |
| + return candidates[i], nil |
| + } |
| + in := demoTestAdmission(t, cfg) |
| + _, id, err := s.reserveFreshDemoWith(t.Context(), in, gen) |
| + if calls != 16 { |
| + t.Fatalf("tries=%d", calls) |
| + } |
| + if exhaust { |
| + if !errors.Is(err, ErrDemoLiveLimit) { |
| + t.Fatalf("exhaustion: %v", err) |
| + } |
| + } else if err != nil || id.ID != fresh.ID { |
| + t.Fatalf("retry: %v", err) |
| + } |
| + } |
| +} |
| + |
| +type demoExpiryFault struct { |
| + release.Store |
| + put, deleteKey string |
| + hits int |
| + after bool |
| + reads bool |
| +} |
| + |
| +func (f *demoExpiryFault) Put(ctx context.Context, k string, b []byte, e string) (string, error) { |
| + if strings.HasSuffix(k, f.put) && f.put != "" { |
| + f.hits++ |
| + if f.after { |
| + _, _ = f.Store.Put(ctx, k, b, e) |
| + } |
| + return "", errors.New("injected put") |
| + } |
| + return f.Store.Put(ctx, k, b, e) |
| +} |
| +func (f *demoExpiryFault) Delete(ctx context.Context, k string) error { |
| + if k == f.deleteKey { |
| + if f.after { |
| + _ = f.Store.Delete(ctx, k) |
| + } |
| + return errors.New("injected delete") |
| + } |
| + return f.Store.Delete(ctx, k) |
| +} |
| +func (f *demoExpiryFault) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + if f.reads { |
| + return nil, "", errors.New("injected read") |
| + } |
| + return f.Store.Get(ctx, k) |
| +} |
| + |
| +func TestDemoPurgeRecoveryInterruptedWrites(t *testing.T) { |
| + for _, fault := range []string{"marker before", "marker after", "row", "receipt", "purge marker after", "final row"} { |
| + t.Run(fault, func(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + life, _ := s.store.AppLife(d.AccountID, d.App) |
| + now := time.Unix(life.ExpiresAt, 0) |
| + original := s.cfg.Releases |
| + f := &demoExpiryFault{Store: original} |
| + s.cfg.Releases = f |
| + switch fault { |
| + case "marker before", "marker after": |
| + f.put = "deleted.json" |
| + f.after = fault == "marker after" |
| + case "receipt": |
| + f.put = "demo-retire.json" |
| + case "row": |
| + _, err := s.store.db.Exec(`CREATE TRIGGER fail_demo_expiry BEFORE UPDATE OF deleted_at ON apps BEGIN SELECT RAISE(FAIL,'injected row'); END`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.expiryPass(t.Context(), now) |
| + if f.put != "" && f.hits == 0 { |
| + t.Fatal("injected PUT failure was not reached") |
| + } |
| + before, err := s.demoRetirement(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.put = "" |
| + if fault == "row" { |
| + if _, err = s.store.db.Exec(`DROP TRIGGER fail_demo_expiry`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.expiryPass(t.Context(), now.Add(time.Minute)) |
| + after, err := s.demoRetirement(t.Context(), d.ID) |
| + if err != nil || !bytes.Equal(before.Wire, after.Wire) { |
| + t.Fatalf("retry changed lifetime: %v", err) |
| + } |
| + if err = s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, after.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + switch fault { |
| + case "purge marker after": |
| + f.deleteKey = release.AppTombstoneKey(d.AccountSqid, d.App) |
| + f.after = true |
| + case "final row": |
| + if _, err = s.store.db.Exec(`CREATE TRIGGER fail_demo_finish BEFORE DELETE ON apps BEGIN SELECT RAISE(FAIL,'injected row'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.expiryPass(t.Context(), now.Add(2*time.Minute)) |
| + f.deleteKey = "" |
| + if fault == "final row" { |
| + if _, err = s.store.db.Exec(`DROP TRIGGER fail_demo_finish`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.expiryPass(t.Context(), now.Add(3*time.Minute)) |
| + got, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil || got.PurgedAt == 0 { |
| + t.Fatalf("retry incomplete: %+v %v", got, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoPurgeRecoveryNoEvidence(t *testing.T) { |
| + for _, fault := range []string{"empty", "read error"} { |
| + t.Run(fault, func(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + life, _ := s.store.AppLife(d.AccountID, d.App) |
| + now := time.Unix(life.ExpiresAt, 0) |
| + s.expiryPass(t.Context(), now) |
| + r, err := s.demoRetirement(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, r.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + if fault == "empty" { |
| + s.cfg.Releases = release.NewDirStore(t.TempDir()) |
| + } else { |
| + s.cfg.Releases = &demoExpiryFault{Store: s.cfg.Releases, reads: true} |
| + } |
| + s.expiryPass(t.Context(), now.Add(time.Minute)) |
| + got, _ := s.store.demoByID(t.Context(), d.ID) |
| + if got.PurgedAt != 0 { |
| + t.Fatal("unproved purge completed") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoExpiryTrashRowHasNoGrace(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + in := demoTestAdmission(t, demoTestConfig(t)) |
| + d, err := st.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := in.Now.Add(24 * time.Hour) |
| + if err = st.TrashAppRow(d.AccountID, d.App, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + life, _ := st.AppLife(d.AccountID, d.App) |
| + if life.PurgeAfter != life.DeletedAt { |
| + t.Fatalf("demo grace=%d", life.PurgeAfter-life.DeletedAt) |
| + } |
| +} |
diff --git a/internal/console/demo_gate_test.go b/internal/console/demo_gate_test.go| index 246924520..7b5637cee 100644 |
| --- a/internal/console/demo_gate_test.go |
| +++ b/internal/console/demo_gate_test.go |
| @@ -21,6 +21,8 @@ func TestDemoSQLClaimsRefuseBuildState(t *testing.T) { |
| `INSERT INTO demo_apps(demo_id,account_id,account_sqid,app,name,fleet,claim_token_hash,created_at,creating_ip,source_sha256,client) VALUES('demo',7,'shop','blog','shop','demo',zeroblob(32),1,'hash',X'','test')`, |
| `INSERT INTO demo_jobs(id,demo_id,generation,attempt,box,deadline,state,wire,job) VALUES('job','demo',1,1,'box',1,'queued',X'',X'')`, |
| `INSERT INTO demo_job_outbox(job_id,source) VALUES('job',X'')`, |
| + `INSERT INTO demo_retirements(demo_id,wire) VALUES('demo',X'')`, |
| + `INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES('shop.example.com','demo',1)`, |
| } { |
| if _, err := initial.db.Exec(query); err != nil { |
| t.Fatal(err) |
| @@ -43,6 +45,10 @@ func TestDemoSQLClaimsRefuseBuildState(t *testing.T) { |
| `UPDATE demo_jobs SET state='failed'`, `DELETE FROM demo_jobs`, |
| `INSERT INTO demo_job_outbox(job_id,source) VALUES('other',X'')`, |
| `UPDATE demo_job_outbox SET source=X'01'`, `DELETE FROM demo_job_outbox`, |
| + `INSERT INTO demo_retirements(demo_id,wire) VALUES('other',X'')`, |
| + `UPDATE demo_retirements SET acknowledged=1`, `DELETE FROM demo_retirements`, |
| + `INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES('other.example.com','other',1)`, |
| + `UPDATE demo_host_tombstones SET purged_at=2`, `DELETE FROM demo_host_tombstones`, |
| } { |
| _, err := v.db.Exec(query) |
| requireDenied(t, query, err) |
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go| index f1d23f597..018e5dfab 100644 |
| --- a/internal/console/demo_store.go |
| +++ b/internal/console/demo_store.go |
| @@ -58,7 +58,7 @@ CREATE INDEX IF NOT EXISTS demo_admissions_ip_time ON demo_admissions(ip_hash, a |
| 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), |
| + claim_token_hash BLOB UNIQUE CHECK(claim_token_hash IS NULL OR 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 '', |
| @@ -78,6 +78,9 @@ CREATE TABLE IF NOT EXISTS demo_apps ( |
| if err != nil { |
| return err |
| } |
| + if err := s.migrateDemoRetirement(); err != nil { |
| + return err |
| + } |
| return s.migrateDemoJobs() |
| } |
| @@ -227,6 +230,12 @@ func (s *Store) ReserveDemo(ctx context.Context, in DemoAdmission) (DemoRow, err |
| if count != 0 { |
| return zero, ErrDemoNameTaken |
| } |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM demo_host_tombstones WHERE host=?`, in.Host).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 |
| @@ -387,9 +396,24 @@ func (s *Server) withDemoLocked(ctx context.Context, id string, fn func(DemoRow, |
| } |
| // 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. |
| +// Purged history lasts seven days; the minimal host tombstone is permanent. |
| +// The existing expiry pass calls this even with admission disabled. |
| 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 |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + cutoff := now.Add(-7 * 24 * time.Hour).Unix() |
| + if _, err = tx.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!='')`, cutoff); err != nil { |
| + return err |
| + } |
| + const expired = `SELECT d.demo_id FROM demo_apps d JOIN demo_host_tombstones t ON t.demo_id=d.demo_id AND t.host=d.host WHERE d.purged_at>0 AND d.purged_at<=? AND NOT EXISTS (SELECT 1 FROM demo_retirements r WHERE r.demo_id=d.demo_id)` |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_jobs WHERE demo_id IN (`+expired+`)`, cutoff); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_apps WHERE demo_id IN (`+expired+`)`, cutoff); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| } |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 3ec42aed2..93e41b972 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -75,6 +75,7 @@ func (s *Server) expiryPass(ctx context.Context, now time.Time) { |
| return |
| } |
| keys, listed, evidence := s.listEvidence(ctx) |
| + s.expireDemos(ctx, now, evidence) |
| ev := func(context.Context) bool { return evidence } |
| if !evidence { |
| log.Printf("console: expiry pass: the apps/ listing holds nothing but trash markers, or could not be read; " + |
| @@ -173,7 +174,7 @@ func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evid |
| return |
| } |
| // A keep that ran after the listing set expires_at = 0, which fails > 0. |
| - if life == nil || life.ExpiresAt <= 0 || life.ExpiresAt > now.Unix() || life.Trashed() || life.Restoring { |
| + if life == nil || life.DemoID != "" || life.ExpiresAt <= 0 || life.ExpiresAt > now.Unix() || life.Trashed() || life.Restoring { |
| return |
| } |
| acct := &Account{ID: r.AccountID, Sqid: r.Sqid} |
| @@ -220,7 +221,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| jobFailed(ctx, fmt.Errorf("expiry pass: read %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| - if life == nil || !life.Trashed() || life.PurgeAfter <= 0 || life.PurgeAfter > now.Unix() || life.PurgeFor <= 0 { |
| + if life == nil || life.DemoID != "" || !life.Trashed() || life.PurgeAfter <= 0 || life.PurgeAfter > now.Unix() || life.PurgeFor <= 0 { |
| return // restored, purged, or never due: settling answered it |
| } |
| acct := &Account{ID: r.AccountID, Sqid: r.Sqid} |
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go| index 820d1c4ed..0c0aece65 100644 |
| --- a/internal/console/lifetimes_purge.go |
| +++ b/internal/console/lifetimes_purge.go |
| @@ -37,7 +37,7 @@ import ( |
| // caller holds s.lockApp(sqid, app) and releases the apps row afterwards. Any |
| // error leaves the marker: errLifetimePending and errLifetimeSettling stop |
| // the purge for a later run, and every step is idempotent. |
| -func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, want, now time.Time) error { |
| +func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, want, now time.Time, keepMarker ...bool) error { |
| s.noteRecordDeletion(sqid, app, time.Now()) // the canary-retire guard's evidence, first |
| if err := release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now); err != nil { |
| return err |
| @@ -89,7 +89,7 @@ func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, wa |
| } |
| } |
| return release.PurgeAppExcept(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now, func(key string) bool { |
| - return provision.IsInstanceRecordKeyOf(key, sqid, app) |
| + return provision.IsInstanceRecordKeyOf(key, sqid, app) || len(keepMarker) > 0 && keepMarker[0] && key == release.AppTombstoneKey(sqid, app) |
| }) |
| } |
| @@ -209,6 +209,9 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| jobFailed(ctx, fmt.Errorf("trash sweep: %s/%s: %w", a.Account, a.App, err)) |
| return |
| } |
| + if life != nil && life.DemoID != "" { |
| + return |
| + } |
| if life != nil && life.ControlPlane { |
| s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s is marked as the control plane; not purging it", a.Account, a.App) |
| return |
diff --git a/internal/console/settle.go b/internal/console/settle.go| index 1a1603588..4d05606ea 100644 |
| --- a/internal/console/settle.go |
| +++ b/internal/console/settle.go |
| @@ -83,6 +83,9 @@ func (s *Server) settleApp(ctx context.Context, accountID int64, sqid, app strin |
| if err != nil || life == nil { |
| return err |
| } |
| + if life.DemoID != "" { |
| + return nil |
| + } // Demo retirement never infers restoration from absence. |
| tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, sqid, app) |
| if err != nil { |
| return err |
diff --git a/internal/console/store.go b/internal/console/store.go| index f01929be7..93a2b920b 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -2045,9 +2045,9 @@ func (s *Store) claimRawTrashAppRow(accountID int64, app string, now time.Time) |
| at := now.Unix() |
| _, err := s.db.Exec(`UPDATE apps SET deleted_at = ?, |
| purge_for = CASE WHEN expires_at > 0 THEN ? ELSE 0 END, |
| - purge_after = CASE WHEN expires_at > 0 THEN ? ELSE 0 END |
| + purge_after = CASE WHEN demo_id != '' THEN ? WHEN expires_at > 0 THEN ? ELSE 0 END |
| WHERE account_id = ? AND app = ? AND deleted_at = 0`, |
| - at, at, at+temporaryCooloffSeconds, accountID, app) |
| + at, at, at, at+temporaryCooloffSeconds, accountID, app) |
| return err |
| } |
| @@ -2056,7 +2056,7 @@ WHERE account_id = ? AND app = ? AND deleted_at = 0`, |
| // something that was never trashed is harmless. |
| func (s *Store) RestoreAppRow(accountID int64, app string) error { |
| _, err := s.db.Exec(`UPDATE apps SET deleted_at = 0, restoring = 0, purge_after = 0, purge_for = 0 |
| -WHERE account_id = ? AND app = ?`, accountID, app) |
| +WHERE account_id = ? AND app = ? AND demo_id = ''`, accountID, app) |
| return err |
| } |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 704e5520e..00fef82b5 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -188,6 +188,8 @@ 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{ |
| + "demo_retirements": {App: "demo_id", Refuse: "anonymous demo retirement requires claims mode off"}, |
| + "demo_host_tombstones": {App: "demo_id", Refuse: "anonymous demo host reservations require claims mode off"}, |
| // Jobs carry demo identity and durable spool metadata; source outbox rows |
| // carry only a job ID. Neither is safe to write with an ordinary app permit. |
| // The opaque IDs below are refusal-only scopes, never matched to a permit. |
diff --git a/internal/console/tempstore.go b/internal/console/tempstore.go| index d1f5e2bb2..b52d957d2 100644 |
| --- a/internal/console/tempstore.go |
| +++ b/internal/console/tempstore.go |
| @@ -129,9 +129,9 @@ func (s *Store) changed(query string, args ...any) (bool, error) { |
| // (expires_at = 0) makes this a no-op. |
| func (s *Store) claimRawExpireAppRow(accountID int64, app string, deletedAt time.Time) (bool, error) { |
| at := deletedAt.Unix() |
| - return s.changed(`UPDATE apps SET deleted_at = ?, purge_for = ?, purge_after = ? |
| + return s.changed(`UPDATE apps SET deleted_at = ?, purge_for = ?, purge_after = CASE WHEN demo_id != '' THEN ? ELSE ? END |
| WHERE account_id = ? AND app = ? AND expires_at > 0 AND deleted_at = 0`, |
| - at, at, at+temporaryCooloffSeconds, accountID, app) |
| + at, at, at, at+temporaryCooloffSeconds, accountID, app) |
| } |
| // KeepApp makes a live temporary app permanent (`carlos apps keep`). |
| @@ -154,7 +154,7 @@ WHERE account_id = ? AND app = ? AND expires_at > 0 AND deleted_at = 0 AND resto |
| // pass never sees an untrashed row with a stale expiry. |
| func (s *Store) claimRawBumpTrashedExpiry(accountID int64, app string, now time.Time) (bool, error) { |
| return s.changed(`UPDATE apps SET expires_at = ? |
| -WHERE account_id = ? AND app = ? AND expires_at > 0 AND expires_at < ? AND deleted_at != 0`, |
| +WHERE account_id = ? AND app = ? AND expires_at > 0 AND expires_at < ? AND deleted_at != 0 AND demo_id = ''`, |
| now.Add(temporaryTTLDefault).Unix(), accountID, app, now.Add(temporaryRestoreFloor).Unix()) |
| } |
| @@ -162,7 +162,7 @@ WHERE account_id = ? AND app = ? AND expires_at > 0 AND expires_at < ? AND delet |
| // it (settleApp, and a failed step 4). |
| func (s *Store) claimRawSetRestoring(accountID int64, app string, on bool) (bool, error) { |
| if on { |
| - return s.changed(`UPDATE apps SET restoring = 1 WHERE account_id = ? AND app = ? AND deleted_at != 0`, accountID, app) |
| + return s.changed(`UPDATE apps SET restoring = 1 WHERE account_id = ? AND app = ? AND deleted_at != 0 AND demo_id = ''`, accountID, app) |
| } |
| return s.changed(`UPDATE apps SET restoring = 0 WHERE account_id = ? AND app = ?`, accountID, app) |
| } |
| @@ -173,7 +173,7 @@ func (s *Store) claimRawSetRestoring(accountID int64, app string, on bool) (bool |
| func (s *Store) FinishRestoreRow(accountID int64, app string, now time.Time) error { |
| _, err := s.db.Exec(`UPDATE apps SET deleted_at = 0, restoring = 0, purge_after = 0, purge_for = 0, |
| expires_at = CASE WHEN expires_at > 0 AND expires_at < ? THEN ? ELSE expires_at END |
| -WHERE account_id = ? AND app = ?`, |
| +WHERE account_id = ? AND app = ? AND demo_id = ''`, |
| now.Add(temporaryRestoreFloor).Unix(), now.Add(temporaryTTLDefault).Unix(), accountID, app) |
| return err |
| } |
diff --git a/internal/demobuild/job.go b/internal/demobuild/job.go| index 13365f125..4124a9284 100644 |
| --- a/internal/demobuild/job.go |
| +++ b/internal/demobuild/job.go |
| @@ -158,8 +158,9 @@ type BuildOutput struct { |
| // StreamMessage carries signed work or a reconciliation hint. Hints grant no |
| // authority: the existing pass verifies the policies and records it reads. |
| type StreamMessage struct { |
| - Job []byte `json:"job,omitempty"` |
| - Reconcile bool `json:"reconcile,omitempty"` |
| + Retirement []byte `json:"retirement,omitempty"` |
| + Job []byte `json:"job,omitempty"` |
| + Reconcile bool `json:"reconcile,omitempty"` |
| } |
| // DecodeMessage bounds and strictly decodes transport metadata, rejecting |
diff --git a/internal/demobuild/purge.go b/internal/demobuild/purge.go| new file mode 100644 |
| index 000000000..188924ab7 |
| --- /dev/null |
| +++ b/internal/demobuild/purge.go |
| @@ -0,0 +1,92 @@ |
| +package demobuild |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + |
| + "github.com/carlosframework/platform/internal/instancefs" |
| +) |
| + |
| +// PurgeDemo waits for running builds (including their cleanup defers) before |
| +// reopening scratch. Only root's own job marker binds a directory to a demo. |
| +// Replay markers remain until their original grant deadline has passed. |
| +func (w *Worker) PurgeDemo(ctx context.Context, demoID string, ids []string) error { |
| + if demoID == "" || len(ids) > 61 { |
| + return ErrJob |
| + } |
| + w.buildPurge.Lock() |
| + defer w.buildPurge.Unlock() |
| + for _, id := range ids { |
| + if !ValidJobID(id) || ctx.Err() != nil { |
| + return ErrJob |
| + } |
| + f, err := instancefs.OpenBeneath(w.root, "seen/"+id, os.O_RDONLY, 0) |
| + if errors.Is(err, os.ErrNotExist) { |
| + if _, e := os.Lstat(filepath.Join(w.root, id)); !errors.Is(e, os.ErrNotExist) { |
| + return ErrBuild |
| + } |
| + continue |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + b, err := io.ReadAll(io.LimitReader(f, MaxJobWire+1)) |
| + f.Close() |
| + var j Job |
| + if err != nil || DecodeMessage(b, &j) != nil || j.validate() != nil || j.ID != id || j.DemoID != demoID || j.Box != w.box { |
| + return ErrJob |
| + } |
| + dir := filepath.Join(w.root, id, strconv.FormatUint(uint64(j.Attempt), 10)) |
| + if _, err = os.Lstat(filepath.Join(w.root, id)); errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } else if err != nil { |
| + return err |
| + } |
| + if w.purgeUnit != nil { |
| + err = w.purgeUnit(ctx, dir) |
| + } else { |
| + var l buildLayout |
| + l, err = layoutIn(w.root, dir) |
| + if err == nil { |
| + err = w.cleanUnit(ctx, l) |
| + } |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// The existing reconnect readiness check retries failed root cleanup. It |
| +// cannot make a poisoned worker available while any build is still active. |
| +func (w *Worker) recoverPurge(ctx context.Context) error { |
| + w.mu.Lock() |
| + poisoned := w.poisoned |
| + w.mu.Unlock() |
| + if !poisoned { |
| + return nil |
| + } |
| + if w.retryCleanup == nil { |
| + return ErrBuild |
| + } |
| + w.buildPurge.Lock() |
| + defer w.buildPurge.Unlock() |
| + w.mu.Lock() |
| + poisoned = w.poisoned |
| + w.mu.Unlock() |
| + if !poisoned { |
| + return nil |
| + } |
| + if err := w.retryCleanup(ctx); err != nil { |
| + return err |
| + } |
| + w.mu.Lock() |
| + w.poisoned = false |
| + w.mu.Unlock() |
| + return nil |
| +} |
diff --git a/internal/demobuild/retirement.go b/internal/demobuild/retirement.go| new file mode 100644 |
| index 000000000..087e44a0f |
| --- /dev/null |
| +++ b/internal/demobuild/retirement.go |
| @@ -0,0 +1,62 @@ |
| +package demobuild |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +// Retirement is console authority to stop and purge one permanently reserved |
| +// host. It has no expiry: an offline assigned box must still consume it. |
| +type Retirement struct { |
| + Demo demo.Descriptor `json:"demo"` |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Fleet string `json:"fleet"` |
| + Box string `json:"box"` |
| + Tombstone int64 `json:"tombstone"` |
| + Jobs []string `json:"jobs"` |
| +} |
| + |
| +const retirementDomain = "carlos-demo-retirement-v1\x00" |
| + |
| +func (r Retirement) valid() bool { |
| + if demo.ValidateBinding(r.Demo, r.Account, r.App, r.Demo.Host, r.Demo.Lifetime, r.Fleet) != nil || r.Tombstone < r.Demo.ExpiresAt || len(r.Jobs) > 61 { |
| + return false |
| + } |
| + for _, id := range r.Jobs { |
| + if !ValidJobID(id) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func SignRetirement(key ed25519.PrivateKey, r Retirement) ([]byte, error) { |
| + if len(key) != ed25519.PrivateKeySize || !r.valid() { |
| + return nil, ErrJob |
| + } |
| + b, err := json.Marshal(r) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p := base64.StdEncoding.EncodeToString(b) |
| + return json.Marshal(signedJob{Payload: p, Sig: base64.StdEncoding.EncodeToString(ed25519.Sign(key, []byte(retirementDomain+p)))}) |
| +} |
| +func VerifyRetirement(key ed25519.PublicKey, wire []byte) (Retirement, error) { |
| + var e signedJob |
| + var r Retirement |
| + if len(key) != ed25519.PublicKeySize || len(wire) > MaxJobWire || strictJobJSON(wire, &e) != nil { |
| + return r, ErrJob |
| + } |
| + sig, err := base64.StdEncoding.Strict().DecodeString(e.Sig) |
| + if err != nil || !ed25519.Verify(key, []byte(retirementDomain+e.Payload), sig) { |
| + return r, ErrJob |
| + } |
| + b, err := base64.StdEncoding.Strict().DecodeString(e.Payload) |
| + if err != nil || strictJobJSON(b, &r) != nil || !r.valid() { |
| + return Retirement{}, ErrJob |
| + } |
| + return r, nil |
| +} |
diff --git a/internal/demobuild/retirement_test.go b/internal/demobuild/retirement_test.go| new file mode 100644 |
| index 000000000..de4c897f9 |
| --- /dev/null |
| +++ b/internal/demobuild/retirement_test.go |
| @@ -0,0 +1,96 @@ |
| +package demobuild |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +func TestDemoRetirementSignature(t *testing.T) { |
| + w, j, key, _ := workerFixture(t) |
| + r := Retirement{Demo: demo.Descriptor{ID: j.DemoID, Host: j.Host, Lifetime: j.Lifetime, ExpiresAt: j.Deadline.Unix()}, Account: j.Account, App: j.App, Fleet: j.Fleet, Box: j.Box, Tombstone: j.Deadline.Unix(), Jobs: []string{j.ID}} |
| + wire, err := SignRetirement(key, r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := VerifyRetirement(w.pub, wire) |
| + if err != nil || got.Demo != r.Demo { |
| + t.Fatalf("verify: %+v %v", got, err) |
| + } |
| + jobWire, _ := SignJob(key, j) |
| + if _, err = VerifyRetirement(w.pub, jobWire); err == nil { |
| + t.Fatal("job accepted as retirement") |
| + } |
| + wire[len(wire)-8] ^= 1 |
| + if _, err = VerifyRetirement(w.pub, wire); err == nil { |
| + t.Fatal("tampered retirement") |
| + } |
| +} |
| + |
| +func TestDemoLocalPurgeBuildOwnership(t *testing.T) { |
| + w, j, key, src := workerFixture(t) |
| + if err := w.reserve(j); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := 0 |
| + w.purgeUnit = func(ctx context.Context, dir string) error { calls++; return os.RemoveAll(filepath.Dir(dir)) } |
| + dir := filepath.Join(w.root, j.ID, "1") |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, name := range []string{"source", "output", "private-cache"} { |
| + os.WriteFile(filepath.Join(dir, name), []byte("private"), 0600) |
| + } |
| + sibling := filepath.Join(w.root, "shared-toolchain") |
| + os.Mkdir(sibling, 0700) |
| + if err := w.PurgeDemo(t.Context(), "foreign", []string{j.ID}); err == nil || calls != 0 { |
| + t.Fatal("foreign marker accepted") |
| + } |
| + if err := w.PurgeDemo(t.Context(), j.DemoID, []string{j.ID}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(dir); !os.IsNotExist(err) { |
| + t.Fatal("build scratch remains") |
| + } |
| + if _, err := os.Stat(sibling); err != nil { |
| + t.Fatal("shared toolchain removed") |
| + } |
| + // Purge never drops the replay marker while its grant can still execute. |
| + wire, _ := SignJob(key, j) |
| + if _, err := w.Build(t.Context(), wire, bytes.NewReader(src)); err == nil { |
| + t.Fatal("purged job replayed") |
| + } |
| +} |
| + |
| +func TestDemoPurgeRecoveryPoisonedWorker(t *testing.T) { |
| + w, _, _, _ := workerFixture(t) |
| + w.poisoned = true |
| + calls := 0 |
| + w.retryCleanup = func(context.Context) error { calls++; return nil } |
| + if err := w.recoverPurge(t.Context()); err != nil || calls != 1 || !w.available() { |
| + t.Fatalf("cleanup retry: calls=%d err=%v available=%v", calls, err, w.available()) |
| + } |
| +} |
| + |
| +func TestDemoPurgeRecoveryInitializationRetries(t *testing.T) { |
| + w, _, _, _ := workerFixture(t) |
| + w.ready = false |
| + calls := 0 |
| + stage := func(context.Context) error { |
| + calls++ |
| + if calls == 1 { |
| + return ErrBuild |
| + } |
| + return nil |
| + } |
| + if err := w.initialize(t.Context(), stage); err == nil { |
| + t.Fatal("failed recovery accepted") |
| + } |
| + if err := w.initialize(t.Context(), stage); err != nil || calls != 2 || !w.available() { |
| + t.Fatalf("retry=%v calls=%d ready=%v", err, calls, w.available()) |
| + } |
| +} |
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go| index b03d22e3d..1c13da7f3 100644 |
| --- a/internal/demobuild/worker.go |
| +++ b/internal/demobuild/worker.go |
| @@ -29,6 +29,9 @@ const BuildRoot = "/var/lib/carlos-demo-builds" |
| // Worker belongs to the root service, surviving agent disconnects and restarts. |
| // An exclusive root-process lock and recovery precede any readiness response. |
| type Worker struct { |
| + retryCleanup func(context.Context) error |
| + buildPurge sync.RWMutex |
| + purgeUnit func(context.Context, string) error |
| cfg demo.Config |
| box string |
| pub ed25519.PublicKey |
| @@ -42,8 +45,8 @@ type Worker struct { |
| mu sync.Mutex |
| poisoned bool |
| ready bool |
| - initOnce sync.Once |
| - initErr error |
| + initMu sync.Mutex |
| + initDone bool |
| } |
| func NewWorker(getenv func(string) string, proof func(context.Context) error) (*Worker, error) { |
| @@ -91,6 +94,7 @@ func NewWorker(getenv func(string) string, proof func(context.Context) error) (* |
| return nil, err |
| } |
| w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard} |
| + w.retryCleanup = w.recover |
| w.prepare = w.prepareUnit |
| w.run = w.runUnit |
| return w, nil |
| @@ -109,25 +113,29 @@ func (w *Worker) Initialize(ctx context.Context) error { |
| } |
| func (w *Worker) initialize(ctx context.Context, stages ...func(context.Context) error) error { |
| - w.initOnce.Do(func() { |
| - ctx, cancel := context.WithTimeout(ctx, BuildWindow) |
| - defer cancel() |
| - for _, stage := range stages { |
| - if w.initErr = ctx.Err(); w.initErr != nil { |
| - return |
| - } |
| - if w.initErr = stage(ctx); w.initErr != nil { |
| - return |
| - } |
| + w.initMu.Lock() |
| + defer w.initMu.Unlock() |
| + if w.initDone { |
| + return nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, BuildWindow) |
| + defer cancel() |
| + for _, stage := range stages { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| } |
| - if w.initErr = ctx.Err(); w.initErr != nil { |
| - return |
| + if err := stage(ctx); err != nil { |
| + return err |
| } |
| - w.mu.Lock() |
| - w.ready = true |
| - w.mu.Unlock() |
| - }) |
| - return w.initErr |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + w.mu.Lock() |
| + w.ready = true |
| + w.mu.Unlock() |
| + w.initDone = true |
| + return nil |
| } |
| func (w *Worker) available() bool { |
| @@ -147,6 +155,9 @@ func (w *Worker) Close() error { |
| } |
| func (w *Worker) Readiness(ctx context.Context) (WorkerReady, error) { |
| + if err := w.recoverPurge(ctx); err != nil { |
| + return WorkerReady{}, err |
| + } |
| if !w.available() || w.proof == nil || w.proof(ctx) != nil { |
| return WorkerReady{}, ErrBuild |
| } |
| @@ -181,6 +192,8 @@ func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out |
| if err != nil { |
| return out, err |
| } |
| + w.buildPurge.RLock() |
| + defer w.buildPurge.RUnlock() |
| ctx, cancel := context.WithDeadline(ctx, j.Deadline) |
| defer cancel() |
| select { |
| @@ -310,6 +323,9 @@ func (w *Worker) expireMarkers() error { |
| return ErrBuild |
| } |
| if !time.Now().Before(j.Deadline) { |
| + if _, e := os.Lstat(filepath.Join(w.root, j.ID)); !errors.Is(e, os.ErrNotExist) { |
| + continue |
| + } |
| if err = r.Remove(e.Name()); err != nil { |
| return err |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index e940ab9cc..b8dac91c0 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -415,6 +415,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| guard.Announce() |
| var act edge.Activator |
| + var demoData release.Store |
| var svc *activator.Service |
| var coordinator *activator.CoordinationClient |
| // egressStatus is root's GET /egress for the status tick (#328): set |
| @@ -488,6 +489,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| log.Printf("agent: region HA: files store: %v (every HA restore that needs it fails)", err) |
| } else { |
| eb.FilesStore = fs |
| + demoData = fs |
| } |
| // Durability 3a: an HA host's secrets publish sealed to this |
| // box's own key, and nothing publishes without one. |
| @@ -935,7 +937,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // so it follows the watch just armed (nil on a fleet or disarmed |
| // box), before any loop that reconciles. |
| armPolicyCache() |
| - startDemoWorker(agentCtx) |
| + startDemoWorker(agentCtx, reg, demoData, cfg.Prefix) |
| go adoptLoop(reg, svc, sd, claims.Writes) |
| go fastConvergeLoop(reg, svc, sd, claims.Writes, serialClaims, bs, boxJudge, claims.Providers.Provision) |
| if logSink != nil { |
diff --git a/internal/host/claimstop_run.go b/internal/host/claimstop_run.go| index 6daf12a1f..0f970f7a9 100644 |
| --- a/internal/host/claimstop_run.go |
| +++ b/internal/host/claimstop_run.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/rootparticipation" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| ) |
| func RunInstanceControl(args []string) { |
| @@ -44,7 +45,7 @@ func RunInstanceControl(args []string) { |
| if !cfg.BoxMode() { |
| egress = newEgressAsserter(registryEgressSource(dataDir(), time.Now), registryEgressHosts(dataDir())) |
| } |
| - instancectl.RunWithRegistryView(args, instancectl.RegistryView{HostApp: instanceRegistryHostApp(nil), HostRuntime: instanceRegistryHostRuntime}, egress) |
| + instancectl.RunWithRegistryView(args, instancectl.RegistryView{HostApp: instanceRegistryHostApp(nil), HostRuntime: instanceRegistryHostRuntime, HostDemo: instanceRegistryDemo, DemoRoutes: instanceRegistryDemoRoutes, DemoPurgeGuard: instanceDemoPurgeGuard}, egress) |
| return |
| } |
| reg, err := openServiceRegistry(filepath.Join(dataDir(), "registry.db")) |
| @@ -223,3 +224,36 @@ func claimRecoveryReady(open func() (rootparticipation.Ledger, bool, error)) err |
| _, err = l.RecoveryCensus() |
| return err |
| } |
| + |
| +func instanceRegistryDemo(host string) (*registry.Route, error) { |
| + reg, err := openServiceRegistryReadOnly(filepath.Join(dataDir(), "registry.db")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer reg.Close() |
| + return reg.Get(host) |
| +} |
| + |
| +func instanceRegistryDemoRoutes() ([]registry.Route, error) { |
| + reg, err := openServiceRegistryReadOnly(filepath.Join(dataDir(), "registry.db")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer reg.Close() |
| + return reg.List() |
| +} |
| + |
| +func instanceDemoPurgeGuard(ctx context.Context, effect func() error) error { |
| + open := func() (rootstate.Store, error) { return rootstate.Open(rootReleasePrivate, true, false) } |
| + return withClaimRootRelease(ctx, false, open, func() error { |
| + unlock, err := lockAdoptPass(dataDir()) |
| + if err != nil { |
| + return err |
| + } |
| + defer unlock() |
| + if err = ctx.Err(); err != nil { |
| + return err |
| + } |
| + return effect() |
| + }) |
| +} |
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go| index 1e9a123a4..bdd8bbe36 100644 |
| --- a/internal/host/claimunit.go |
| +++ b/internal/host/claimunit.go |
| @@ -120,6 +120,7 @@ func claimUnitContent(name string, content []byte, cfg claimUnitSettings) []byte |
| } |
| if !cfg.enabled { |
| if cfg.demo.BoxMode() { |
| + content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nReadWritePaths=/data /run/carlos/instances /opt/carlos/live /opt/carlos/versions /var/lib/carlos-release/private\n"), 1) |
| content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\n"+claimControlEnvironment), 1) |
| if cfg.demo.BuildWorker { |
| content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nStateDirectory=carlos-demo-builds\nStateDirectoryMode=0700\nReadWritePaths=/var/lib/carlos-demo-builds\n"), 1) |
diff --git a/internal/host/demo_cleanup.go b/internal/host/demo_cleanup.go| new file mode 100644 |
| index 000000000..54fa64e42 |
| --- /dev/null |
| +++ b/internal/host/demo_cleanup.go |
| @@ -0,0 +1,117 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func (w *demoWorker) retireDemo(ctx context.Context, wire []byte) error { |
| + r, err := demobuild.VerifyRetirement(w.pub, wire) |
| + if err != nil { |
| + return err |
| + } |
| + if r.Box != w.box || w.cfg.ValidateBinding(r.Demo, r.Account, r.App, r.Demo.Host, r.Demo.Lifetime, r.Fleet) != nil || w.reg == nil || w.purge == nil || w.acknowledge == nil || w.complete == nil || w.data == nil { |
| + return demo.ErrPolicy |
| + } |
| + if w.store == nil { |
| + return demo.ErrPolicy |
| + } |
| + stored, _, err := w.store.Get(ctx, release.AppPrefix(r.Account, r.App)+"demo-retire.json") |
| + if err != nil { |
| + return err |
| + } |
| + if !bytes.Equal(stored, wire) { |
| + return demo.ErrPolicy |
| + } |
| + tomb, err := release.ReadAppTombstone(ctx, w.store, r.Account, r.App) |
| + if err != nil { |
| + return err |
| + } |
| + if tomb == nil || tomb.DeletedAt.Unix() != r.Tombstone { |
| + return demo.ErrPolicy |
| + } |
| + rt, err := w.reg.Get(r.Demo.Host) |
| + if err != nil { |
| + return err |
| + } |
| + op := "demo-retire/" + r.Demo.ID |
| + if rt != nil { |
| + if rt.DemoID != r.Demo.ID || rt.DemoLifetime != r.Demo.Lifetime || rt.DemoHost != r.Demo.Host || rt.Account != r.Account || rt.App != r.App || rt.Assigned != w.box || rt.Region != "fleet/"+r.Fleet { |
| + return demo.ErrPolicy |
| + } |
| + ok, err := w.reg.SetHoldIf(rt.Host, "releasing", op, rt.HoldOp) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + return demo.ErrPolicy |
| + } |
| + if w.notify != nil { |
| + w.notify() |
| + } |
| + } |
| + if err = w.purge(ctx, instancectl.DemoPurgeRequest{Demo: r.Demo, Jobs: r.Jobs}); err != nil { |
| + return err |
| + } |
| + if rt != nil { |
| + if ok, err := w.reg.DeleteIfHoldWithTimers(rt.Host, op); err != nil { |
| + return err |
| + } else if !ok { |
| + return demo.ErrPolicy |
| + } |
| + } |
| + if w.notify != nil { |
| + w.notify() |
| + } |
| + if err = w.acknowledge(ctx, wire); err != nil { |
| + return err |
| + } |
| + // The first acknowledgment is durable before initialization evidence goes. |
| + key := path.Join(w.dataPrefix, r.Demo.Host, "demo-initialized", r.Demo.ID+".json") |
| + if _, _, err = w.data.Get(ctx, key); err == nil { |
| + if err = w.data.Delete(ctx, key); err != nil { |
| + return err |
| + } |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + return w.complete(ctx, wire) |
| +} |
| + |
| +func (w *demoWorker) acknowledgeDemoHTTP(ctx context.Context, wire []byte) error { |
| + return w.acknowledgeDemoPhaseHTTP(ctx, wire, false) |
| +} |
| +func (w *demoWorker) acknowledgeDemoPhaseHTTP(ctx context.Context, wire []byte, complete bool) error { |
| + suffix := "" |
| + if complete { |
| + suffix = "?complete=1" |
| + } |
| + req, err := http.NewRequestWithContext(ctx, "POST", w.base+"/api/box/demo-retirements/ack"+suffix, bytes.NewReader(wire)) |
| + if err != nil { |
| + return err |
| + } |
| + req.Header, err = w.headers() |
| + if err != nil { |
| + return err |
| + } |
| + res, err := w.http.Do(req) |
| + if err != nil { |
| + return err |
| + } |
| + defer res.Body.Close() |
| + io.Copy(io.Discard, io.LimitReader(res.Body, 4096)) |
| + if res.StatusCode != 204 { |
| + return demo.ErrPolicy |
| + } |
| + return nil |
| +} |
diff --git a/internal/host/demo_cleanup_test.go b/internal/host/demo_cleanup_test.go| new file mode 100644 |
| index 000000000..4bf0ba1a6 |
| --- /dev/null |
| +++ b/internal/host/demo_cleanup_test.go |
| @@ -0,0 +1,107 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestDemoOfflineRetirement(t *testing.T) { |
| + pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| + id, _ := demo.NewIdentity(rand.Reader) |
| + cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"} |
| + d := demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: 1800000000} |
| + receipt := demobuild.Retirement{Demo: d, Account: "shop", App: id.App, Fleet: "demo", Box: "box", Tombstone: d.ExpiresAt} |
| + wire, err := demobuild.SignRetirement(key, receipt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + rt := registry.Route{Host: d.Host, Kind: "instance", Account: "shop", App: id.App, Region: "fleet/demo", Assigned: "box", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt} |
| + if err = reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + store := release.NewDirStore(t.TempDir()) |
| + if _, err = store.Put(t.Context(), release.AppPrefix(receipt.Account, receipt.App)+"demo-retire.json", wire, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = release.TrashApp(t.Context(), store, receipt.Account, receipt.App, "expiry", time.Unix(receipt.Tombstone, 0)); err != nil { |
| + t.Fatal(err) |
| + } |
| + data := release.NewDirStore(t.TempDir()) |
| + marker := "instances/" + d.Host + "/demo-initialized/" + d.ID + ".json" |
| + if _, err = data.Put(t.Context(), marker, []byte("proof"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + rootCalls, acks := 0, 0 |
| + fail := true |
| + w := &demoWorker{store: store, cfg: cfg, pub: pub, box: "box", reg: reg, data: data, dataPrefix: "instances", complete: func(ctx context.Context, _ []byte) error { |
| + if _, _, err := data.Get(ctx, marker); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("remote marker retained after final ack") |
| + } |
| + return nil |
| + }, |
| + purge: func(ctx context.Context, in instancectl.DemoPurgeRequest) error { |
| + rootCalls++ |
| + row, _ := reg.Get(d.Host) |
| + if rootCalls <= 2 && (row == nil || row.HoldOp != "demo-retire/"+d.ID) { |
| + t.Fatal("purge before route held") |
| + } |
| + if fail { |
| + return errors.New("cgroup populated") |
| + } |
| + return nil |
| + }, |
| + acknowledge: func(ctx context.Context, b []byte) error { |
| + acks++ |
| + if acks == 1 { |
| + if _, _, err := data.Get(ctx, marker); err != nil { |
| + t.Fatal("remote marker removed before local acknowledgment") |
| + } |
| + } |
| + return nil |
| + }} |
| + if err = w.retireDemo(t.Context(), wire); err == nil || acks != 0 { |
| + t.Fatal("ack before local purge") |
| + } |
| + fail = false |
| + if err = w.retireDemo(t.Context(), wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + if acks != 1 || rootCalls != 2 { |
| + t.Fatalf("calls root=%d ack=%d", rootCalls, acks) |
| + } |
| + if row, err := reg.Get(d.Host); err != nil || row != nil { |
| + t.Fatalf("route retained: %+v %v", row, err) |
| + } |
| + if err = w.retireDemo(t.Context(), wire); err != nil || acks != 2 { |
| + t.Fatalf("lost ack replay: %v", err) |
| + } |
| + receipt.Box = "wrong" |
| + bad, _ := demobuild.SignRetirement(key, receipt) |
| + if err = w.retireDemo(t.Context(), bad); err == nil || acks != 2 { |
| + t.Fatal("wrong box retirement") |
| + } |
| + wire[5] ^= 1 |
| + if err = w.retireDemo(t.Context(), wire); err == nil || acks != 2 { |
| + t.Fatal("bad signature retirement") |
| + } |
| + if versionSweepGrace(func(string) string { return "" }) != release.DefaultSweepGrace { |
| + t.Fatal("ordinary grace changed") |
| + } |
| +} |
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go| index b5c2b036e..c0ac4dee7 100644 |
| --- a/internal/host/demo_jobs.go |
| +++ b/internal/host/demo_jobs.go |
| @@ -24,6 +24,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/interactive" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "golang.org/x/net/websocket" |
| ) |
| @@ -38,6 +39,12 @@ type demoRootBuilder interface { |
| } |
| type demoWorker struct { |
| + reg *registry.Registry |
| + data release.Store |
| + dataPrefix string |
| + purge func(context.Context, instancectl.DemoPurgeRequest) error |
| + acknowledge func(context.Context, []byte) error |
| + complete func(context.Context, []byte) error |
| cfg demo.Config |
| pub ed25519.PublicKey |
| box, base string |
| @@ -50,7 +57,7 @@ type demoWorker struct { |
| notify func() |
| } |
| -func startDemoWorker(ctx context.Context) { |
| +func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.Store, dataPrefix string) { |
| if os.Getenv("CARLOS_DEMO_BUILD_WORKER") != "1" { |
| return |
| } |
| @@ -86,9 +93,11 @@ func startDemoWorker(ctx context.Context) { |
| log.Printf("agent: demo worker: console origin unavailable") |
| return |
| } |
| - w := &demoWorker{cfg: cfg, pub: pub, box: identity.Label, base: base, store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }} |
| + w := &demoWorker{reg: reg, data: data, dataPrefix: dataPrefix, purge: instancectl.NewClient(controlsock.Path).PurgeDemo, cfg: cfg, pub: pub, box: identity.Label, base: base, store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }} |
| w.http = &http.Client{Timeout: demobuild.ResultGrace, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| w.pickup = w.pickupHTTP |
| + w.acknowledge = w.acknowledgeDemoHTTP |
| + w.complete = func(ctx context.Context, b []byte) error { return w.acknowledgeDemoPhaseHTTP(ctx, b, true) } |
| go func() { |
| delay := time.Second |
| for { |
| @@ -384,6 +393,11 @@ func (w *demoWorker) Connect(ctx context.Context) error { |
| if demobuild.DecodeMessage(raw, &msg) != nil { |
| return errors.New("demo-build: malformed stream") |
| } |
| + if len(msg.Retirement) > 0 { |
| + if err := w.retireDemo(ctx, msg.Retirement); err != nil { |
| + return err |
| + } |
| + } |
| if msg.Reconcile && w.notify != nil { |
| w.notify() |
| } |
diff --git a/internal/instancectl/demo_cleanup.go b/internal/instancectl/demo_cleanup.go| new file mode 100644 |
| index 000000000..4461d9685 |
| --- /dev/null |
| +++ b/internal/instancectl/demo_cleanup.go |
| @@ -0,0 +1,227 @@ |
| +package instancectl |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +type DemoPurgeRequest struct { |
| + Demo demo.Descriptor `json:"demo"` |
| + Jobs []string `json:"jobs"` |
| +} |
| + |
| +func (c *Client) PurgeDemo(ctx context.Context, in DemoPurgeRequest) error { |
| + b, err := json.Marshal(in) |
| + if err != nil { |
| + return err |
| + } |
| + req, err := http.NewRequestWithContext(ctx, "POST", "http://control/demo-purge", bytes.NewReader(b)) |
| + if err != nil { |
| + return err |
| + } |
| + res, err := c.httpClient().Do(req) |
| + if err != nil { |
| + return err |
| + } |
| + defer res.Body.Close() |
| + if res.StatusCode != 204 { |
| + return demo.ErrPolicy |
| + } |
| + return nil |
| +} |
| +func (s *Server) lockDemo(host string) func() { |
| + v, _ := s.demoLocks.LoadOrStore(host, &sync.Mutex{}) |
| + m := v.(*sync.Mutex) |
| + m.Lock() |
| + return m.Unlock |
| +} |
| +func (s *Server) handleDemoPurge(w http.ResponseWriter, r *http.Request) { |
| + defer r.Body.Close() |
| + dec := json.NewDecoder(io.LimitReader(r.Body, 16385)) |
| + dec.DisallowUnknownFields() |
| + var in DemoPurgeRequest |
| + if dec.Decode(&in) != nil || dec.Decode(new(any)) != io.EOF || len(in.Jobs) > 61 { |
| + http.Error(w, "DEMO-EXPIRED", 400) |
| + return |
| + } |
| + effect := func() error { return s.purgeDemoWithJobs(r.Context(), in.Demo, in.Jobs) } |
| + var err error |
| + if s.DemoPurgeGuard == nil { |
| + err = demo.ErrPolicy |
| + } else { |
| + err = s.DemoPurgeGuard(r.Context(), effect) |
| + } |
| + if err != nil { |
| + http.Error(w, "DEMO-EXPIRED", 409) |
| + return |
| + } |
| + w.WriteHeader(204) |
| +} |
| + |
| +func (s *Server) purgeDemoLocal(ctx context.Context, d demo.Descriptor) error { |
| + return s.purgeDemoWithJobs(ctx, d, nil) |
| +} |
| +func (s *Server) purgeDemoWithJobs(ctx context.Context, d demo.Descriptor, jobs []string) error { |
| + if !s.DemoBox || !provision.ValidHostShape(d.Host) || d.ID == "" || d.Lifetime == "" || s.HostDemo == nil || s.CgroupRoot == "" || s.DataRoot == "" || s.DemoRunRoot == "" { |
| + return demo.ErrPolicy |
| + } |
| + name, _, ok := strings.Cut(d.Host, ".") |
| + if !ok || !s.DemoConfig.BoxMode() || s.DemoConfig.ValidateBinding(d, s.DemoConfig.Account, demo.AppPrefix+name, d.Host, d.Lifetime, s.DemoConfig.Fleet) != nil { |
| + return demo.ErrPolicy |
| + } |
| + defer s.lockDemo(d.Host)() |
| + rt, err := s.HostDemo(d.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if rt != nil && (!rt.IsDemo() || rt.DemoID != d.ID || rt.DemoHost != d.Host || rt.DemoLifetime != d.Lifetime || rt.Status != "releasing" || rt.HoldOp != "demo-retire/"+d.ID || rt.DemoExpiresAt != d.ExpiresAt || rt.Account != s.DemoConfig.Account || rt.App != demo.AppPrefix+name) { |
| + return demo.ErrPolicy |
| + } |
| + // Root-owned job markers bind scratch to this demo; a current foreign |
| + // route was refused above before any build or instance was stopped. |
| + if len(jobs) > 0 { |
| + cleaner, ok := s.DemoBuilder.(interface { |
| + PurgeDemo(context.Context, string, []string) error |
| + }) |
| + if !ok { |
| + return demo.ErrPolicy |
| + } |
| + if err := cleaner.PurgeDemo(ctx, d.ID, jobs); err != nil { |
| + return err |
| + } |
| + } |
| + id := provision.InstanceID(d.Host) |
| + if rt == nil { |
| + // Registry absence is only an acknowledgment of nothing present, never |
| + // authority to remove an unbound local directory. |
| + for _, root := range []string{s.DataRoot, s.DemoRunRoot, s.ExeRoot} { |
| + if root == "" { |
| + continue |
| + } |
| + if _, err := os.Lstat(filepath.Join(root, id)); !errors.Is(err, os.ErrNotExist) { |
| + return demo.ErrPolicy |
| + } |
| + } |
| + return nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, s.waitBudget()) |
| + defer cancel() |
| + out, err := s.Systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "--no-pager") |
| + if err != nil { |
| + return err |
| + } |
| + units := map[string]bool{UnitName(RoleRun, d.Host): true} |
| + for _, line := range strings.Split(out, "\n") { |
| + f := strings.Fields(line) |
| + if len(f) == 0 { |
| + continue |
| + } |
| + _, esc, ok := ParseUnitName(f[0]) |
| + if ok && esc == Escape(id) { |
| + units[f[0]] = true |
| + } |
| + } |
| + // A stopped unit may have been garbage-collected by systemd while its |
| + // generation files remain. Discover only canonical keys of this host. |
| + for _, root := range []string{s.ExeRoot, s.DropInDir} { |
| + if root == "" { |
| + continue |
| + } |
| + entries, err := os.ReadDir(root) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + for _, e := range entries { |
| + if root == s.ExeRoot { |
| + if iid, n, ok := ParseGenKey(e.Name()); ok && iid == id { |
| + units[GenUnitName(d.Host, n)] = true |
| + } |
| + } |
| + if root == s.DropInDir { |
| + unit := strings.TrimSuffix(e.Name(), ".d") |
| + if esc, _, ok := ParseGenUnitName(unit); ok && esc == Escape(id) { |
| + units[unit] = true |
| + } |
| + } |
| + } |
| + } |
| + for unit := range units { |
| + if _, err = s.Systemctl(ctx, "stop", unit); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err = s.Systemctl(ctx, "stop", SliceName(d.Host)); err != nil { |
| + return err |
| + } |
| + for unit := range units { |
| + out, err = s.Systemctl(ctx, "show", unit, "-p", "ActiveState") |
| + if err != nil { |
| + return err |
| + } |
| + state := parseShow(out)["ActiveState"] |
| + if state != "inactive" && state != "failed" { |
| + return demo.ErrPolicy |
| + } |
| + if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(d.Host), unit, time.Millisecond); err != nil { |
| + return err |
| + } |
| + } |
| + if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(d.Host), "", time.Millisecond); err != nil { |
| + return err |
| + } |
| + // Every path is a derived direct child. RemoveAllBeneath holds directory |
| + // descriptors and never follows a leaf or intermediate symlink. |
| + remove := func(root, name string) error { |
| + if root == "" { |
| + return nil |
| + } |
| + err := instancefs.RemoveAllBeneath(root, name) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + return err |
| + } |
| + // Delete the database before its local initialization proof. |
| + dir := filepath.Join(s.DataRoot, id) |
| + for _, suffix := range []string{".db-wal", ".db-shm", ".db"} { |
| + if err := instancefs.RemoveBeneath(dir, d.Host+suffix); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + } |
| + if err = remove(s.DataRoot, id); err != nil { |
| + return err |
| + } |
| + if err = remove(s.DemoRunRoot, id); err != nil { |
| + return err |
| + } |
| + if err = remove(s.ExeRoot, id); err != nil { |
| + return err |
| + } |
| + for unit := range units { |
| + if err = remove(s.DropInDir, unit+".d"); err != nil { |
| + return err |
| + } |
| + if _, n, ok := ParseGenUnitName(unit); ok { |
| + if err = remove(s.ExeRoot, GenKey(d.Host, n)); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return s.purgeDemoVersions(ctx, d) |
| +} |
diff --git a/internal/instancectl/demo_cleanup_test.go b/internal/instancectl/demo_cleanup_test.go| new file mode 100644 |
| index 000000000..fdb1d93da |
| --- /dev/null |
| +++ b/internal/instancectl/demo_cleanup_test.go |
| @@ -0,0 +1,154 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/release" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestDemoLocalPurge(t *testing.T) { |
| + for _, fault := range []string{"", "live", "populated", "stop", "foreign", "ordinary", "symlink"} { |
| + t.Run(fault, func(t *testing.T) { |
| + host := "bright-otter-42.example.com" |
| + d := demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: host, Lifetime: "life-1", ExpiresAt: 1800000000} |
| + data, run := t.TempDir(), t.TempDir() |
| + id := provision.InstanceID(host) |
| + for _, base := range []string{data, run} { |
| + for _, name := range []string{id, "sibling"} { |
| + if err := os.Mkdir(filepath.Join(base, name), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + for _, name := range []string{id + ".db", id + ".db-wal", id + ".db-shm", id + ".db.demo-init-pending", "assignment.json"} { |
| + if err := os.WriteFile(filepath.Join(data, id, name), []byte("private"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + outside := t.TempDir() |
| + os.WriteFile(filepath.Join(outside, "keep"), []byte("keep"), 0600) |
| + if fault == "symlink" { |
| + os.Symlink(outside, filepath.Join(data, id, "outside")) |
| + } |
| + cg := t.TempDir() |
| + slice := filepath.Join(cg, parentSlices, SliceName(host)) |
| + os.MkdirAll(slice, 0700) |
| + populated := "populated 0\n" |
| + if fault == "populated" { |
| + populated = "populated 1\n" |
| + } |
| + os.WriteFile(filepath.Join(slice, "cgroup.events"), []byte(populated), 0600) |
| + stopped := false |
| + s := &Server{DemoConfig: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}, DemoBox: fault != "ordinary", DataRoot: data, DemoRunRoot: run, CgroupRoot: cg, cgroupWaitBudget: 5 * time.Millisecond, |
| + HostDemo: func(string) (*registry.Route, error) { |
| + rt := ®istry.Route{Account: "shop", App: "tmp-demo-bright-otter-42", Host: host, DemoID: d.ID, DemoHost: host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt, Status: "releasing", HoldOp: "demo-retire/" + d.ID} |
| + if fault == "foreign" { |
| + rt.DemoID = "AQEBAQEBAQEBAQEBAQEBAQ" |
| + rt.Status = "ready" |
| + rt.HoldOp = "" |
| + } |
| + return rt, nil |
| + }, |
| + Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + if args[0] == "stop" { |
| + stopped = true |
| + if fault == "stop" { |
| + return "", errors.New("stop failure") |
| + } |
| + return "", nil |
| + } |
| + if args[0] == "list-units" { |
| + return UnitName(RoleRun, host) + " loaded inactive dead -\n", nil |
| + } |
| + if args[0] == "show" { |
| + if fault == "live" { |
| + return "ActiveState=active\n", nil |
| + } |
| + return "ActiveState=inactive\n", nil |
| + } |
| + return "", nil |
| + }} |
| + err := s.purgeDemoLocal(t.Context(), d) |
| + success := fault == "" || fault == "symlink" |
| + if success && err != nil { |
| + t.Fatal(err) |
| + } |
| + if !success && err == nil { |
| + t.Fatal("unsafe purge accepted") |
| + } |
| + _, stat := os.Stat(filepath.Join(data, id, id+".db")) |
| + if success && (!stopped || !errors.Is(stat, os.ErrNotExist)) { |
| + t.Fatalf("stop before delete: %v %v", stopped, stat) |
| + } |
| + if !success && stat != nil { |
| + t.Fatalf("unproved deletion: %v", stat) |
| + } |
| + for _, p := range []string{filepath.Join(data, "sibling"), filepath.Join(run, "sibling"), filepath.Join(outside, "keep")} { |
| + if _, err := os.Stat(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if strings.Contains(id, "/") { |
| + t.Fatal("bad derived ID") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoLocalPurgeVersions(t *testing.T) { |
| + for _, pin := range []bool{false, true} { |
| + t.Run(fmt.Sprint(pin), func(t *testing.T) { |
| + cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"} |
| + host := "bright-otter-42.example.com" |
| + app := "tmp-demo-bright-otter-42" |
| + version := "v0.0.0-demo.1" |
| + d := demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: host, Lifetime: "life", ExpiresAt: 1800000000} |
| + opt, data := t.TempDir(), t.TempDir() |
| + for _, name := range []string{app, "sibling"} { |
| + if err := release.StageArtifact(opt, "shop", version, name, []byte("binary")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.StageManifest(opt, "shop", version, name, []byte("{}")); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.PointLive(opt, "sibling.example.com", "shop", version, "sibling"); err != nil { |
| + t.Fatal(err) |
| + } |
| + routes := []registry.Route{{Host: "sibling.example.com", Account: "shop", App: "sibling", Version: version}} |
| + s := &Server{OptDir: opt, DataRoot: filepath.Join(data, "instances"), DemoConfig: cfg, DemoRoutes: func() ([]registry.Route, error) { return routes, nil }} |
| + if pin { |
| + if err := release.WriteGenerations(release.GenerationsPath(data), release.Generations{Paths: map[string][]string{host: {release.VersionPath(opt, "shop", version, app)}}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + err := s.purgeDemoVersions(t.Context(), d) |
| + if pin && err == nil { |
| + t.Fatal("generation pin ignored") |
| + } |
| + if !pin && err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(release.VersionPath(opt, "shop", version, "sibling")); err != nil { |
| + t.Fatal("sibling removed") |
| + } |
| + if !pin { |
| + for _, suffix := range []string{"", ".manifest.json"} { |
| + if _, err := os.Stat(release.VersionPath(opt, "shop", version, app) + suffix); !os.IsNotExist(err) { |
| + t.Fatal("demo staged file remains") |
| + } |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/instancectl/demo_policy.go b/internal/instancectl/demo_policy.go| index 313138e8a..5fbc2c225 100644 |
| --- a/internal/instancectl/demo_policy.go |
| +++ b/internal/instancectl/demo_policy.go |
| @@ -11,6 +11,8 @@ import ( |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| // demoHandler refuses unsupported launch and mutation doors before dispatch. |
| @@ -24,6 +26,17 @@ func (s *Server) demoHandler(next http.Handler) http.Handler { |
| http.Error(w, demo.ErrPolicy.Error(), http.StatusForbidden) |
| return |
| } |
| + if r.Method == "POST" && r.URL.Path == "/start" && provision.ValidHostShape(r.URL.Query().Get("host")) { |
| + host := r.URL.Query().Get("host") |
| + defer s.lockDemo(host)() |
| + if s.HostDemo != nil { |
| + rt, err := s.HostDemo(host) |
| + if err != nil || rt == nil || !rt.IsDemo() || registry.IsHold(rt.Status) { |
| + http.Error(w, "DEMO-POLICY", 409) |
| + return |
| + } |
| + } |
| + } |
| next.ServeHTTP(w, r) |
| }) |
| } |
diff --git a/internal/instancectl/demo_versions.go b/internal/instancectl/demo_versions.go| new file mode 100644 |
| index 000000000..aaedbdd0f |
| --- /dev/null |
| +++ b/internal/instancectl/demo_versions.go |
| @@ -0,0 +1,100 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| +) |
| + |
| +// Only this app's staged files are eligible. Version directories can contain |
| +// several apps, so deleting a whole version would remove a sibling's build. |
| +func (s *Server) purgeDemoVersions(ctx context.Context, d demo.Descriptor) error { |
| + if s.OptDir == "" { |
| + return nil |
| + } // Tests of the local data boundary need no staged tree. |
| + if s.DemoRoutes == nil || !s.DemoConfig.BoxMode() { |
| + return demo.ErrPolicy |
| + } |
| + name, _, ok := strings.Cut(d.Host, ".") |
| + if !ok { |
| + return demo.ErrPolicy |
| + } |
| + account, app := s.DemoConfig.Account, demo.AppPrefix+name |
| + if s.DemoConfig.ValidateBinding(d, account, app, d.Host, d.Lifetime, s.DemoConfig.Fleet) != nil { |
| + return demo.ErrPolicy |
| + } |
| + |
| + err := instancefs.RemoveBeneath(filepath.Join(s.OptDir, "live"), d.Host) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + routes, err := s.DemoRoutes() |
| + if err != nil { |
| + return err |
| + } |
| + others := make([]registry.Route, 0, len(routes)) |
| + for _, rt := range routes { |
| + if rt.Host != d.Host { |
| + others = append(others, rt) |
| + } |
| + } |
| + // An incomplete publication or a generation still in memory delays the |
| + // acknowledgment. The normal activator retires its held route on reload. |
| + pins, err := release.GenerationPins(release.GenerationsPath(filepath.Dir(s.DataRoot)), func() ([]registry.Route, error) { return routes, nil }).StagedPins(ctx, s.OptDir) |
| + if err != nil { |
| + return err |
| + } |
| + live, err := release.LivePins(s.OptDir) |
| + if err != nil { |
| + return err |
| + } |
| + versions, err := os.ReadDir(filepath.Join(s.OptDir, "versions")) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + for _, v := range versions { |
| + if !v.IsDir() || !release.ValidVersion(v.Name()) { |
| + continue |
| + } |
| + path := release.VersionPath(s.OptDir, account, v.Name(), app) |
| + if pins[path] { |
| + return demo.ErrPolicy |
| + } |
| + // A live link to this app or any route naming this app protects its files. |
| + if live[v.Name()] { |
| + entries, err := os.ReadDir(filepath.Join(s.OptDir, "live")) |
| + if err != nil { |
| + return err |
| + } |
| + for _, e := range entries { |
| + dst, err := filepath.EvalSymlinks(filepath.Join(s.OptDir, "live", e.Name())) |
| + if err != nil { |
| + return err |
| + } |
| + if dst == path { |
| + return demo.ErrPolicy |
| + } |
| + } |
| + } |
| + for _, rt := range others { |
| + if rt.Account == account && rt.App == app { |
| + return demo.ErrPolicy |
| + } |
| + } |
| + for _, name := range []string{app, app + ".manifest.json"} { |
| + if err = instancefs.RemoveAllBeneath(filepath.Dir(path), name); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/instancectl/rootfs.go b/internal/instancectl/rootfs.go| index 8643ee1e5..f804d4efa 100644 |
| --- a/internal/instancectl/rootfs.go |
| +++ b/internal/instancectl/rootfs.go |
| @@ -39,8 +39,11 @@ import ( |
| // RegistryView is what the control service reads of the registry: a |
| // host's account and app, and its runtime. |
| type RegistryView struct { |
| - HostApp func(host string) (acct, app string, err error) |
| - HostRuntime func(host string) (string, error) |
| + DemoPurgeGuard func(context.Context, func() error) error |
| + DemoRoutes func() ([]registry.Route, error) |
| + HostDemo func(string) (*registry.Route, error) |
| + HostApp func(host string) (acct, app string, err error) |
| + HostRuntime func(host string) (string, error) |
| } |
| // boxPlatform is release.BoxPlatform, a var so a test on another platform |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 1d0963ade..e8892217a 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -29,6 +29,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demobuild" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -42,8 +43,14 @@ import ( |
| // source; nothing from a request reaches systemctl as a string. |
| type Server struct { |
| // DemoBox is fixed from root-owned environment at service startup. |
| - DemoBox bool |
| - DemoBuilder demoBuilder |
| + DemoBox bool |
| + DemoBuilder demoBuilder |
| + HostDemo func(string) (*registry.Route, error) |
| + DemoRunRoot string |
| + DemoConfig demo.Config |
| + DemoRoutes func() ([]registry.Route, error) |
| + DemoPurgeGuard func(context.Context, func() error) error |
| + demoLocks sync.Map |
| ClaimStop http.Handler |
| // ClaimHeldRelease is the moves held-release route's handler (moves |
| @@ -291,6 +298,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| OptDir: "/opt/carlos", |
| HostApp: view.HostApp, |
| HostRuntime: view.HostRuntime, |
| + HostDemo: view.HostDemo, |
| + DemoConfig: cfg, |
| + DemoRoutes: view.DemoRoutes, |
| + DemoPurgeGuard: view.DemoPurgeGuard, |
| + DemoRunRoot: "/run/carlos/instances", |
| ProbeImage: BuildProbeImage, |
| ProbeImageFile: ProbeImagePath, |
| RootfsProbeOut: filepath.Join(controlsock.Dir, "rootfs-probe.out"), |
| @@ -358,8 +370,19 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { |
| done := make(chan struct{}) |
| go func() { |
| defer close(done) |
| - if err := s.DemoBuilder.Initialize(ctx); err != nil { |
| - s.logf("instance-control: demo builder: %v", err) |
| + for { |
| + if err := s.DemoBuilder.Initialize(ctx); err == nil { |
| + return |
| + } else { |
| + s.logf("instance-control: demo builder: %v", err) |
| + } |
| + timer := time.NewTimer(5 * time.Second) |
| + select { |
| + case <-ctx.Done(): |
| + timer.Stop() |
| + return |
| + case <-timer.C: |
| + } |
| } |
| }() |
| defer func() { cancel(); <-done }() |
| @@ -444,6 +467,7 @@ func (s *Server) peerOK(c net.Conn) error { return s.PeerOK(c) } |
| func (s *Server) Handler() http.Handler { |
| mux := http.NewServeMux() |
| if s.DemoBox { |
| + mux.HandleFunc("POST /demo-purge", s.handleDemoPurge) |
| mux.HandleFunc("POST /demo-build", s.handleDemoBuild) |
| mux.HandleFunc("GET /demo-build/ready", s.handleDemoBuildReady) |
| } |
diff --git a/internal/provision/demo_census_test.go b/internal/provision/demo_census_test.go| index b0d61927c..defe27934 100644 |
| --- a/internal/provision/demo_census_test.go |
| +++ b/internal/provision/demo_census_test.go |
| @@ -12,6 +12,11 @@ func demoWriteCensusInventory() []censusEntry { |
| } |
| } |
| for _, next := range []censusEntry{ |
| + // Task 8: retain local demo identity until the signed retirement worker |
| + // has purged it. The early continue adds no record write or key site; |
| + // hub and ordinary retirement still use the existing path. Covered by |
| + // TestDemoOfflineRetirementKeepsBinding; controller review remains pending. |
| + {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "2c4de9124c2536425cbab2336db28ea1adf0dd0120ad45fd245370ee7f014337"}, |
| // Registers demo HTTP handlers; the instance/sidecar strings are routes. |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "033513f39cf26dc83b949fc7997f4c1eecd62f08405610b3ac9f6c529b1d0433"}, |
| // Skips demo records before the existing typed fleet-box CAS. |
diff --git a/internal/provision/demo_routing_test.go b/internal/provision/demo_routing_test.go| index d90b68993..92a234621 100644 |
| --- a/internal/provision/demo_routing_test.go |
| +++ b/internal/provision/demo_routing_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| func TestDemoDomainRouting(t *testing.T) { |
| @@ -72,3 +73,38 @@ func TestDemoDomainAdoptionRefusesIdentityLoss(t *testing.T) { |
| t.Fatal("demo route adopted into ordinary authority") |
| } |
| } |
| + |
| +func TestDemoOfflineRetirementKeepsBinding(t *testing.T) { |
| + store := dirStore(t) |
| + account, _ := fwdSetup(t, store) |
| + id, err := demo.NewIdentity(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := Record{Schema: 1, Account: account, App: id.App, Host: id.Name + ".example.com", Slug: id.Name, Channel: "edge", Region: "fleet/demo", FleetBox: "box", CreatedAt: time.Now(), Demo: &demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}} |
| + if err = PutManifest(t.Context(), store, account, id.App, Manifest{Schema: 1, App: id.App, Domain: "example.com", Channel: "edge"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + mustCreate(t, store, rec) |
| + reg, err := registry.Open(t.TempDir() + "/registry.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + cfg := ReconcileConfig{Region: rec.Region, FleetBox: rec.FleetBox, DataDir: t.TempDir()} |
| + mustPass(t, store, reg, cfg) |
| + if err = release.TrashApp(t.Context(), store, account, id.App, "expiry", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + mustPass(t, store, reg, cfg) |
| + if row := getRow(t, reg, rec.Host); row == nil || row.DemoID != id.ID { |
| + t.Fatal("normal removal erased cleanup binding") |
| + } |
| + if err = store.Delete(t.Context(), RecordKey(account, id.App, rec.Host)); err != nil { |
| + t.Fatal(err) |
| + } |
| + mustPass(t, store, reg, cfg) |
| + if row := getRow(t, reg, rec.Host); row == nil || row.DemoLifetime != "life" { |
| + t.Fatal("record absence erased cleanup binding") |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index 72d8927de..b15aecae6 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -2287,6 +2287,11 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| neither := collides(sc) |
| removed = map[string]bool{} |
| for _, rt := range routes { |
| + // The demo worker retains the binding until signed retirement has |
| + // stopped and purged local state. A missing record alone cannot erase it. |
| + if cfg.FleetBox != "" && rt.IsDemo() { |
| + continue |
| + } |
| // gone is the judge's evidence that the row's OWN record is |
| // absent or stale (claims-off only, below): it also outranks a |
| // keep view, which keys by hostname and cannot vouch for a row |
diff --git a/internal/release/trash.go b/internal/release/trash.go| index 28518d52c..33ae4f0c9 100644 |
| --- a/internal/release/trash.go |
| +++ b/internal/release/trash.go |
| @@ -214,7 +214,7 @@ func PurgeAppGuards(ctx context.Context, s Store, pub ed25519.PublicKey, acct, a |
| // clock) whose sweep leaves every key keep reports: the console's lifetime |
| // purge has already retired the instance records through their own protocol |
| // and keeps the sweep off those keys. The guards run again first, and the |
| -// marker still goes last. |
| +// marker still goes last unless keep explicitly retains it. |
| func PurgeAppExcept(ctx context.Context, s Store, pub ed25519.PublicKey, acct, app string, wantDeletedAt, now time.Time, keep func(key string) bool) error { |
| return purgeApp(ctx, s, pub, acct, app, trashedAtCheck(acct, app, wantDeletedAt), keep) |
| } |
| @@ -318,7 +318,7 @@ func purgeStoreGuard(ctx context.Context, s Store, acct, app string) error { |
| } |
| // purgeSweep is purgeApp's destruction: every key of the app but those keep |
| -// reports, the trash marker last. |
| +// reports, the trash marker last unless explicitly kept for a durable checkpoint. |
| func purgeSweep(ctx context.Context, s Store, acct, app string, keep func(string) bool) error { |
| prefix := appPrefix(acct, app) |
| marker := AppTombstoneKey(acct, app) |
| @@ -377,6 +377,9 @@ func purgeSweep(ctx context.Context, s Store, acct, app string, keep func(string |
| return fmt.Errorf("release: purge %s: %w", key, err) |
| } |
| } |
| + if keep != nil && keep(marker) { |
| + return nil |
| + } |
| return s.Delete(ctx, marker) |
| } |
| func TrashApp(ctx context.Context, s Store, acct, app, actor string, now time.Time) (claimResult0 error) { |