carlos / platform Public

console: purge releases domain claims; no deleting accounts with domains

Every purge branch releases the app's custom-domain claims (this app's
aliases and instance catch-alls on hosts outside the apps domain) before
the step that removes the trash marker: inside purgeAppWithLifetimes after
the per-host retirements, and on the lifetimes-off purge door, trash sweep,
expiry pass and demo retirement, after the purge's own guards. A failed
release stops the purge with the marker and row in place for a retry.
releaseDomainHost is split so the purge reuses detach's removal under the
locks it already holds.

Account deletion is refused, naming the domains, while the account holds a
registration or a live purchase: checked in deletionRefused (before the
sign-in and again under the billing hold) and re-checked in
Store.DeleteAccount's transaction. Refusal copy is a draft.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fc181e1215b8fed4a09ee2bc19ef267810604dea parent 4e7c3f3
8 files changed, +538 −14
  • internal/console/demo_expiry.go +3 −1
  • internal/console/domainattach.go +14 −4
  • internal/console/domainbuy_copy.go +17 −0
  • internal/console/expirypass.go +3 −1
  • internal/console/lifetimes_purge.go +137 −1
  • internal/console/lifetimes_purge_test.go +225 −0
  • internal/console/ownership.go +43 −7
  • internal/console/ownership_test.go +96 −0
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index b4c8ced1f..bbbefa33a 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -333,7 +333,9 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
// 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 {
+ } else if err = s.releaseAppDomainClaims(ctx, d.AccountSqid, d.App); err == nil {
+ // Guards checked above; the claims before the contents, as
+ // purgeAppWithLifetimes releases them.
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 {
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index c756569f2..1ccebd126 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -434,13 +434,22 @@ func domainNotAttached() *doorRefusal {
// gone releases its hosts through it too (finishPurchaseUnpointed). host is
// already normalized.
func (s *Server) releaseDomainHost(ctx context.Context, acct *Account, app, host, principal string) *doorRefusal {
- notAttached := domainNotAttached()
if lifetimesUnit(ctx) {
// Admitted on: the claim read, the record and the claim release
// run inside the app lock and the hostname exclusion, the same two
// every attach of the hostname holds from its claim to its record.
defer s.lockAppHost(acct.Sqid, app, host)()
}
+ return s.releaseDomainHostHeld(ctx, acct, app, host, principal, true)
+}
+
+// releaseDomainHostHeld is releaseDomainHost inside the locks it takes
+// (admitted on, the caller holds s.lockApp and host's exclusion). record
+// false skips the first-route record step: the purge with lifetimes has
+// already retired every record of the app, and an instance catch-all has
+// none.
+func (s *Server) releaseDomainHostHeld(ctx context.Context, acct *Account, app, host, principal string, record bool) *doorRefusal {
+ notAttached := domainNotAttached()
claim, err := domains.GetClaim(ctx, s.cfg.Releases, host)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
@@ -453,9 +462,10 @@ func (s *Server) releaseDomainHost(ctx context.Context, acct *Account, app, host
if claim.Account != acct.Sqid || claim.App != app {
return notAttached
}
- if claim.Route == "" && lifetimesUnit(ctx) {
+ firstRoute := record && claim.Route == ""
+ if firstRoute && lifetimesUnit(ctx) {
// First-route, admitted on: the record retires through its
- // tombstone inside the two locks held above, before the claim.
+ // tombstone inside the two locks the caller holds, before the claim.
ref, err := s.detachRetireLocked(ctx, acct.Sqid, app, host)
if err != nil {
log.Printf("console: detach %s: record delete: %v", host, err)
@@ -465,7 +475,7 @@ func (s *Server) releaseDomainHost(ctx context.Context, acct *Account, app, host
if ref != nil {
return ref
}
- } else if claim.Route == "" {
+ } else if firstRoute {
// First-route: the record goes before the claim, the mirror of
// attach. A record left behind by a released claim would keep a
// route alive for a host anyone may now claim.
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go
index a7e8e3de6..93828a285 100644
--- a/internal/console/domainbuy_copy.go
+++ b/internal/console/domainbuy_copy.go
@@ -3,8 +3,10 @@ package console
import (
"context"
"errors"
+ "fmt"
"log"
"net/http"
+ "strings"
"github.com/carlosframework/platform/internal/domainreg"
"github.com/carlosframework/platform/internal/domains"
@@ -115,3 +117,18 @@ func (s *Server) domainBuyRegistrarRefusal(ctx context.Context, acct *Account, n
}
return domainBuyErrorRefusal(err)
}
+
+// accountDomainsCopy is account deletion's refusal while the account holds
+// registered domains or a purchase still under way (Plan 2a Task 6). DRAFTS
+// (2026-11-19), awaiting the copy pass. Named takes the domains, comma
+// separated; Count is the store's own re-check, which knows only how many.
+var accountDomainsCopy = struct{ Named, Count, Unreadable string }{
+ Named: "This account holds domains it registered or is buying: %s. Transfer each one out or release it, then delete the account.",
+ Count: "This account holds domains it registered or is buying. Transfer each one out or release it, then delete the account.",
+ Unreadable: "Could not check whether this account holds domains. Nothing was deleted.",
+}
+
+// accountDomainsRefusal is the deletion refusal naming domains.
+func accountDomainsRefusal(domains []string) string {
+ return fmt.Sprintf(accountDomainsCopy.Named, strings.Join(domains, ", "))
+}
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go
index 0919d80a8..f0947800b 100644
--- a/internal/console/expirypass.go
+++ b/internal/console/expirypass.go
@@ -248,7 +248,9 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide
// Every lifetime of the app retired first, under the lock this
// pass holds (lifetimes_purge.go).
err = s.purgeAppWithLifetimes(ctx, r.Sqid, r.App, time.Unix(life.PurgeFor, 0), now)
- } else {
+ } else if err = s.releaseAppDomainClaimsGuarded(ctx, r.Sqid, r.App, time.Unix(life.PurgeFor, 0), now); err == nil {
+ // The app's custom-domain claims went first; a failed release
+ // purges nothing and the next pass retries.
err = release.PurgeAppIfTrashedAt(ctx, s.cfg.Releases, s.cfg.ReleasePub, r.Sqid, r.App, time.Unix(life.PurgeFor, 0), now)
}
switch {
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go
index dfeedae6d..990e5497b 100644
--- a/internal/console/lifetimes_purge.go
+++ b/internal/console/lifetimes_purge.go
@@ -5,10 +5,14 @@ import (
"errors"
"fmt"
"log"
+ "net/http"
+ "os"
"sort"
+ "strings"
"sync"
"time"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -91,6 +95,12 @@ func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, wa
return fmt.Errorf("console: purge %s/%s: %s: %w", sqid, app, host, err)
}
}
+ // The app's custom-domain claims go before the marker (spec §11.7, C2),
+ // once every record of the app is retired above. A failed release
+ // returns with the marker and the row in place; the next run resumes.
+ if err := s.releaseAppDomainClaims(ctx, sqid, app); err != nil {
+ return err
+ }
return release.PurgeAppExcept(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now, func(key string) bool {
return provision.IsInstanceRecordKeyOf(key, sqid, app) || len(keepMarker) > 0 && keepMarker[0] && key == release.AppTombstoneKey(sqid, app)
})
@@ -245,7 +255,10 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now
err = s.purgeAppWithLifetimes(ctx, a.Account, a.App, tomb.DeletedAt, now)
} else {
s.noteRecordDeletion(a.Account, a.App, time.Now()) // the canary-retire guard's evidence, first (#415)
- err = release.PurgeAppIfTrashedAt(ctx, s.cfg.Releases, s.cfg.ReleasePub, a.Account, a.App, tomb.DeletedAt, now)
+ // The claims before the marker; a failed release purges nothing.
+ if err = s.releaseAppDomainClaimsGuarded(ctx, a.Account, a.App, tomb.DeletedAt, now); err == nil {
+ err = release.PurgeAppIfTrashedAt(ctx, s.cfg.Releases, s.cfg.ReleasePub, a.Account, a.App, tomb.DeletedAt, now)
+ }
}
if err != nil {
log.Printf("console: trash sweep: purge %s/%s: %v", a.Account, a.App, err)
@@ -262,6 +275,129 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now
}
}
+// ---- the app's custom-domain claims -------------------------------------------
+
+// purgeActor is the audit actor of the claim releases a purge makes.
+const purgeActor = "purge"
+
+// releaseAppDomainClaims releases every custom-domain claim of sqid/app
+// (spec §11.7, builder check C2): each claim whose Account and App are the
+// app's and whose host (a catch-all's parent) is a custom domain, so the
+// hosts are free for the account's other apps once the app is gone.
+// Platform names and other apps' or accounts' claims are never touched.
+//
+// Every purge branch calls it under the app lock, before the step that
+// removes the trash marker. An error stops that purge with the marker and
+// the row in place, and the next run lists the claims again and releases
+// what is left: each release is idempotent (a claim already gone, or no
+// longer the app's, is skipped).
+//
+// Admitted on, it runs inside purgeAppWithLifetimes once every record of
+// the app is retired, so it skips the record step and holds each host's
+// exclusion. Admitted off, a first-route claim's record goes before its
+// claim, as detach does, so no record outlives its claim. Under the
+// host-claim gate it does nothing: alias detach is unsupported there
+// (claim_alias.go), and that purge is the claim operation's.
+func (s *Server) releaseAppDomainClaims(ctx context.Context, sqid, app string) error {
+ claims, err := s.appDomainClaims(ctx, sqid, app)
+ if err != nil {
+ return err
+ }
+ return s.releaseDomainClaims(ctx, sqid, app, claims)
+}
+
+// releaseAppDomainClaimsGuarded is a lifetimes-off purge's claim release:
+// when the app holds any, the purge's own guards run first
+// (release.PurgeAppGuards, want's clock included), so a purge they would
+// refuse releases nothing. The purge call that follows runs them again.
+func (s *Server) releaseAppDomainClaimsGuarded(ctx context.Context, sqid, app string, want, now time.Time) error {
+ claims, err := s.appDomainClaims(ctx, sqid, app)
+ if err != nil || len(claims) == 0 {
+ return err
+ }
+ if err := release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now); err != nil {
+ return err
+ }
+ return s.releaseDomainClaims(ctx, sqid, app, claims)
+}
+
+// appDomainClaims is sqid/app's custom-domain claims, sorted by host. A
+// claim the listing could not read that may be this account's custom
+// domain (its account this one or unknown) is read again on its own: gone
+// is skipped, still unreadable fails the purge (it fails toward keeping),
+// and a readable one is judged like the rest. Nothing under the host-claim
+// gate (releaseAppDomainClaims).
+func (s *Server) appDomainClaims(ctx context.Context, sqid, app string) ([]domains.Claim, error) {
+ if s.cfg.HostClaim || s.cfg.Releases == nil {
+ return nil, nil
+ }
+ custom := func(host string) bool {
+ return s.customDomain(strings.TrimPrefix(strings.ToLower(host), "*."), sqid)
+ }
+ mine := func(c domains.Claim) bool { return c.Account == sqid && c.App == app && custom(c.Host) }
+ listed, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ return nil, fmt.Errorf("console: purge %s/%s: list the domain claims: %w", sqid, app, err)
+ }
+ var out []domains.Claim
+ for _, c := range listed {
+ if mine(c) {
+ out = append(out, c)
+ }
+ }
+ for _, u := range unread {
+ if (u.Account != "" && u.Account != sqid) || !custom(u.Host) {
+ continue
+ }
+ c, err := domains.GetClaim(ctx, s.cfg.Releases, u.Host)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ continue
+ case err != nil:
+ return nil, fmt.Errorf("console: purge %s/%s: read the domain claim %s: %w", sqid, app, u.Host, err)
+ }
+ if mine(*c) {
+ out = append(out, *c)
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Host < out[j].Host })
+ return out, nil
+}
+
+// releaseDomainClaims releases claims of sqid/app one by one through
+// detach's own removal (releaseDomainHostHeld), stopping at the first
+// failure.
+func (s *Server) releaseDomainClaims(ctx context.Context, sqid, app string, claims []domains.Claim) error {
+ if len(claims) == 0 {
+ return nil
+ }
+ acct, err := s.store.AccountBySqid(sqid)
+ if err != nil {
+ return fmt.Errorf("console: purge %s/%s: read the account: %w", sqid, app, err)
+ }
+ if acct == nil {
+ acct = &Account{Sqid: sqid} // a headless app's: no row to audit under
+ }
+ on := lifetimesUnit(ctx)
+ for _, c := range claims {
+ var ref *doorRefusal
+ release := func() error {
+ ref = s.releaseDomainHostHeld(ctx, acct, app, c.Host, purgeActor, !on && !c.Instances)
+ return nil
+ }
+ if on {
+ _ = s.withHostname(c.Host, release)
+ } else {
+ _ = release()
+ }
+ // 404: gone already, or no longer this app's. Both are done.
+ if ref != nil && ref.Status != http.StatusNotFound {
+ return fmt.Errorf("console: purge %s/%s: release the domain claim %s: %d %s", sqid, app, c.Host, ref.Status, ref.Msg)
+ }
+ }
+ return nil
+}
+
// ---- restore evidence ----------------------------------------------------------
// recordEvidenceMax bounds how many instance keys restore evidence judges;
diff --git a/internal/console/lifetimes_purge_test.go b/internal/console/lifetimes_purge_test.go
index 7fbcd500c..4d1f812ce 100644
--- a/internal/console/lifetimes_purge_test.go
+++ b/internal/console/lifetimes_purge_test.go
@@ -5,10 +5,14 @@ import (
"encoding/json"
"errors"
"net/http"
+ "net/url"
+ "os"
+ "slices"
"sync/atomic"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -452,3 +456,224 @@ func TestMaterializationHoldsTheAppLock(t *testing.T) {
}
})
}
+
+// ---- the purge releases the app's custom-domain claims ------------------------
+
+// putPurgeClaim writes host's claim for sqid/app straight into the bucket: an
+// alias of route r, or (catchall) an instance catch-all "*.<parent>".
+func putPurgeClaim(t *testing.T, s release.Store, sqid, app, host string, catchall bool) {
+ t.Helper()
+ c := domains.Claim{Schema: 1, Host: host, Account: sqid, App: app, Route: "r." + app,
+ CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ if catchall {
+ c.Route, c.Instances = "", true
+ }
+ b, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Put(context.Background(), domains.ClaimKey(host), b, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// claimHeld reports whether host's claim is still in the bucket.
+func claimHeld(t *testing.T, s release.Store, host string) bool {
+ t.Helper()
+ _, err := domains.GetClaim(context.Background(), s, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return true
+}
+
+// purgeClaimsWorld is shop (lifetimes on, apps domain oncarlos.test) holding
+// two custom-domain aliases and a catch-all, a platform name, and web, a
+// live app of the same account, holding blog.example. Then shop is trashed.
+func purgeClaimsWorld(t *testing.T) ltOn {
+ t.Helper()
+ l := newLtOn(t)
+ l.fx.srv.cfg.AppsDomain = "oncarlos.test"
+ l.mustCreate(t, ltOne)
+ if _, err := l.fx.st.CreateAppIn(OpsAccountID, "web", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ putPurgeClaim(t, l.fx.rel, "bab", ltApp, "shop.example", false)
+ putPurgeClaim(t, l.fx.rel, "bab", ltApp, "www.shop.example", false)
+ putPurgeClaim(t, l.fx.rel, "bab", ltApp, "*.shop.example", true)
+ putPurgeClaim(t, l.fx.rel, "bab", ltApp, "shop.bab.oncarlos.test", false)
+ putPurgeClaim(t, l.fx.rel, "bab", "web", "blog.example", false)
+ trashShop(t, l)
+ return l
+}
+
+// wantShopClaimsReleased: the purged app's custom-domain claims gone, its
+// platform name and the live app's claim untouched.
+func wantShopClaimsReleased(t *testing.T, s release.Store) {
+ t.Helper()
+ for _, host := range []string{"shop.example", "www.shop.example", "*.shop.example"} {
+ if claimHeld(t, s, host) {
+ t.Errorf("%s is still claimed by the purged app", host)
+ }
+ }
+ for _, host := range []string{"shop.bab.oncarlos.test", "blog.example"} {
+ if !claimHeld(t, s, host) {
+ t.Errorf("%s was released; the purge must not touch it", host)
+ }
+ }
+}
+
+func TestPurgeReleasesTheAppsDomainClaims(t *testing.T) {
+ l := purgeClaimsWorld(t)
+ if err := purgeCore(t, l.fx.srv, onCtx(t, l.fx.srv), time.Time{}); err != nil {
+ t.Fatalf("purge = %v", err)
+ }
+ wantShopClaimsReleased(t, l.fx.rel)
+ if tomb, err := release.ReadAppTombstone(context.Background(), l.fx.rel, "bab", ltApp); err != nil || tomb != nil {
+ t.Fatalf("marker = %+v %v, want gone", tomb, err)
+ }
+ // The claims go before the marker: a purge that stops between the two
+ // still holds the admission evidence it needs to resume.
+ marker := l.bucket.index("delete " + release.AppTombstoneKey("bab", ltApp))
+ for _, host := range []string{"shop.example", "www.shop.example"} {
+ if i := l.bucket.index("delete " + domains.ClaimKey(host)); i < 0 || i > marker {
+ t.Fatalf("%s released at op %d, the marker at %d: want the claim first", host, i, marker)
+ }
+ }
+ // The record retirement the purge already made is untouched.
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+}
+
+func TestPurgeDomainDetachFailureKeepsMarkerAndRetries(t *testing.T) {
+ ctx := context.Background()
+ l := purgeClaimsWorld(t)
+ tomb, _ := release.ReadAppTombstone(ctx, l.fx.rel, "bab", ltApp)
+ if _, err := l.fx.st.db.Exec(`UPDATE apps SET purge_for = ?, purge_after = ? WHERE app = ?`, tomb.DeletedAt.Unix(), tomb.DeletedAt.Unix()+1, ltApp); err != nil {
+ t.Fatal(err)
+ }
+ now := tomb.DeletedAt.Add(time.Hour)
+ pass := func() {
+ t.Helper()
+ if !l.fx.srv.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { l.fx.srv.expiryPass(ctx, now) }) {
+ t.Fatal("the expiry pass did not run")
+ }
+ }
+ // www.shop.example's release fails, after the claims sorted before it went.
+ l.bucket.setHook(failNth("delete", domains.ClaimKey("www.shop.example"), 1, false))
+ pass()
+ l.bucket.setHook(nil)
+ if tomb, err := release.ReadAppTombstone(ctx, l.fx.rel, "bab", ltApp); err != nil || tomb == nil {
+ t.Fatalf("marker = %+v %v after a failed release, want it kept", tomb, err)
+ }
+ if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life == nil {
+ t.Fatal("the row went with a claim still held")
+ }
+ if !claimHeld(t, l.fx.rel, "www.shop.example") {
+ t.Fatal("the failed release removed the claim")
+ }
+ pass()
+ wantShopClaimsReleased(t, l.fx.rel)
+ if tomb, err := release.ReadAppTombstone(ctx, l.fx.rel, "bab", ltApp); err != nil || tomb != nil {
+ t.Fatalf("marker = %+v %v after the retry, want gone", tomb, err)
+ }
+ if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life != nil {
+ t.Fatalf("row = %+v after the retry, want gone", life)
+ }
+}
+
+// TestLegacyPurgeBranchesReleaseClaims: with lifetimes off, the purge door,
+// the hourly trash sweep and the expiry pass's early purge each release the
+// app's custom-domain claims before the marker goes; a purge its guards
+// refuse releases nothing.
+func TestLegacyPurgeBranchesReleaseClaims(t *testing.T) {
+ ctx := context.Background()
+ setup := func(t *testing.T, fx *consoleFixture, app string) *hookStore {
+ t.Helper()
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "web", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ putPurgeClaim(t, fx.rel, fx.sqid, app, "shop.example", false)
+ putPurgeClaim(t, fx.rel, fx.sqid, app, "www.shop.example", false)
+ putPurgeClaim(t, fx.rel, fx.sqid, app, app+"."+fx.sqid+".oncarlos.test", false)
+ putPurgeClaim(t, fx.rel, fx.sqid, "web", "blog.example", false)
+ h := &hookStore{Store: fx.rel}
+ fx.srv.cfg.Releases = h
+ return h
+ }
+ check := func(t *testing.T, fx *consoleFixture, h *hookStore, app string) {
+ t.Helper()
+ for _, host := range []string{"shop.example", "www.shop.example"} {
+ if claimHeld(t, fx.rel, host) {
+ t.Errorf("%s is still claimed by the purged app", host)
+ }
+ }
+ for _, host := range []string{app + "." + fx.sqid + ".oncarlos.test", "blog.example"} {
+ if !claimHeld(t, fx.rel, host) {
+ t.Errorf("%s was released; the purge must not touch it", host)
+ }
+ }
+ if markerOf(t, fx, app) != nil {
+ t.Fatal("the marker is still there")
+ }
+ marker := slices.Index(h.deletes, release.AppTombstoneKey(fx.sqid, app))
+ for _, host := range []string{"shop.example", "www.shop.example"} {
+ if i := slices.Index(h.deletes, domains.ClaimKey(host)); i < 0 || i > marker {
+ t.Fatalf("%s released at delete %d, the marker at %d: want the claim first (%v)", host, i, marker, h.deletes)
+ }
+ }
+ }
+ t.Run("the purge door", func(t *testing.T) {
+ fx, c, csrf := trashPageFixture(t)
+ h := setup(t, fx, "kass")
+ status, _, body := postGated(t, fx, c, fx.u("/trash/delete"), url.Values{"csrf": {csrf}, "app": {"kass"}, "confirm": {"kass"}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("purge = %d:\n%s", status, body)
+ }
+ check(t, fx, h, "kass")
+ })
+ t.Run("the hourly trash sweep", func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ old := time.Now().Add(-31 * 24 * time.Hour)
+ trashKass(t, fx, "paul@keymail.dev", old)
+ h := setup(t, fx, "kass")
+ fx.srv.trashSweep(ctx, time.Now())
+ check(t, fx, h, "kass")
+ if lifeOf(t, fx, "kass") != nil {
+ t.Fatal("the sweep kept the row")
+ }
+ })
+ t.Run("the expiry pass", func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ now := time.Now().Truncate(time.Second)
+ trashedTemp(t, fx, "tmp-a", now.Add(-72*time.Hour))
+ h := setup(t, fx, "tmp-a")
+ fx.srv.expiryPass(ctx, now)
+ check(t, fx, h, "tmp-a")
+ if lifeOf(t, fx, "tmp-a") != nil {
+ t.Fatal("the pass kept the row")
+ }
+ })
+ t.Run("a purge its guards refuse releases nothing", func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ now := time.Now().Truncate(time.Second)
+ trashedTemp(t, fx, "tmp-a", now.Add(-72*time.Hour))
+ setup(t, fx, "tmp-a")
+ // Restored and trashed again by hand: the decision was about the
+ // old trash, so the purge refuses on the marker's clock.
+ release.RestoreApp(ctx, fx.rel, fx.sqid, "tmp-a")
+ release.TrashApp(ctx, fx.rel, fx.sqid, "tmp-a", "paul@keymail.dev", now.Add(-time.Hour))
+ rows, _ := fx.st.PurgeDueApps(now)
+ for _, r := range rows {
+ fx.srv.purgeOne(ctx, r, now, always(true))
+ }
+ for _, host := range []string{"shop.example", "www.shop.example"} {
+ if !claimHeld(t, fx.rel, host) {
+ t.Errorf("%s was released by a purge that was refused", host)
+ }
+ }
+ })
+}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index a2f9d46c1..34088e2a8 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -152,9 +152,9 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
s.deleteAccountNow(w, r, addr, acct)
}
-// deletionRefused re-checks both refusals that DeleteAccount enforces, before
-// the bucket is touched, and answers whether it refused (the response is
-// written). They are cheap, and getting them in the wrong order is
+// deletionRefused re-checks the refusals that DeleteAccount enforces (the ops
+// account, apps, domains) before the bucket is touched, and answers whether
+// it refused (the response is written). They are cheap, and getting them in the wrong order is
// expensive: tombstoning an account the store then refuses to delete would
// leave a live account marked retired, which the next reconcile pass would
// act on by dropping its registry row.
@@ -174,6 +174,22 @@ func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *A
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return true
}
+ // A registered domain, or a purchase still under way, is the
+ // customer's: the account is refused, naming them, until each is
+ // transferred out or released (spec §4.3). From deleteAccountNow this
+ // runs under the billing hold retireForDeletion took, the hold every
+ // purchase is created under (it refuses a retiring account), so no
+ // purchase can start between this check and the deletion.
+ if doms, err := s.store.DomainObligations(r.Context(), acct.ID); err != nil || len(doms) > 0 {
+ if err != nil {
+ log.Printf("console: domain obligations of %s: %v", acct.Sqid, err)
+ s.setFlash(w, "err", accountDomainsCopy.Unreadable)
+ } else {
+ s.setFlash(w, "err", accountDomainsRefusal(doms))
+ }
+ http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
+ return true
+ }
return false
}
@@ -569,7 +585,9 @@ func (s *Server) handlePurgeApp(w http.ResponseWriter, r *http.Request) {
// Admitted on: every lifetime of the app is retired first, under
// the app lock this door holds (lifetimes_purge.go).
purgeErr = s.purgeAppWithLifetimes(r.Context(), acct.Sqid, app, time.Time{}, time.Now())
- } else {
+ } else if purgeErr = s.releaseAppDomainClaimsGuarded(r.Context(), acct.Sqid, app, time.Time{}, time.Now()); purgeErr == nil {
+ // The app's custom-domain claims went first; a failed release
+ // purges nothing, and pressing the button again retries.
purgeErr = release.PurgeApp(r.Context(), s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app, time.Now())
}
if err := purgeErr; err != nil {
@@ -714,6 +732,9 @@ func transferAdvice(err error, target string) string {
}
func deletionAdvice(err error) string {
+ if errors.Is(err, errAccountHoldsDomains) {
+ return accountDomainsCopy.Count
+ }
if strings.Contains(err.Error(), "still holds") {
return "This account still holds apps. Move or retire them first — deleting an account " +
"never deletes an app."
@@ -729,6 +750,10 @@ func deletionAdvice(err error) string {
// also matched any store error that happened to contain those letters.
var errOpsAccountUndeletable = errors.New("console: the ops account cannot be deleted")
+// errAccountHoldsDomains is DeleteAccount's refusal of an account holding a
+// registered domain or a purchase still under way (spec §4.3).
+var errAccountHoldsDomains = errors.New("console: the account holds domains")
+
// ---- store ------------------------------------------------------------------
// TransferOwnership promotes `to` and demotes `from`, atomically. Both must
@@ -771,7 +796,9 @@ func (s *Store) TransferOwnership(accountID int64, from, to string, now time.Tim
// DeleteAccount retires an account that owns nothing. It refuses the ops
// account (id 1 is the platform's own) and refuses while any app is still
// homed here — an account row is cheap to delete and an app's objects, routes
-// and domains are not, so the two are never destroyed by one click.
+// and domains are not, so the two are never destroyed by one click. It
+// refuses too while the account holds a registered domain or a purchase
+// still under way (errAccountHoldsDomains, spec §4.3).
//
// The accounts ROW is MARKED (deleted_at set), never removed — this is the
// console's own path, and the identical resurrection hole the spec's §8
@@ -796,13 +823,22 @@ func (s *Store) DeleteAccount(accountID int64, now time.Time) error {
return err
}
defer tx.Rollback()
- var apps int
- if err := tx.QueryRow(`SELECT COUNT(*) FROM apps WHERE account_id = ?`, accountID).Scan(&apps); err != nil {
+ // What the account still holds, in one read inside the transaction
+ // (deletionRefused asked first): its apps, and its domains, a
+ // registration or a live purchase each (DomainObligations' set).
+ var apps, doms int
+ if err := tx.QueryRow(`SELECT (SELECT COUNT(*) FROM apps WHERE account_id = ?),
+ (SELECT COUNT(*) FROM (SELECT domain FROM domain_registrations WHERE account_id = ?
+ UNION SELECT domain FROM domain_purchases WHERE account_id = ? AND `+liveDomainPurchaseSQL+`))`,
+ accountID, accountID, accountID).Scan(&apps, &doms); err != nil {
return err
}
if apps > 0 {
return fmt.Errorf("console: this account still holds %d app(s)", apps)
}
+ if doms > 0 {
+ return fmt.Errorf("console: this account has %d domain(s) registered or being bought: %w", doms, errAccountHoldsDomains)
+ }
for _, stmt := range []string{
`DELETE FROM app_stars WHERE account_id = ?`,
`DELETE FROM getting_started_marks WHERE account_id = ?`,
diff --git a/internal/console/ownership_test.go b/internal/console/ownership_test.go
new file mode 100644
index 000000000..1863ef365
--- /dev/null
+++ b/internal/console/ownership_test.go
@@ -0,0 +1,96 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+// An account that holds registered domains, or a purchase still under way,
+// cannot be deleted (spec §4.3): a paid-for domain is the customer's, and
+// deleting the account must not silently drop it.
+
+func TestAccountDeletionRefusedWhileHoldingRegistrations(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ for _, d := range []string{"shop.example", "blog.example"} {
+ if err := o.st.AddDomainRegistration(DomainRegistration{Domain: d, AccountID: o.acct.ID}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ o.wantDeleteRefused(t, r, accountDomainsRefusal([]string{"blog.example", "shop.example"}))
+ for _, d := range []string{"shop.example", "blog.example"} {
+ if !strings.Contains(r.FlashMsg, d) {
+ t.Fatalf("refusal %q does not name %s", r.FlashMsg, d)
+ }
+ }
+ if m := readManifest(t, o.rel, o.acct.Sqid); m.Deleted() {
+ t.Fatal("the account was tombstoned in the bucket though it still holds domains")
+ }
+}
+
+// The refusal comes before the sign-in is asked for, as the app refusal
+// does, and a purchase that has ended no longer blocks.
+func TestAccountDeletionRefusedWithLivePurchase(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ p := DomainPurchase{ID: "dp_00000000000000a1", AccountID: o.acct.ID, Domain: "shop.example",
+ State: PurchaseAwaitingPayment, CreatedAt: time.Now()}
+ if err := o.st.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ status, loc, body := postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/delete",
+ url.Values{"csrf": {o.csrf}, "confirm": {o.acct.Name}})
+ if status != http.StatusSeeOther || loc != o.settingsPath() {
+ t.Fatalf("delete = %d %q, want the settings tab before any sign-in\n%s", status, loc, body)
+ }
+ if kind, msg := o.jarFlash(t); kind != "err" || msg != accountDomainsRefusal([]string{"shop.example"}) {
+ t.Fatalf("flash = %s:%q, want the domains refusal", kind, msg)
+ }
+ o.wantKept(t)
+ if m := readManifest(t, o.rel, o.acct.Sqid); m.Deleted() {
+ t.Fatal("the account was tombstoned in the bucket though a purchase is under way")
+ }
+ if err := o.st.AdvanceDomainPurchase(p.ID, PurchaseAwaitingPayment, PurchaseExpired, nil); err != nil {
+ t.Fatal(err)
+ }
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+}
+
+// The store re-checks inside its transaction: a deletion that got past the
+// door's check while a registration was recorded is still refused, with
+// nothing changed.
+func TestStoreDeleteAccountRechecksObligations(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ id := testAccountID()
+ if err := s.CreateAccount(id, "test-del-dom", "Testco", "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.AddDomainRegistration(DomainRegistration{Domain: "shop.example", AccountID: id}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CreateDomainPurchase(DomainPurchase{ID: "dp_00000000000000b1", AccountID: id, Domain: "blog.example",
+ State: PurchaseAuthorised, CreatedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ err := s.DeleteAccount(id, now)
+ if !errors.Is(err, errAccountHoldsDomains) || !strings.Contains(err.Error(), "2 domain") {
+ t.Fatalf("DeleteAccount = %v, want the domains refusal naming 2", err)
+ }
+ if got := deletionAdvice(err); got != accountDomainsCopy.Count {
+ t.Fatalf("deletionAdvice = %q, want the domains advice", got)
+ }
+ if a, err := s.AccountBySqid("test-del-dom"); err != nil || a == nil {
+ t.Fatalf("account = %+v %v after a refused deletion, want it kept", a, err)
+ }
+ if got, err := s.DomainObligations(context.Background(), id); err != nil || len(got) != 2 {
+ t.Fatalf("obligations = %v %v, want both kept", got, err)
+ }
+}