carlos / platform Public

domains: final review fixes (resumable buys, setup deadline, alerts)

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev ac01910555a2d9025234e51609400c4460b1e8ea parent 8f2abbc
21 files changed, +743 −102
  • cmd/console/domains.go +6 −4
  • cmd/console/domains_test.go +8 −4
  • docs/site/domains-buying.md +7 −2
  • docs/superpowers/notes/census-proposal-domain-registration-final-fixes.md +11 −0
  • internal/console/apidomainbuy.go +13 −23
  • internal/console/apidomainbuy_test.go +20 −13
  • internal/console/appdomainbuy.go +15 −6
  • internal/console/domainbuy.go +144 −20
  • internal/console/domainbuy_admission_test.go +1 −1
  • internal/console/domainbuy_copy.go +1 −0
  • internal/console/domainbuy_final_fix_test.go +460 −0
  • internal/console/domainbuy_fix_test.go +5 −1
  • internal/console/domainbuy_limit.go +29 −0
  • internal/console/domainbuy_test.go +3 −3
  • internal/console/domainstore.go +2 −0
  • internal/console/server.go +2 −1
  • internal/console/templates/domain_buy.html +3 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-domain-registration-final-fixes.tsv +3 −0
  • internal/registrar/openprovider/client.go +0 −7
  • internal/registrar/openprovider/client_test.go +9 −17
diff --git a/cmd/console/domains.go b/cmd/console/domains.go
index d4bcc3d8b..38cd34294 100644
--- a/cmd/console/domains.go
+++ b/cmd/console/domains.go
@@ -15,8 +15,8 @@ import (
)
// domainBackends leaves buying off until every required setting is present.
-// Once configured, construction errors stop startup instead of hiding a broken
-// deployment. Errors name the setting or adapter, never configuration values
+// Catalog errors stop startup; adapter errors leave buying off.
+// Errors name the setting or adapter, never configuration values
// or wrapped provider errors, which may contain credentials.
func domainBackends(
getenv func(string) string,
@@ -56,7 +56,8 @@ func domainBackends(
Password: values["CARLOS_OPENPROVIDER_PASSWORD"],
})
if err != nil || r == nil {
- return nil, nil, nil, nil, errors.New("console: cannot construct domain registrar; check CARLOS_OPENPROVIDER_URL, CARLOS_OPENPROVIDER_USERNAME and CARLOS_OPENPROVIDER_PASSWORD")
+ log.Print("console: cannot construct domain registrar; check CARLOS_OPENPROVIDER_URL, CARLOS_OPENPROVIDER_USERNAME and CARLOS_OPENPROVIDER_PASSWORD")
+ return nil, nil, nil, nil, nil
}
nameservers := strings.Split(values["CARLOS_DOMAIN_NAMESERVERS"], ",")
for i := range nameservers {
@@ -72,7 +73,8 @@ func domainBackends(
}
z, err := newZones(context.Background(), cfg)
if err != nil || z == nil {
- return nil, nil, nil, nil, errors.New("console: cannot construct domain zone host; check CARLOS_DOMAIN_DELEGATION_SET_ID, CARLOS_DOMAIN_NAMESERVERS and AWS configuration")
+ log.Print("console: cannot construct domain zone host; check CARLOS_DOMAIN_DELEGATION_SET_ID, CARLOS_DOMAIN_NAMESERVERS and AWS configuration")
+ return nil, nil, nil, nil, nil
}
var apex zonehost.ApexSource
if cfg.SteeringHost != "" {
diff --git a/cmd/console/domains_test.go b/cmd/console/domains_test.go
index 245519068..70e09e37e 100644
--- a/cmd/console/domains_test.go
+++ b/cmd/console/domains_test.go
@@ -161,8 +161,11 @@ func TestDomainBackendsErrorNeverLeaksPassword(t *testing.T) {
}
return &route53zones.Host{}, nil
})
- if r != nil || z != nil || a != nil || c != nil || err == nil {
- t.Fatal("a failed construction must return an error and no partial backends")
+ if r != nil || z != nil || a != nil || c != nil || (err != nil) != (stage == "catalog") {
+ t.Fatal("only catalog errors are fatal; adapters leave buying off")
+ }
+ if stage != "catalog" && strings.Count(logs.String(), "\n") != 1 {
+ t.Fatal("adapter failure must log one line")
}
if strings.Contains(fmt.Sprintf("%+v", err)+logs.String(), strings.TrimSpace(secret)) {
t.Fatal("startup error leaked the password")
@@ -200,14 +203,15 @@ func TestDomainBackendsRejectsInvalidNameservers(t *testing.T) {
} {
t.Run(names, func(t *testing.T) {
env := domainTestEnv()
+ logs := domainTestLog(t)
env["CARLOS_DOMAIN_NAMESERVERS"] = names
r, z, a, c, err := domainBackends(func(k string) string { return env[k] },
func(openprovider.Config) (registrar.Registrar, error) { return registrartest.New(), nil },
route53zones.New)
- if r != nil || z != nil || a != nil || c != nil || err == nil || !strings.Contains(err.Error(), "CARLOS_DOMAIN_NAMESERVERS") {
+ if r != nil || z != nil || a != nil || c != nil || err != nil || !strings.Contains(logs.String(), "CARLOS_DOMAIN_NAMESERVERS") {
t.Fatalf("invalid nameservers must fail without partial backends: %v", err)
}
- if strings.Contains(err.Error(), names) {
+ if strings.Contains(logs.String(), names) {
t.Fatal("startup error contains the invalid nameserver value")
}
})
diff --git a/docs/site/domains-buying.md b/docs/site/domains-buying.md
index 7552870de..d8cbbff9c 100644
--- a/docs/site/domains-buying.md
+++ b/docs/site/domains-buying.md
@@ -48,8 +48,10 @@ AWS includes this operator step in the procedure above.
Set all six variables together. If any is empty or whitespace-only, domain
buying stays off and one startup log line lists the missing variable names.
-When all are present, a catalog load error or backend construction failure stops
-startup. Error messages omit configuration values and underlying provider errors.
+A malformed `CARLOS_DOMAIN_CATALOG` stays fatal (operator config error, same as
+`CARLOS_PLAN_CATALOG`); a registrar or zone-host constructor failure logs one line
+and leaves the buy door off. Error messages omit configuration values and
+underlying provider errors.
| Variable | Value |
| --- | --- |
@@ -83,6 +85,9 @@ before buying on a deployment without steering.
## Set prices and verify
+The catalog may list only TLDs that allow WHOIS privacy — if wrong, a TLD is
+unbuyable until removed from the catalog.
+
Save a catalog such as this at the path in `CARLOS_DOMAIN_CATALOG`. These are
example prices, not a price recommendation:
diff --git a/docs/superpowers/notes/census-proposal-domain-registration-final-fixes.md b/docs/superpowers/notes/census-proposal-domain-registration-final-fixes.md
new file mode 100644
index 000000000..4f09ac185
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-domain-registration-final-fixes.md
@@ -0,0 +1,11 @@
+# Census approval: domain-registration-final-fixes
+
+Ruling `census-ruling-domain-registration-final-fixes`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc` → `4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-domain-registration-final-fixes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go
index e2bc40421..cea2c370a 100644
--- a/internal/console/apidomainbuy.go
+++ b/internal/console/apidomainbuy.go
@@ -71,22 +71,6 @@ func (s *Server) handleAPIDomainCheck(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"domain": q.Domain, "price": q.Price, "currency": q.Currency, "available": true})
}
-func (s *Server) domainBuyContact(acct *Account, supplied *registrar.Contact) (registrar.Contact, *doorRefusal) {
- var c registrar.Contact
- if supplied != nil {
- c = *supplied
- } else {
- var err error
- c, _, err = s.store.DomainContact(acct.ID)
- if err != nil {
- return c, domainBuyUnavailable()
- }
- }
- if err := c.Validate(); err != nil {
- return c, &doorRefusal{422, domainBuyCopy["contactError"]}
- }
- return c, nil
-}
func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) {
addr, acct, ok := s.domainBuyAPIGate(w, r)
if !ok {
@@ -104,19 +88,25 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request)
writeDoorRefusalJSON(w, r, ref)
return
}
- c, ref := s.domainBuyContact(acct, in.Contact)
- if ref != nil {
- if ref.Status == 422 {
- writeJSON(w, 422, map[string]string{"error": ref.Msg, "code": "contact"})
- } else {
- writeDoorRefusalJSON(w, r, ref)
+ var c registrar.Contact
+ if in.Contact != nil {
+ c = *in.Contact
+ } else {
+ var err error
+ c, _, err = s.store.DomainContact(acct.ID)
+ if err != nil {
+ writeDoorRefusalJSON(w, r, domainBuyUnavailable())
+ return
}
- return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
p, checkout, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr)
if ref != nil {
+ if ref.Status == 422 && ref.Msg == domainBuyCopy["contactError"] {
+ writeJSON(w, 422, map[string]string{"error": ref.Msg, "code": "contact"})
+ return
+ }
writeDoorRefusalJSON(w, r, ref)
return
}
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go
index 64f55c66c..d510f1226 100644
--- a/internal/console/apidomainbuy_test.go
+++ b/internal/console/apidomainbuy_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/billing"
"github.com/carlosframework/platform/internal/domainreg"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/registrar"
@@ -101,7 +102,7 @@ func TestBuyDoorOwnerOnly(t *testing.T) {
t.Fatalf("unauthorized provider calls: %v", f.reg.Calls)
}
}
-func TestBuyDoorSecondConcurrentBuyRefused(t *testing.T) {
+func TestBuyDoorConcurrentBuysResumeSamePurchase(t *testing.T) {
f := newPurchaseFixture(t)
tok := buyToken(t, f)
var wg sync.WaitGroup
@@ -115,18 +116,16 @@ func TestBuyDoorSecondConcurrentBuyRefused(t *testing.T) {
}(i)
}
wg.Wait()
- successes, conflicts := 0, 0
- for i, s := range statuses {
- if s == 200 || s == 201 {
- successes++
- } else if s == 409 {
- conflicts++
- } else {
- t.Fatalf("unexpected %d %s", s, bodies[i])
+ for i, status := range statuses {
+ if status != 200 {
+ t.Fatalf("unexpected %d %s", status, bodies[i])
}
}
- if successes != 1 || conflicts != 1 {
- t.Fatalf("statuses %v", statuses)
+ if bodies[0] != bodies[1] {
+ t.Fatalf("concurrent resume differs: %v", bodies)
+ }
+ if f.sent(billing.PreparedPaymentCheckout) != 1 {
+ t.Fatal("duplicate checkout")
}
if purchaseCalls(f.reg.Calls, "contact:") > 1 {
t.Fatal("duplicate contact")
@@ -159,7 +158,11 @@ func TestCheckDoorRefusalsAreNeutral(t *testing.T) {
if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: "held.com", Account: "foreign", App: "other", Route: "other.example.com"}); err != nil {
t.Fatal(err)
}
- f.start(t)
+ p := f.start(t)
+ other := planAccount(t, f.consoleFixture, 802)
+ if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.AccountID = other.ID }); err != nil {
+ t.Fatal(err)
+ }
s1, b1 := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"held.com"}`)
s2, b2 := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com"}`)
if s1 != 409 || s2 != 409 || b1 != b2 {
@@ -428,7 +431,11 @@ func TestBrowserBuyPrefillsContactAndHidesUnconfigured(t *testing.T) {
func TestBuyDoorLiveAndHeldRefusalsAreNeutral(t *testing.T) {
f := newPurchaseFixture(t)
tok := buyToken(t, f)
- f.start(t)
+ p := f.start(t)
+ other := planAccount(t, f.consoleFixture, 802)
+ if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.AccountID = other.ID }); err != nil {
+ t.Fatal(err)
+ }
// A pending journal may already have registered the name at the provider.
f.reg.Available["shop.com"] = registrar.Availability{Available: false}
if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: "www.held.com", Account: "foreign", App: "other"}); err != nil {
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index b8e1c8fb3..abfee982e 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -18,6 +18,7 @@ type domainBuyField struct {
}
type domainBuyView struct {
Base, Back, PollURL string
+ CheckoutURL string
Price string
Quote *domainreg.Quote
Fields []domainBuyField
@@ -109,17 +110,16 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) {
c := registrar.Contact{FirstName: r.FormValue("FirstName"), LastName: r.FormValue("LastName"), Company: r.FormValue("Company"),
Email: r.FormValue("Email"), PhoneCountryCode: r.FormValue("PhoneCountryCode"), Phone: r.FormValue("Phone"), Street: r.FormValue("Street"), HouseNumber: r.FormValue("HouseNumber"),
City: r.FormValue("City"), State: r.FormValue("State"), PostalCode: r.FormValue("PostalCode"), Country: r.FormValue("Country")}
- if _, ref := s.domainBuyContact(acct, &c); ref != nil {
- s.renderDoorRefusal(w, r, ref)
- return
- }
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
- _, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr)
+ p, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr)
if ref != nil {
s.renderDoorRefusal(w, r, ref)
return
}
+ if checkout == "" {
+ checkout = domainPurchaseURL(acct.Sqid, p.App, p.ID)
+ }
http.Redirect(w, r, checkout, http.StatusSeeOther)
}
func (s *Server) handleAppDomainPurchase(w http.ResponseWriter, r *http.Request) {
@@ -131,7 +131,16 @@ func (s *Server) handleAppDomainPurchase(w http.ResponseWriter, r *http.Request)
if p == nil {
return
}
- s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Purchase: p, PollURL: domainPurchaseURL(acct.Sqid, app, p.ID) + "/status"})
+ var checkout string
+ if p.State == PurchaseAwaitingPayment && p.CheckoutSession != "" && time.Now().Before(p.CheckoutExpires) {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ info, err := s.billing.cfg.Provider.PaymentCheckout(ctx, p.CheckoutSession)
+ if err == nil && info.Status == "open" {
+ checkout = info.URL
+ }
+ }
+ s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Purchase: p, CheckoutURL: checkout, PollURL: domainPurchaseURL(acct.Sqid, app, p.ID) + "/status"})
}
func (s *Server) handleAppDomainPurchaseStatus(w http.ResponseWriter, r *http.Request) {
_, _, acct, app, ok := s.domainBuyBrowserGate(w, r)
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go
index 15a813199..971e829a5 100644
--- a/internal/console/domainbuy.go
+++ b/internal/console/domainbuy.go
@@ -32,7 +32,8 @@ func domainBuyUnavailable() *doorRefusal {
}
// admitDomainBuy is shared by every check and purchase door after owner/person
-// authorization. Claims and live purchases may only produce the neutral refusal:
+// authorization. An owner may resume their live purchase at its stored price.
+// Other holders may only produce the neutral refusal:
// name-only refusals and the shared budget come first, then registrar availability,
// then the claim/live checks, and finally premium and price checks.
func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) {
@@ -46,6 +47,13 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string)
if err != nil {
return domainreg.Quote{}, domainBuyErrorRefusal(err)
}
+ own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
+ if err != nil {
+ return domainreg.Quote{}, domainBuyUnavailable()
+ }
+ if own != nil {
+ return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil
+ }
b, err := s.store.BillingAccount(acct.ID)
if err != nil || b == nil || b.Currency == "" || b.Customer == "" {
return domainreg.Quote{}, domainBuyUnavailable()
@@ -88,6 +96,9 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string)
return domainreg.Quote{}, ref
}
q, err := s.cfg.DomainCatalog.Quote(name, b.Currency, a)
+ if errors.Is(err, domainreg.ErrCostAboveCeiling) {
+ s.purchaseRefusalAlert(ctx, acct, name, "cost:"+suffix, "registrar cost above ceiling")
+ }
if err != nil {
return domainreg.Quote{}, domainBuyErrorRefusal(err)
}
@@ -95,11 +106,21 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string)
}
func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) {
+ // Serialize starts so a concurrent buyer resumes the winning checkout.
+ defer s.planLock(acct)()
q, ref := s.admitDomainBuy(ctx, acct, name)
if ref != nil {
return nil, "", ref
}
name = q.Domain
+ own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
+ if err != nil {
+ return nil, "", domainBuyUnavailable()
+ }
+ if own != nil {
+ return s.resumeDomainPurchase(ctx, own)
+ }
+
exists, err := s.store.HasAppIn(acct.ID, app)
if err != nil {
return nil, "", domainBuyUnavailable()
@@ -110,8 +131,6 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
if err := c.Validate(); err != nil {
return nil, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]}
}
- // Keep concurrent starts on this account inside the same daily-cap check.
- defer s.planLock(acct)()
count, err := s.store.PurchasesToday(acct.ID, time.Now())
if err != nil {
return nil, "", domainBuyUnavailable()
@@ -124,7 +143,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
return nil, "", domainBuyErrorRefusal(err)
}
if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor {
- s.purchaseAlert(ctx, acct, name, "", "registrar balance")
+ s.purchaseRefusalAlert(ctx, acct, name, "balance", "registrar balance")
return nil, "", domainBuyUnavailable()
}
now := time.Now().UTC()
@@ -133,18 +152,44 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
purchaseDetails: purchaseDetails{Principal: principal, Contact: c}}
err = s.store.withAutoAppSQL(ctx, acct.ID, app, "sql.CreateDomainPurchase", func(st *Store) error { return st.CreateDomainPurchase(p) })
if errors.Is(err, ErrDomainPurchaseLive) {
+ own, readErr := s.ownLiveDomainPurchase(ctx, acct.ID, name)
+ if readErr != nil {
+ return nil, "", domainBuyUnavailable()
+ }
+ if own != nil {
+ return s.resumeDomainPurchase(ctx, own)
+ }
return nil, "", claimRefusal(name, domains.ErrHostUnavailable)
}
if err != nil {
return nil, "", domainBuyUnavailable()
}
- checkout, err := s.purchaseCheckout(ctx, &p)
+ return s.resumeDomainPurchase(ctx, &p)
+}
+
+func (s *Server) ownLiveDomainPurchase(ctx context.Context, account int64, name string) (*DomainPurchase, error) {
+ p, err := scanDomainPurchase(s.store.db.QueryRowContext(ctx, `SELECT `+domainPurchaseColumns+` FROM domain_purchases WHERE account_id=? AND domain=? AND `+liveDomainPurchaseSQL, account, name))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return p, err
+}
+
+func (s *Server) resumeDomainPurchase(ctx context.Context, p *DomainPurchase) (*DomainPurchase, string, *doorRefusal) {
+ var checkout string
+ var err error
+ if p.State == PurchaseAwaitingPayment {
+ checkout, err = s.purchaseCheckout(ctx, p)
+ }
if err != nil {
log.Printf("console: purchase %s: checkout: %v", p.ID, err)
- return &p, "", domainBuyUnavailable()
+ if p.State == PurchaseFailed && p.Reason == "contact" {
+ return p, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]}
+ }
+ return p, "", domainBuyUnavailable()
}
s.nudgePurchase(p.ID)
- return &p, checkout, nil
+ return p, checkout, nil
}
func (s *Server) movePurchase(ctx context.Context, p *DomainPurchase, to PurchaseState, set func(*DomainPurchase)) error {
@@ -166,7 +211,10 @@ func (s *Server) purchaseCheckout(ctx context.Context, p *DomainPurchase) (strin
provider := s.billing.cfg.Provider
if p.CheckoutSession != "" {
info, err := provider.PaymentCheckout(ctx, p.CheckoutSession)
- return info.URL, err
+ if err != nil || info.Status != "open" || !time.Now().Before(p.CheckoutExpires) {
+ return "", err
+ }
+ return info.URL, nil
}
if !time.Now().Before(p.CheckoutExpires) && p.CheckoutPrepared != nil {
if time.Now().Before(p.CheckoutExpires.Add(time.Hour)) {
@@ -223,6 +271,9 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s
}
handle, err := s.cfg.Registrar.EnsureContact(ctx, existing, p.Contact)
if err != nil {
+ if errors.Is(err, registrar.ErrRefused) {
+ return "", errors.Join(err, s.movePurchase(ctx, p, PurchaseFailed, func(p *DomainPurchase) { p.Reason = "contact" }))
+ }
return "", err
}
if handle == "" {
@@ -350,7 +401,7 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma
return billing.ErrIndeterminate
}
return s.purchaseMutation(ctx, p, func(ctx context.Context) error {
- return s.movePurchase(ctx, p, PurchaseAuthorised, func(p *DomainPurchase) { p.PaymentIntent = info.PaymentIntent })
+ return s.movePurchase(ctx, p, PurchaseAuthorised, func(p *DomainPurchase) { p.PaymentIntent = info.PaymentIntent; p.SetupStartedAt = time.Now().UTC() })
})
}
if info.Status == "expired" || (info.Status == "open" && !time.Now().Before(p.CheckoutExpires)) {
@@ -369,12 +420,25 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma
func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *DomainPurchase) error {
provider := s.billing.cfg.Provider
+ if p.State == PurchaseAuthorised || p.State == PurchaseZoneReady {
+ stop, err := s.purchaseSetupDeadline(ctx, acct, p)
+ if stop || err != nil {
+ return err
+ }
+ }
switch p.State {
case PurchaseAuthorised:
z, err := s.cfg.ZoneHost.CreateZone(ctx, p.Domain, p.ID)
+ // A branding failure can still return a created zone that cleanup must own.
+ if z.ID != "" && z.ID != p.ZoneID {
+ if saveErr := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.ZoneID = z.ID }); saveErr != nil {
+ return errors.Join(err, saveErr)
+ }
+ }
if err != nil {
return err
}
+
source := s.cfg.DomainApex
if source == nil {
source = zonehost.StaticApex(s.dnsTargets(ctx).EdgeIPs)
@@ -395,13 +459,6 @@ func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *D
}
return s.movePurchase(ctx, p, PurchaseZoneReady, func(p *DomainPurchase) { p.ZoneID = z.ID })
case PurchaseZoneReady:
- if err := s.movePurchase(ctx, p, PurchaseRegistering, func(p *DomainPurchase) {
- p.Attempts = 1
- p.RegisterStartedAt = time.Now().UTC()
- p.RegisterNextAt = p.RegisterStartedAt.Add(10 * time.Minute)
- }); err != nil {
- return err
- }
return s.registerPurchase(ctx, p)
case PurchaseRegistered:
prepared, err := provider.PrepareCapture(p.PaymentIntent, p.ID+":capture")
@@ -462,6 +519,10 @@ func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *D
}
func (s *Server) reconcileRegisteringPurchase(ctx context.Context, acct *Account, p *DomainPurchase) error {
+ if p.Reason == "payment_hold_lost" {
+ return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.finishPurchaseWithoutHold(ctx, p) })
+ }
+
if p.Reason == "taken" || p.Reason == "refused" || p.Reason == "unconfirmed" {
return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.failPurchase(ctx, p) })
}
@@ -525,6 +586,29 @@ func (s *Server) reconcileRegisteringPurchase(ctx context.Context, acct *Account
}
func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error {
+ info, err := s.billing.cfg.Provider.PaymentCheckout(ctx, p.CheckoutSession)
+ if err != nil {
+ return err
+ }
+ if info.PaymentIntent != p.PaymentIntent {
+ return billing.ErrIndeterminate
+ }
+ if info.IntentStatus != "requires_capture" {
+ if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = "payment_hold_lost" }); err != nil {
+ return err
+ }
+ return s.finishPurchaseWithoutHold(ctx, p)
+ }
+ if p.State == PurchaseZoneReady {
+ if err := s.movePurchase(ctx, p, PurchaseRegistering, func(p *DomainPurchase) {
+ p.Attempts = 1
+ p.RegisterStartedAt = time.Now().UTC()
+ p.RegisterNextAt = p.RegisterStartedAt.Add(10 * time.Minute)
+ }); err != nil {
+ return err
+ }
+ }
+
r, err := s.cfg.Registrar.Register(ctx, registrar.Registration{Domain: p.Domain, Years: 1, Nameservers: s.cfg.ZoneHost.Nameservers(), OwnerHandle: p.OwnerHandle, Key: p.ID})
if err == nil {
return s.registeredPurchase(ctx, p, r)
@@ -572,6 +656,43 @@ func (s *Server) registeredPurchase(ctx context.Context, p *DomainPurchase, r re
return s.movePurchase(ctx, p, PurchaseRegistered, func(p *DomainPurchase) { p.RegistrarID = r.RegistrarID; p.Reason = "" })
}
+func (s *Server) purchaseSetupDeadline(ctx context.Context, acct *Account, p *DomainPurchase) (bool, error) {
+ if p.Reason == "payment_hold_lost" {
+ return true, s.finishPurchaseWithoutHold(ctx, p)
+ }
+ if p.Reason == "setup_timeout" {
+ return true, s.failPurchase(ctx, p)
+ }
+ started := p.SetupStartedAt
+ if started.IsZero() {
+ // Older journals have no authorisation clock. Their creation bounds the hold.
+ started = p.CreatedAt
+ }
+ now := time.Now().UTC()
+ if !p.SetupAlerted && !now.Before(started.Add(30*time.Minute)) {
+ if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.SetupAlerted = true }); err != nil {
+ return true, err
+ }
+ s.purchaseAlert(ctx, acct, p.Domain, p.ID, "setup")
+ }
+ if now.Before(started.Add(24 * time.Hour)) {
+ return false, nil
+ }
+ if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = "setup_timeout" }); err != nil {
+ return true, err
+ }
+ return true, s.failPurchase(ctx, p)
+}
+
+func (s *Server) finishPurchaseWithoutHold(ctx context.Context, p *DomainPurchase) error {
+ if p.ZoneID != "" {
+ if err := s.cfg.ZoneHost.DeleteZone(ctx, zonehost.Zone{ID: p.ZoneID, Domain: p.Domain}); err != nil {
+ return err
+ }
+ }
+ return s.movePurchase(ctx, p, PurchaseFailed, nil)
+}
+
func (s *Server) failPurchase(ctx context.Context, p *DomainPurchase) error {
provider := s.billing.cfg.Provider
prepared, err := provider.PrepareCancelPayment(p.PaymentIntent, p.ID+":cancel")
@@ -588,10 +709,7 @@ func (s *Server) failPurchase(ctx context.Context, p *DomainPurchase) error {
return errors.Join(err, billing.ErrIndeterminate)
}
}
- if err := s.cfg.ZoneHost.DeleteZone(ctx, zonehost.Zone{ID: p.ZoneID, Domain: p.Domain}); err != nil {
- return err
- }
- return s.movePurchase(ctx, p, PurchaseFailed, nil)
+ return s.finishPurchaseWithoutHold(ctx, p)
}
func (s *Server) nudgePurchase(id string) {
@@ -670,3 +788,9 @@ func (s *Server) purchaseOwnerNotice(ctx context.Context, acct *Account, p *Doma
}
}
}
+
+func (s *Server) purchaseRefusalAlert(ctx context.Context, acct *Account, name, key, reason string) {
+ if s.purchaseAlerts.allow(key) {
+ s.purchaseAlert(ctx, acct, name, "", reason)
+ }
+}
diff --git a/internal/console/domainbuy_admission_test.go b/internal/console/domainbuy_admission_test.go
index 599d9356f..935ded5ee 100644
--- a/internal/console/domainbuy_admission_test.go
+++ b/internal/console/domainbuy_admission_test.go
@@ -37,7 +37,7 @@ func TestBuyAdmissionNeutralityGuard(t *testing.T) {
held, unheld := "held."+tc.suffix, "unheld."+tc.suffix
switch holder {
case "live":
- if err := f.st.CreateDomainPurchase(DomainPurchase{ID: "guard-live", AccountID: f.acct.ID, Domain: held, App: "kass", State: PurchaseAwaitingPayment}); err != nil {
+ if err := f.st.CreateDomainPurchase(DomainPurchase{ID: "guard-live", AccountID: planAccount(t, f.consoleFixture, 802).ID, Domain: held, App: "kass", State: PurchaseAwaitingPayment}); err != nil {
t.Fatal(err)
}
case "own-apex":
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go
index ae42c112c..5e91517e2 100644
--- a/internal/console/domainbuy_copy.go
+++ b/internal/console/domainbuy_copy.go
@@ -22,6 +22,7 @@ var domainBuyCopy = map[string]string{
"background": "Your purchase will continue in the background. Reload this page to check its progress.",
"contact": "Your contact details",
"pay": "Continue to checkout",
+ "continuePayment": "continue to payment",
"back": "Back to domains",
"contactError": "Enter your name, email address, postal address, country code and phone number. Use digits for the phone number and calling code, and two uppercase letters for the country.",
"nameError": "Enter a domain name that can be registered.",
diff --git a/internal/console/domainbuy_final_fix_test.go b/internal/console/domainbuy_final_fix_test.go
new file mode 100644
index 000000000..c4f43d1f0
--- /dev/null
+++ b/internal/console/domainbuy_final_fix_test.go
@@ -0,0 +1,460 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/carlosframework/platform/internal/zonehost"
+)
+
+type refusedContactRegistrar struct {
+ registrar.Registrar
+ calls int
+}
+
+func (r *refusedContactRegistrar) EnsureContact(context.Context, string, registrar.Contact) (string, error) {
+ r.calls++
+ return "", fmt.Errorf("postal code: %w", registrar.ErrRefused)
+}
+
+func TestContactRefusalFailsAtOnce(t *testing.T) {
+ f := newPurchaseFixture(t)
+ r := &refusedContactRegistrar{Registrar: f.reg}
+ f.srv.cfg.Registrar = r
+ tok := buyToken(t, f)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, buyBody())
+ if status != 422 || !strings.Contains(body, `"code":"contact"`) || !strings.Contains(body, domainBuyCopy["contactError"]) {
+ t.Errorf("contact refusal: %d %s", status, body)
+ }
+ var id string
+ if err := f.st.db.QueryRow(`SELECT id FROM domain_purchases`).Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ p := f.read(t, id)
+ if p.State != PurchaseFailed || p.Reason != "contact" {
+ t.Errorf("purchase: %s %s", p.State, p.Reason)
+ }
+ _ = f.srv.advancePurchase(context.Background(), id)
+ if r.calls != 1 || len(f.fake.Sent) != 0 || len(f.zone.Zones) != 0 {
+ t.Fatalf("contact retried or made payment/zone effects: %d", r.calls)
+ }
+ f.srv.cfg.Registrar = f.reg
+ status, body = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, buyBody())
+ if status != 200 {
+ t.Fatalf("corrected contact cannot buy: %d %s", status, body)
+ }
+}
+
+func TestOwnLivePurchaseResumes(t *testing.T) {
+ for _, state := range []PurchaseState{PurchaseAwaitingPayment, PurchaseAuthorised, PurchaseRegistered} {
+ t.Run(string(state), func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ if state != PurchaseAwaitingPayment {
+ f.authorise(t, p)
+ p = f.until(t, p.ID, state)
+ }
+ f.srv.cfg.DomainCatalog.DailyCap = 1
+ before := len(f.fake.Sent)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"SHOP.COM.","app":"kass"}`)
+ var got struct {
+ ID string
+ State PurchaseState
+ Checkout string `json:"checkout_url"`
+ }
+ if err := json.Unmarshal([]byte(body), &got); err != nil {
+ t.Fatal(err)
+ }
+ if status != 200 || got.ID != p.ID || got.State != state || (got.Checkout != "") != (state == PurchaseAwaitingPayment) {
+ t.Fatalf("resume: %d %s", status, body)
+ }
+ if len(f.fake.Sent) != before {
+ t.Fatal("resume recreated checkout")
+ }
+ })
+ }
+}
+
+func TestOwnLostCheckoutResumes(t *testing.T) {
+ f := newPurchaseFixture(t)
+ f.fake.LoseNextResponse = true
+ p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ if p == nil {
+ t.Fatal("missing journal")
+ }
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass"}`)
+ if status != 200 || !strings.Contains(body, p.ID) || !strings.Contains(body, `"checkout_url":"https://`) {
+ t.Fatalf("resume: %d %s", status, body)
+ }
+ if f.sent(billing.PreparedPaymentCheckout) != 2 {
+ t.Fatal("lost checkout was not replayed")
+ }
+}
+
+func TestCheckoutCancelPageOffersContinue(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ c := newBrowser(t)
+ f.setUser("owner" + f.acct.Sqid + "@example.com")
+ signUp(t, f.consoleFixture, c, "resume-browser")
+ info, err := f.fake.PaymentCheckout(context.Background(), p.CheckoutSession)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var request struct {
+ Request billing.PaymentCheckoutRequest
+ }
+ if err := json.Unmarshal(p.CheckoutPrepared.Body, &request); err != nil {
+ t.Fatal(err)
+ }
+ back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, p.App, p.ID)
+ if request.Request.CancelURL != back {
+ t.Fatalf("cancel URL: %v", request)
+ }
+ status, _, body := get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.App, p.ID))
+ if status != 200 || !strings.Contains(body, `href="`+info.URL+`"`) || !strings.Contains(body, ">continue to payment</a>") {
+ t.Fatalf("missing continue link: status=%d", status)
+ }
+ values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}}
+ status, loc, _ := postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/buy", values)
+ if status != 303 || loc != info.URL {
+ t.Fatalf("browser resume: %d %s", status, loc)
+ }
+ f.authorise(t, p)
+ status, _, body = get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.App, p.ID))
+ if status != 200 || strings.Contains(body, `href="`+info.URL+`"`) {
+ t.Fatal("closed checkout still offered")
+ }
+ status, loc, _ = postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/buy", values)
+ if status != 303 || loc != domainPurchaseURL(f.acct.Sqid, p.App, p.ID) {
+ t.Fatalf("active purchase resume: %d %s", status, loc)
+ }
+}
+
+func ageSetupPurchase(t *testing.T, f *purchaseFixture, id string, age time.Duration) {
+ t.Helper()
+ var raw string
+ if err := f.st.db.QueryRow(`SELECT details FROM domain_purchases WHERE id=?`, id).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var details map[string]any
+ if err := json.Unmarshal([]byte(raw), &details); err != nil {
+ t.Fatal(err)
+ }
+ details["SetupStartedAt"] = time.Now().Add(-age).UTC()
+ data, err := json.Marshal(details)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.st.db.Exec(`UPDATE domain_purchases SET details=? WHERE id=?`, string(data), id); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestSetupDeadlineAlertAndFailure(t *testing.T) {
+ for _, stage := range []string{"create", "records", "zone_ready"} {
+ t.Run(stage, func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ f.authorise(t, p)
+ if stage == "zone_ready" {
+ f.until(t, p.ID, PurchaseZoneReady)
+ }
+ alerts := 0
+ pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
+ fail := func() {
+ if stage == "create" {
+ f.zone.CreateErr = errors.New("quota")
+ } else if stage == "records" {
+ f.zone.SetErr = errors.New("records")
+ } else {
+ f.fake.Err = billing.ErrNoResponse
+ }
+ }
+ for _, age := range []time.Duration{29 * time.Minute, 30 * time.Minute, 31 * time.Minute, 24 * time.Hour} {
+ ageSetupPurchase(t, f, p.ID, age)
+ f.fake.Err = nil
+ if age < 24*time.Hour {
+ fail()
+ }
+ _ = f.srv.advancePurchase(context.Background(), p.ID)
+ want := 1
+ if age < 30*time.Minute {
+ want = 0
+ }
+ if alerts != want {
+ t.Errorf("at %v alerts=%d want=%d", age, alerts, want)
+ }
+ }
+ f.fake.Err = nil
+ _ = f.srv.advancePurchase(context.Background(), p.ID)
+ p = f.read(t, p.ID)
+ if p.State != PurchaseFailed || p.Reason != "setup_timeout" || f.sent(billing.PreparedCancelPayment) != 1 || len(f.zone.Zones) != 0 || purchaseCalls(f.reg.Calls, "register:") != 0 {
+ t.Fatalf("timeout: state=%s reason=%s cancels=%d zones=%d registrar=%v", p.State, p.Reason, f.sent(billing.PreparedCancelPayment), len(f.zone.Zones), f.reg.Calls)
+ }
+ })
+ }
+}
+
+func TestRegisterRequiresLivePaymentHold(t *testing.T) {
+ for _, retry := range []bool{false, true} {
+ t.Run(fmt.Sprint(retry), func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ var p *DomainPurchase
+ if retry {
+ p = unresolvedPurchase(t, f)
+ ageRegisteringPurchase(t, f, p.ID, 11*time.Minute)
+ } else {
+ p = f.start(t)
+ f.authorise(t, p)
+ p = f.until(t, p.ID, PurchaseZoneReady)
+ }
+ prep, err := f.fake.PrepareCancelPayment(p.PaymentIntent, "external-cancel")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.fake.Send(context.Background(), prep); err != nil {
+ t.Fatal(err)
+ }
+ calls := purchaseCalls(f.reg.Calls, "register:")
+ if err = f.srv.advancePurchase(context.Background(), p.ID); err != nil {
+ t.Fatal(err)
+ }
+ p = f.read(t, p.ID)
+ if p.State != PurchaseFailed || p.Reason != "payment_hold_lost" || purchaseCalls(f.reg.Calls, "register:") != calls || f.sent(billing.PreparedCancelPayment) != 1 || len(f.zone.Zones) != 0 {
+ t.Fatalf("lost hold: %s %s calls=%v", p.State, p.Reason, f.reg.Calls)
+ }
+ })
+ }
+}
+
+type lookupFailureRegistrar struct{ registrar.Registrar }
+
+func (r lookupFailureRegistrar) Lookup(context.Context, string) (registrar.Registered, bool, error) {
+ return registrar.Registered{}, false, registrar.ErrIndeterminate
+}
+func TestRegisteringDeadlineLookupFoundRegisters(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := unresolvedPurchase(t, f)
+ ageRegisteringPurchase(t, f, p.ID, 24*time.Hour)
+ f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)}
+ p = f.advance(t, p.ID)
+ if p.State != PurchaseRegistered || f.sent(billing.PreparedCancelPayment) != 0 || len(f.zone.Zones) != 1 || purchaseCalls(f.reg.Calls, "register:") != 1 {
+ t.Fatalf("found at deadline: %s", p.State)
+ }
+ f.until(t, p.ID, PurchaseDone)
+ if f.sent(billing.PreparedCapture) != 1 {
+ t.Fatal("did not capture found registration")
+ }
+}
+func TestRegisteringDeadlineLookupErrorStaysLive(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := unresolvedPurchase(t, f)
+ ageRegisteringPurchase(t, f, p.ID, 24*time.Hour)
+ f.srv.cfg.Registrar = lookupFailureRegistrar{f.reg}
+ for i := 0; i < 2; i++ {
+ if err := f.srv.advancePurchase(context.Background(), p.ID); !errors.Is(err, registrar.ErrIndeterminate) {
+ t.Fatalf("lookup error: %v", err)
+ }
+ p = f.read(t, p.ID)
+ if p.State != PurchaseRegistering || f.sent(billing.PreparedCancelPayment) != 0 || f.sent(billing.PreparedCapture) != 0 || len(f.zone.Zones) != 1 || purchaseCalls(f.reg.Calls, "register:") != 1 {
+ t.Fatalf("uncertain deadline: %s", p.State)
+ }
+ }
+}
+
+func TestPurchaseRefusalAlertsRateLimited(t *testing.T) {
+ for _, cause := range []string{"cost", "balance"} {
+ t.Run(cause, func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ f.srv.cfg.DomainCatalog.TLDs["net"] = f.srv.cfg.DomainCatalog.TLDs["com"]
+ for _, name := range []string{"shop.com", "other.com", "shop.net"} {
+ a := f.reg.Available["shop.com"]
+ if cause == "cost" {
+ a.Cost.Minor = 1001
+ }
+ f.reg.Available[name] = a
+ }
+ if cause == "balance" {
+ f.reg.BalanceMoney.Minor = 0
+ }
+ alerts := 0
+ pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
+ for _, name := range []string{"shop.com", "other.com", "shop.net", "shop.com"} {
+ _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer")
+ if ref == nil || ref.Status != 503 {
+ t.Fatalf("refusal: %+v", ref)
+ }
+ }
+ want := 1
+ if cause == "cost" {
+ want = 2
+ }
+ if alerts != want {
+ t.Fatalf("alerts=%d want=%d", alerts, want)
+ }
+ })
+ }
+}
+
+func TestPurchaseAlertHourlyBoundaryAndConcurrency(t *testing.T) {
+ now := time.Now()
+ l := purchaseAlertLimiter{now: func() time.Time { return now }}
+ var count atomic.Int32
+ var wg sync.WaitGroup
+ for i := 0; i < 40; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if l.allow("balance") {
+ count.Add(1)
+ }
+ }()
+ }
+ wg.Wait()
+ if count.Load() != 1 {
+ t.Fatalf("concurrent alerts=%d", count.Load())
+ }
+ now = now.Add(time.Hour - time.Nanosecond)
+ if l.allow("balance") {
+ t.Fatal("early hourly refill")
+ }
+ now = now.Add(time.Nanosecond)
+ if !l.allow("balance") || l.allow("balance") {
+ t.Fatal("hourly boundary")
+ }
+ if !l.allow("cost:com") || !l.allow("cost:net") || l.allow("cost:com") {
+ t.Fatal("cost keys not per TLD")
+ }
+}
+
+func TestSetupClockAndAlertSurviveRestartAndTransition(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ f.authorise(t, p)
+ p = f.read(t, p.ID)
+ if p.SetupStartedAt.IsZero() {
+ t.Fatal("authorisation did not persist setup clock")
+ }
+ ageSetupPurchase(t, f, p.ID, 30*time.Minute)
+ started := f.read(t, p.ID).SetupStartedAt
+ alerts := 0
+ pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
+ f.until(t, p.ID, PurchaseZoneReady)
+ srv, err := NewServer(f.srv.cfg, f.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.srv = srv
+ f.srv.billing.ready.Store(true)
+ f.until(t, p.ID, PurchaseRegistered)
+ p = f.read(t, p.ID)
+ if alerts != 1 || !p.SetupStartedAt.Equal(started) || !p.SetupAlerted {
+ t.Fatalf("clock or alert reset: alerts=%d details=%+v", alerts, p.purchaseDetails)
+ }
+}
+
+func TestSetupTimeoutRetriesCleanupWithoutRegister(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ f.authorise(t, p)
+ f.until(t, p.ID, PurchaseZoneReady)
+ ageSetupPurchase(t, f, p.ID, 24*time.Hour)
+ f.fake.FailBeforeDelivery = 1
+ if err := f.srv.advancePurchase(context.Background(), p.ID); !errors.Is(err, billing.ErrNoResponse) {
+ t.Fatalf("cancel failure: %v", err)
+ }
+ p = f.read(t, p.ID)
+ if p.State != PurchaseZoneReady || p.Reason != "setup_timeout" {
+ t.Fatalf("cleanup not checkpointed: %s %s", p.State, p.Reason)
+ }
+ f.until(t, p.ID, PurchaseFailed)
+ if len(f.zone.Zones) != 0 || purchaseCalls(f.reg.Calls, "register:") != 0 || f.sent(billing.PreparedCapture) != 0 {
+ t.Fatal("cleanup retried registration or leaked zone")
+ }
+}
+
+func TestOwnLivePurchaseCheckReturnsStoredQuote(t *testing.T) {
+ for _, state := range []PurchaseState{PurchaseAwaitingPayment, PurchaseRegistered} {
+ t.Run(string(state), func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ if state != PurchaseAwaitingPayment {
+ f.authorise(t, p)
+ f.until(t, p.ID, state)
+ }
+ // A catalog change or a now-registered name must not block resuming its checkout.
+ delete(f.srv.cfg.DomainCatalog.TLDs, "com")
+ calls := len(f.reg.Calls)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", buyToken(t, f), `{"name":"SHOP.COM."}`)
+ var quote struct {
+ Domain, Currency string
+ Price int64
+ Available bool
+ }
+ if err := json.Unmarshal([]byte(body), &quote); err != nil {
+ t.Fatal(err)
+ }
+ if status != 200 || quote.Domain != p.Domain || quote.Currency != p.Currency || quote.Price != p.Amount || !quote.Available || len(f.reg.Calls) != calls {
+ t.Fatalf("own check: %d %s", status, body)
+ }
+ })
+ }
+}
+
+type partialCreateZoneHost struct {
+ zonehost.Host
+ calls int
+}
+
+func (h *partialCreateZoneHost) CreateZone(ctx context.Context, domain, key string) (zonehost.Zone, error) {
+ h.calls++
+ z, err := h.Host.CreateZone(ctx, domain, key)
+ if err != nil {
+ return z, err
+ }
+ if h.calls == 1 {
+ return z, errors.New("branding failed after create")
+ }
+ return z, nil
+}
+func TestSetupRetainsZoneFromPartialCreate(t *testing.T) {
+ for _, timeout := range []bool{false, true} {
+ t.Run(fmt.Sprint(timeout), func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ f.authorise(t, p)
+ h := &partialCreateZoneHost{Host: f.zone}
+ f.srv.cfg.ZoneHost = h
+ if err := f.srv.advancePurchase(context.Background(), p.ID); err == nil {
+ t.Fatal("partial create should fail")
+ }
+ p = f.read(t, p.ID)
+ if p.ZoneID == "" || p.State != PurchaseAuthorised {
+ t.Fatalf("lost partial zone: %+v", p)
+ }
+ if timeout {
+ ageSetupPurchase(t, f, p.ID, 24*time.Hour)
+ f.until(t, p.ID, PurchaseFailed)
+ if len(f.zone.Zones) != 0 || h.calls != 1 {
+ t.Fatal("timeout leaked or recreated zone")
+ }
+ } else {
+ f.until(t, p.ID, PurchaseZoneReady)
+ if h.calls != 2 {
+ t.Fatal("branding was not retried")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go
index 9e5b77d00..70c884cb4 100644
--- a/internal/console/domainbuy_fix_test.go
+++ b/internal/console/domainbuy_fix_test.go
@@ -62,7 +62,11 @@ func TestCheckDoorPlanGateFirst(t *testing.T) {
func TestCheckAndBuyNeutralAcrossClaimLivePurchaseAndTaken(t *testing.T) {
f := newPurchaseFixture(t)
tok := buyToken(t, f)
- f.start(t)
+ p := f.start(t)
+ other := planAccount(t, f.consoleFixture, 802)
+ if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.AccountID = other.ID }); err != nil {
+ t.Fatal(err)
+ }
holdBuyName(t, f, "held.com")
holdBuyName(t, f, "www.wwwheld.com")
wantStatus, wantBody := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"held.com"}`)
diff --git a/internal/console/domainbuy_limit.go b/internal/console/domainbuy_limit.go
index e3aa5b3f7..a750befff 100644
--- a/internal/console/domainbuy_limit.go
+++ b/internal/console/domainbuy_limit.go
@@ -69,3 +69,32 @@ func (l *domainCheckLimiter) allow(account int64) bool {
l.deployment.credit -= deploymentCost
return true
}
+
+// Admission alerts share a deployment-wide hourly budget per cause (and cost TLD).
+type purchaseAlertLimiter struct {
+ mu sync.Mutex
+ last map[string]time.Time
+ now func() time.Time
+}
+
+func (l *purchaseAlertLimiter) allow(key string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := time.Now()
+ if l.now != nil {
+ now = l.now()
+ }
+ if l.last == nil {
+ l.last = make(map[string]time.Time)
+ }
+ if at, ok := l.last[key]; ok && now.Before(at.Add(time.Hour)) {
+ return false
+ }
+ for k, at := range l.last {
+ if !now.Before(at.Add(time.Hour)) {
+ delete(l.last, k)
+ }
+ }
+ l.last[key] = now
+ return true
+}
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go
index f2437c606..34777a145 100644
--- a/internal/console/domainbuy_test.go
+++ b/internal/console/domainbuy_test.go
@@ -678,9 +678,9 @@ func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) {
if ref != nil || p == nil {
t.Fatalf("start: %+v", ref)
}
- _, _, duplicate := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
- if duplicate == nil || *duplicate != *claimRefusal("shop.com", domains.ErrHostUnavailable) {
- t.Fatalf("duplicate: %+v", duplicate)
+ resumed, checkout, duplicate := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
+ if duplicate != nil || resumed == nil || resumed.ID != p.ID || checkout == "" || f.sent(billing.PreparedPaymentCheckout) != 1 {
+ t.Fatalf("resume: %+v %q %+v", resumed, checkout, duplicate)
}
f.authorise(t, p)
f.until(t, p.ID, PurchaseDone)
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go
index 1b33de725..10bf0d61f 100644
--- a/internal/console/domainstore.go
+++ b/internal/console/domainstore.go
@@ -41,6 +41,8 @@ type purchaseDetails struct {
RegisterStartedAt time.Time
RegisterNextAt time.Time
RegisterAlerted bool
+ SetupStartedAt time.Time
+ SetupAlerted bool
}
type DomainPurchase struct {
diff --git a/internal/console/server.go b/internal/console/server.go
index 98c322027..089426f57 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1112,7 +1112,8 @@ type Server struct {
secure bool // Secure cookies iff the origin is https
cli *cliLimits // rate limits on the CLI-identity endpoints (authcli.go)
- domainChecks domainCheckLimiter
+ domainChecks domainCheckLimiter
+ purchaseAlerts purchaseAlertLimiter
// boxCerts are AWS's instance-identity signing certificates by AWS
// region (boxid.EmbeddedCerts), loaded once at construction. The Phase
// 1 move door verifies each box's identity record with them; nil (a
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html
index 9ac0cb60c..323356fdc 100644
--- a/internal/console/templates/domain_buy.html
+++ b/internal/console/templates/domain_buy.html
@@ -6,16 +6,19 @@
<p>{{$.DomainBuyCopy.ownership}}</p>
<p>{{$.DomainBuyCopy.timing}}</p>
<p id="purchase-progress" role="status">{{index $.DomainBuyCopy (printf "%s" .Purchase.State)}}</p>
+{{if .CheckoutURL}}<p id="purchase-continue"><a href="{{.CheckoutURL}}">{{$.DomainBuyCopy.continuePayment}}</a></p>{{end}}
<script>
(function () {
const endpoint = {{.PollURL}}, copy = {{$.DomainBuyCopy}};
const progress = document.getElementById('purchase-progress');
+ const payment = document.getElementById('purchase-continue');
const started = Date.now();
async function poll() {
try {
const response = await fetch(endpoint, {credentials: 'same-origin', cache: 'no-store'});
if (!response.ok) throw new Error();
const purchase = await response.json();
+ if (payment && purchase.state !== 'awaiting_payment') payment.hidden = true;
progress.textContent = purchase.state === 'done' && purchase.domain_state === 'live' ? copy.live : (copy[purchase.state] || copy.pollError);
if (['failed', 'expired', 'unpaid'].includes(purchase.state) || (purchase.state === 'done' && purchase.domain_state === 'live')) return;
} catch (_) { progress.textContent = copy.pollError; }
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 4693127b3..40d8d051e 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -57,3 +57,4 @@ plan14-root-reads-durability-3a-escrow.tsv 03a92257beb9b8aac421559e247d191bd69f2
plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276c3d13ccae0f038190f51287ed5
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
plan14-root-reads-domain-registration-task-9.tsv 4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc
+plan14-root-reads-domain-registration-final-fixes.tsv 4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc
diff --git a/internal/provision/testdata/plan14-root-reads-domain-registration-final-fixes.tsv b/internal/provision/testdata/plan14-root-reads-domain-registration-final-fixes.tsv
new file mode 100644
index 000000000..ea9ba76ca
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-domain-registration-final-fixes.tsv
@@ -0,0 +1,3 @@
+# Census overlay domain-registration-final-fixes, written by census-propose (#369). census-ruling-domain-registration-final-fixes, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-domain-registration-final-fixes.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . e8db66a62018240f876c15c6f1d1429e79f3687e405b14f5513ff908ee6c0d49
diff --git a/internal/registrar/openprovider/client.go b/internal/registrar/openprovider/client.go
index bb9ae6e2d..4bb8fbfc1 100644
--- a/internal/registrar/openprovider/client.go
+++ b/internal/registrar/openprovider/client.go
@@ -257,13 +257,6 @@ func (c *Client) Register(ctx context.Context, in registrar.Registration) (regis
// unused. After an indeterminate outcome the caller must reconcile by Lookup.
var response domainRecord
err = c.call(ctx, http.MethodPost, "/domains", request, &response)
- var pe *providerError
- if errors.As(err, &pe) && errors.Is(err, registrar.ErrRefused) && (pe.code == 19006 || pe.code == 19007) {
- // These refusals mean nothing was registered. No other failure permits a
- // second registration request here (apart from the bounded 401 re-login).
- request.Private = false
- err = c.call(ctx, http.MethodPost, "/domains", request, &response)
- }
if err != nil {
return registrar.Registered{}, err
}
diff --git a/internal/registrar/openprovider/client_test.go b/internal/registrar/openprovider/client_test.go
index 8285616d1..e79b57b89 100644
--- a/internal/registrar/openprovider/client_test.go
+++ b/internal/registrar/openprovider/client_test.go
@@ -221,31 +221,23 @@ func TestStringRedactsSecrets(t *testing.T) {
}
}
-func TestPrivacyRefusalRetriesOnce(t *testing.T) {
+func TestPrivacyRefusalNeverRetriesWithoutPrivacy(t *testing.T) {
for _, code := range []int{19006, 19007} {
- for _, again := range []bool{false, true} {
- t.Run(fmt.Sprintf("%d/%v", code, again), func(t *testing.T) {
+ for _, status := range []int{200, 400} {
+ t.Run(fmt.Sprintf("%d/%d", code, status), func(t *testing.T) {
var calls atomic.Int32
c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
- n := calls.Add(1)
- b := body(t, r)
- if b["is_private_whois_enabled"] != (n == 1) {
- t.Errorf("attempt %d privacy=%v", n, b["is_private_whois_enabled"])
+ calls.Add(1)
+ if body(t, r)["is_private_whois_enabled"] != true {
+ t.Error("registration disabled privacy")
}
- if n == 1 || again {
- w.WriteHeader(400)
- fmt.Fprintf(w, `{"code":%d,"desc":"privacy not supported"}`, code)
- return
- }
- reply(t, w, "register")
+ w.WriteHeader(status)
+ fmt.Fprintf(w, `{"code":%d,"desc":"privacy not supported"}`, code)
}, time.Second)
_, err := c.Register(context.Background(), registration())
- if (err != nil) != again || calls.Load() != 2 {
+ if !errors.Is(err, registrar.ErrRefused) || calls.Load() != 1 {
t.Fatalf("error=%v calls=%d", err, calls.Load())
}
- if again && !errors.Is(err, registrar.ErrRefused) {
- t.Fatal(err)
- }
})
}
}