console: purchases with no app, frozen contacts, unpointed finish
A purchase may start with no app ("Not yet"): its zone is set to the
empty managed set and it finishes done with nothing attached. The plan
rule and daily cap apply either way.
A purchase binds one frozen contact (R12): a new contact is saved by the
start, a saved one is copied with its version and handle. EnsureContact
is only ever called with no existing handle; a minted handle goes back
to the saved contact only while its version still matches. The
registration's registrant is the frozen copy, and a registration row
left by a crash before registrants is backfilled. Nothing reads the old
domain_contacts row any more.
The start re-reads the account under the billing hold and inserts its
row there, so an account being deleted never gains a purchase. A paid
purchase whose app was purged or trashed releases what an earlier pass
attached (detach's own removal, owner-checked), unpoints the zone and
finishes with reason app_gone.
Buying is off with CARLOS_HOST_CLAIM on: the buy doors and the card
setup door are not registered, the purchase pass returns at once, and
the console logs why at boot. The claim census drops the armed-gate buy
tests accordingly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+1,014
−399
.amadan/code-health.tsv+0 −1cmd/console/domains.go+14 −0cmd/console/domains_test.go+9 −0internal/console/apidomainbuy.go+29 −14internal/console/apidomainbuy_test.go+36 −51internal/console/appdomainbuy.go+8 −2internal/console/claim_invariant_fixtures_test.go+3 −34internal/console/claim_invariant_probes_nonapp_test.go+0 −28internal/console/claim_invariant_probes_read_test.go+0 −9internal/console/claim_invariant_probes_worker_test.go+1 −0internal/console/claim_invariant_test.go+1 −0internal/console/domainattach.go+17 −2internal/console/domainbuy.go+259 −73internal/console/domainbuy_account_test.go+592 −0internal/console/domainbuy_round1_test.go+5 −5internal/console/domainbuy_round2_test.go+1 −1internal/console/domainbuy_test.go+15 −168internal/console/jobs_test.go+1 −1internal/console/routedecls.go+12 −10internal/console/svcroutes_test.go+11 −0
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index ae1864170..407c61ca6 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -1336,7 +1336,6 @@ db-no-context cmd/moveprobe insertSeq (*sql.DB).Exec 1 |
| db-no-context internal/activator buildEmptySQLiteDB (*sql.DB).Exec 1 |
| db-no-context internal/activator buildEmptySQLiteDB (*sql.DB).QueryRow 1 |
| db-no-context internal/console (*Server).advancePurchaseEffects console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Server).registeredPurchase console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).ARRSnapshots console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AcceptInvite console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).AccountAnyBySqid console.sqlHandle.QueryRow 1 |
diff --git a/cmd/console/domains.go b/cmd/console/domains.go| index 60983ea73..e20670c61 100644 |
| --- a/cmd/console/domains.go |
| +++ b/cmd/console/domains.go |
| @@ -14,6 +14,17 @@ import ( |
| "github.com/carlosframework/platform/internal/zonehost/route53zones" |
| ) |
| +// domainBuyingHostClaimNotice is the one boot line saying why domain |
| +// buying is off on a console whose domain backends are configured (the |
| +// only caller is domainBackends' success path): the console runs no |
| +// purchase path with host claims on. |
| +func domainBuyingHostClaimNotice(hostClaim bool) (string, bool) { |
| + if !hostClaim { |
| + return "", false |
| + } |
| + return "console: domain buying is off; CARLOS_HOST_CLAIM is on", true |
| +} |
| + |
| // domainBackends leaves buying off until every required setting is present. |
| // Catalog errors stop startup; adapter errors leave buying off. |
| // Errors name the setting or adapter, never configuration values |
| @@ -84,5 +95,8 @@ func domainBackends( |
| if cfg.SteeringHost != "" { |
| apex = z.Steered() |
| } |
| + if msg, off := domainBuyingHostClaimNotice(hostClaimEnabled(getenv)); off { |
| + log.Print(msg) |
| + } |
| return r, z, apex, catalog, nil |
| } |
diff --git a/cmd/console/domains_test.go b/cmd/console/domains_test.go| index 251b6859c..e700c1cdf 100644 |
| --- a/cmd/console/domains_test.go |
| +++ b/cmd/console/domains_test.go |
| @@ -224,3 +224,12 @@ func TestDomainBackendsRejectsInvalidNameservers(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestDomainBuyingOffNoticeNamesHostClaim(t *testing.T) { |
| + if msg, off := domainBuyingHostClaimNotice(true); !off || !strings.Contains(msg, "CARLOS_HOST_CLAIM") { |
| + t.Errorf("host claims on: %q %v", msg, off) |
| + } |
| + if msg, off := domainBuyingHostClaimNotice(false); off { |
| + t.Errorf("host claims off: %q", msg) |
| + } |
| +} |
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go| index 99435a977..0993fdc05 100644 |
| --- a/internal/console/apidomainbuy.go |
| +++ b/internal/console/apidomainbuy.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "log" |
| "net/http" |
| "os" |
| "time" |
| @@ -40,15 +41,27 @@ func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name, countr |
| return domainreg.Quote{}, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["contactError"]} |
| } |
| if country == "" { |
| - c, _, err := s.store.DomainContact(acct.ID) |
| - if err != nil { |
| - return domainreg.Quote{}, domainBuyUnavailable() |
| - } |
| - country = c.Country |
| + country = s.defaultQuoteCountry(acct) |
| } |
| return s.admitDomainBuy(ctx, acct, name, country) |
| } |
| +// defaultQuoteCountry is the country a quote assumes when the request names |
| +// none: the most recently used saved contact's, else "" (the catalog's |
| +// default currency). A failed read is "" too: the quote is only a default, |
| +// and the purchase confirms the price again under the billing hold. |
| +func (s *Server) defaultQuoteCountry(acct *Account) string { |
| + contacts, err := s.store.SavedContacts(context.Background(), acct.ID) |
| + if err != nil { |
| + log.Printf("console: domain quote %s: saved contacts: %v", acct.Sqid, err) |
| + return "" |
| + } |
| + if len(contacts) == 0 { |
| + return "" |
| + } |
| + return contacts[0].Contact.Country |
| +} |
| + |
| func (s *Server) liveDomainPurchaseRefusal(ctx context.Context, name string) *doorRefusal { |
| var live bool |
| if err := s.store.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domain_purchases WHERE domain=? AND `+liveDomainPurchaseSQL+`)`, name).Scan(&live); err != nil { |
| @@ -101,20 +114,22 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) |
| writeDoorRefusalJSON(w, r, ref) |
| return |
| } |
| - var c registrar.Contact |
| - if in.Contact != nil { |
| - c = *in.Contact |
| - } else { |
| - var err error |
| - c, _, err = s.store.DomainContact(acct.ID) |
| + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| + defer cancel() |
| + // A request with no contact buys with the most recently used saved |
| + // contact; with none saved, the contact refusal asks for one. |
| + sel := purchaseContactSelection{New: in.Contact} |
| + if in.Contact == nil { |
| + contacts, err := s.store.SavedContacts(ctx, acct.ID) |
| if err != nil { |
| writeDoorRefusalJSON(w, r, domainBuyUnavailable()) |
| return |
| } |
| + if len(contacts) > 0 { |
| + sel.ID = contacts[0].ID |
| + } |
| } |
| - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| - defer cancel() |
| - p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr, domainreg.Quote{Currency: in.Currency, Price: in.Price}) |
| + p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, sel, addr, domainreg.Quote{Currency: in.Currency, Price: in.Price}) |
| if changed != nil { |
| writeJSON(w, http.StatusConflict, map[string]any{"error": ref.Msg, "code": "price_changed", "domain": changed.Domain, "currency": changed.Currency, "price": changed.Price, "available": true}) |
| return |
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go| index a7f000c6e..85309f7f6 100644 |
| --- a/internal/console/apidomainbuy_test.go |
| +++ b/internal/console/apidomainbuy_test.go |
| @@ -237,7 +237,7 @@ func TestBuyDoorStoredContact(t *testing.T) { |
| if status != 422 || !strings.Contains(b, `"code":"contact"`) { |
| t.Fatalf("missing contact %d %s", status, b) |
| } |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| status, b = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`) |
| @@ -258,29 +258,20 @@ func setupClaimBuyDoors(t *testing.T, cx *claimCase) { |
| cx.srv.cfg.ZoneHost = zonehosttest.New("ns1.carloku.test") |
| cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| } |
| -func claimBuyForm(t *testing.T, cx *claimCase) int { |
| - kv := []string{"name", "shop.com", "currency", "usd", "price", "1500"} |
| - for _, field := range buyContactFields(purchaseContact()) { |
| - kv = append(kv, field.Name, field.Value) |
| - } |
| - return cx.formReply(t, "/a/bab/apps/kass/domains/buy", kv...).Status |
| -} |
| -func claimBuyCheck(t *testing.T, cx *claimCase, open bool) string { |
| - ps, err := cx.st.LiveDomainPurchases() |
| - if err != nil { |
| - return err.Error() |
| + |
| +// TestBuyDoorsAbsentOnHostClaimConsole: no purchase path runs under the |
| +// armed gate. The buy doors are not registered (so the claim census has no |
| +// entry for them), and the purchase pass leaves a live purchase alone. |
| +func TestBuyDoorsAbsentOnHostClaimConsole(t *testing.T) { |
| + cx := newClaimCase(t) |
| + for _, p := range claimFixtureCensus(cx.srv.claimEntries.snapshot(), claimFixtures) { |
| + t.Error(p) |
| } |
| - if open { |
| - if len(ps) != 1 || ps[0].CheckoutSession == "" { |
| - return "purchase did not reach checkout" |
| - } |
| - } else if len(ps) != 0 { |
| - return "blocked purchase wrote a journal row" |
| + setupClaimBuyDoors(t, cx) |
| + if cx.srv.domainBuyReady() { |
| + t.Fatal("buying is on with host claims on") |
| } |
| - return "" |
| -} |
| -func TestBuyDoorClaimBoundaries(t *testing.T) { |
| - keys := []string{ |
| + for _, path := range []string{ |
| "route POST /api/cli/accounts/{account}/domains/check", |
| "route POST /api/cli/accounts/{account}/domains/purchases", |
| "route GET /api/cli/accounts/{account}/domains/purchases/{id}", |
| @@ -289,37 +280,31 @@ func TestBuyDoorClaimBoundaries(t *testing.T) { |
| "route POST /a/{sqid}/apps/{app}/domains/buy", |
| "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}", |
| "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", |
| + } { |
| + if _, ok := claimFixtures[path]; ok { |
| + t.Errorf("%s is in the host-claim census", path) |
| + } |
| } |
| - cx := newClaimCase(t) |
| - for _, p := range claimFixtureCensus(cx.srv.claimEntries.snapshot(), claimFixtures) { |
| - t.Error(p) |
| + if status := cx.api(t, http.MethodPost, "/api/cli/accounts/bab/domains/check", `{"name":"shop.com"}`); status != http.StatusNotFound { |
| + t.Fatalf("check door on a host-claim console: %d", status) |
| } |
| - for _, p := range claimProbeCensus(claimFixtures, claimProbes) { |
| - t.Error(p) |
| + setupClaimPurchase(t, cx) |
| + before, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil || before == nil { |
| + t.Fatal(before, err) |
| } |
| - for _, key := range keys { |
| - t.Run(key, func(t *testing.T) { |
| - f := claimFixtures[key] |
| - if f.door != nil { |
| - problems, writers := runClaimDoor(t, f.door) |
| - for _, p := range problems { |
| - t.Error(p) |
| - } |
| - found := false |
| - for _, w := range writers { |
| - if w == "sql/domain_purchases" { |
| - found = true |
| - } |
| - } |
| - if !found { |
| - t.Error("purchase writer not covered") |
| - } |
| - } else { |
| - for _, p := range runClaimProbe(t, newClaimCase(t), key, claimProbes[key]) { |
| - t.Error(p) |
| - } |
| - } |
| - }) |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + cx.srv.RunClaimWorker(ctx, "StartDomainPurchasePass") |
| + if err := cx.srv.domainPurchasePass(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + after, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil || after.State != before.State || after.Revision != before.Revision { |
| + t.Fatalf("purchase moved on a host-claim console: %+v -> %+v %v", before, after, err) |
| + } |
| + if zone := cx.srv.cfg.ZoneHost.(*zonehosttest.Fake); len(zone.Calls) != 0 { |
| + t.Fatalf("zone effects: %v", zone.Calls) |
| } |
| } |
| @@ -407,7 +392,7 @@ func TestBrowserBuyPrefillsContactAndHidesUnconfigured(t *testing.T) { |
| signUp(t, f.consoleFixture, c, "prefill") |
| contact := purchaseContact() |
| contact.HouseNumber = "42" |
| - if err := f.st.SetDomainContact(f.acct.ID, contact, ""); err != nil { |
| + if err := f.addContact(contact); err != nil { |
| t.Fatal(err) |
| } |
| base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass" |
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go| index d400d525b..69e2d49c1 100644 |
| --- a/internal/console/appdomainbuy.go |
| +++ b/internal/console/appdomainbuy.go |
| @@ -154,11 +154,17 @@ func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request) |
| s.renderDoorRefusal(w, r, ref) |
| return |
| } |
| - c, _, err := s.store.DomainContact(acct.ID) |
| + // The form starts from the most recently used saved contact, whose |
| + // country checkDomainBuy's quote assumed when the request named none. |
| + contacts, err := s.store.SavedContacts(ctx, acct.ID) |
| if err != nil { |
| s.renderDoorRefusal(w, r, domainBuyUnavailable()) |
| return |
| } |
| + var c registrar.Contact |
| + if len(contacts) > 0 { |
| + c = contacts[0].Contact |
| + } |
| if country := r.FormValue("country"); country != "" { |
| c.Country = country |
| } |
| @@ -182,7 +188,7 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) { |
| if err != nil { |
| price = 0 |
| } |
| - p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr, domainreg.Quote{Currency: r.FormValue("currency"), Price: price}) |
| + p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), purchaseContactSelection{New: &c}, addr, domainreg.Quote{Currency: r.FormValue("currency"), Price: price}) |
| if changed != nil { |
| s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: changed, Fields: buyContactFields(c), PriceChanged: true}) |
| return |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index ffa1469a2..380981d5b 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1516,7 +1516,6 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| // Plans 6b: the locked portal opens a provider portal session for the |
| // account's customer and writes nothing locally. |
| - "route POST /a/{sqid}/billing/card": claimNonApp("creates or reuses the account billing customer and opens a card setup session; writes only account billing state and names no app"), |
| "route POST /a/{sqid}/billing/portal": claimNonApp("opens a provider portal session for the account's customer and redirects the owner to it, writing nothing locally; names no app"), |
| // Plans 6b: an owner's Confirm now finishes an outstanding billing |
| // operation under the account's billing hold and refreshes the |
| @@ -2519,39 +2518,9 @@ var claimFixtures = map[string]claimFixture{ |
| }, |
| do: claimWorker("StartDoorKeyResign"), |
| }}, |
| - "route POST /api/cli/accounts/{account}/domains/check": claimRead("checks availability and price without reserving or buying"), |
| - "route GET /api/cli/accounts/{account}/domains/purchases/{id}": claimRead("reads an owned purchase and wakes the worker without taking an app operation"), |
| - "route GET /a/{sqid}/apps/{app}/domains/buy": claimRead("renders the owner's domain search form"), |
| - "route POST /a/{sqid}/apps/{app}/domains/check": claimRead("quotes a domain and reads the account's stored contact"), |
| - "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}": claimRead("renders an owned purchase's progress page"), |
| - "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status": claimRead("reads purchase progress through the session gate"), |
| - "route POST /api/cli/accounts/{account}/domains/purchases": {door: &claimDoor{ |
| - apps: claimRefs("bab/kass"), setup: setupClaimBuyDoors, |
| - do: claimAPI(http.MethodPost, "/api/cli/accounts/bab/domains/purchases", buyBody()), check: claimBuyCheck, |
| - }}, |
| - "route POST /a/{sqid}/apps/{app}/domains/buy": {door: &claimDoor{ |
| - apps: claimRefs("bab/kass"), setup: setupClaimBuyDoors, do: claimBuyForm, check: claimBuyCheck, |
| - }}, |
| - |
| - "worker StartDomainPurchasePass": {door: &claimDoor{ |
| - apps: claimRefs("bab/kass"), |
| - setup: setupClaimPurchase, |
| - do: claimWorker("StartDomainPurchasePass"), |
| - check: func(t *testing.T, cx *claimCase, open bool) string { |
| - p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| - if err != nil || p == nil { |
| - return fmt.Sprintf("purchase: %+v %v", p, err) |
| - } |
| - want := PurchaseAwaitingPayment |
| - if open { |
| - want = PurchaseExpired |
| - } |
| - if p.State != want { |
| - return fmt.Sprintf("purchase state %s, want %s", p.State, want) |
| - } |
| - return "" |
| - }, |
| - }}, |
| + // The domain buy doors are not registered on a host-claim console |
| + // (gateNoHostClaim): buying is off there. |
| + "worker StartDomainPurchasePass": claimRead("off on a host-claim console, where buying domains is off: it logs that and reads and writes nothing"), |
| "worker StartExpiryPass": {door: &claimDoor{ |
| apps: claimRefs("bab/tmp-claim-expiry"), |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 4d6417813..119be2108 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -22,16 +22,13 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/billing/billingtest" |
| - "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/infraview" |
| "github.com/carlosframework/platform/internal/plans" |
| - "github.com/carlosframework/platform/internal/registrar/registrartest" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| "github.com/carlosframework/platform/internal/telemetry" |
| - "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| ) |
| // claimProbes is every read, nonApp and worker probe, merged. A key in two |
| @@ -989,31 +986,6 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| - "route POST /a/{sqid}/billing/card": { |
| - setup: func(t *testing.T, cx *claimCase) { |
| - claimCheckoutWorld(t, cx) |
| - cx.srv.cfg.Registrar = registrartest.New() |
| - cx.srv.cfg.ZoneHost = zonehosttest.New("ns1.example.test") |
| - cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3} |
| - sponsored := sponsorUnlimited() |
| - if _, err := cx.st.SetAccountPlan(OpsAccountID, "free", nil, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - }, |
| - do: claimFormReply("/a/bab/billing/card"), |
| - status: http.StatusSeeOther, loc: "https://checkout.example.test/c/", |
| - effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| - fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake) |
| - fake.Lock() |
| - defer fake.Unlock() |
| - for _, p := range fake.Sent { |
| - if p.Kind == billing.PreparedSetupCheckout { |
| - return "" |
| - } |
| - } |
| - return "no card setup session was created" |
| - }, |
| - }, |
| "route POST /a/{sqid}/billing/portal": { |
| setup: claimBillingWorld, |
| do: claimFormReply("/a/bab/billing/portal"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 4cc42ab6a..28ea01003 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -253,15 +253,6 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /upgrade": {setup: claimBillingWorld, do: claimPageReply("/upgrade?plan=personal"), status: http.StatusSeeOther, |
| loc: "/a/bab/billing?plan=personal"}, |
| - "route POST /api/cli/accounts/{account}/domains/check": {setup: setupClaimBuyDoors, |
| - do: claimAPIReply(http.MethodPost, "/api/cli/accounts/bab/domains/check", `{"name":"shop.com"}`), body: []string{`"domain":"shop.com"`, `"price":1500`}}, |
| - "route GET /api/cli/accounts/{account}/domains/purchases/{id}": claimAPIRead(setupClaimPurchase, "/api/cli/accounts/bab/domains/purchases/dp_claim_purchase", `"id":"dp_claim_purchase"`), |
| - "route GET /a/{sqid}/apps/{app}/domains/buy": claimPageRead(setupClaimBuyDoors, "/a/bab/apps/kass/domains/buy", "Check availability"), |
| - "route POST /a/{sqid}/apps/{app}/domains/check": {setup: setupClaimBuyDoors, |
| - do: claimFormReply("/a/bab/apps/kass/domains/check", "name", "shop.com"), body: []string{"shop.com", "PhoneCountryCode"}}, |
| - "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}": claimPageRead(setupClaimPurchase, "/a/bab/apps/kass/domains/purchases/dp_claim_purchase", "shop.com"), |
| - "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status": claimPageRead(setupClaimPurchase, "/a/bab/apps/kass/domains/purchases/dp_claim_purchase/status", `"id":"dp_claim_purchase"`), |
| - |
| // ---- the CLI's reads ---- |
| "route GET /api/cli/apps": claimAPIRead(nil, "/api/cli/apps", `"sqid":"bab"`, `"kass"`), |
| "route GET /api/cli/apps/{account}/list": claimAPIRead(nil, "/api/cli/apps/bab/list", `"kass"`), |
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go| index 007d82750..29941bbce 100644 |
| --- a/internal/console/claim_invariant_probes_worker_test.go |
| +++ b/internal/console/claim_invariant_probes_worker_test.go |
| @@ -84,6 +84,7 @@ var claimWorkerProbes = map[string]claimProbe{ |
| "worker FleetRelabel": claimLogWorkerProbe("FleetRelabel", nil, "fleet relabel", "host-claim console"), |
| "worker ManagedFleets": claimLogWorkerProbe("ManagedFleets", nil, "managed fleets", "host-claim console"), |
| "worker StartSeedsPass": claimLogWorkerProbe("StartSeedsPass", nil, "seeds pass", "host-claim console"), |
| + "worker StartDomainPurchasePass": claimLogWorkerProbe("StartDomainPurchasePass", nil, "domain purchase pass", "host-claim console"), |
| "worker StartLifetimesCutoverWatch": claimLogWorkerProbe("StartLifetimesCutoverWatch", nil, "lifetimes cutover watch", "host-claim console"), |
| "worker StartLifetimeRecoveryPass": claimLogWorkerProbe("StartLifetimeRecoveryPass", nil, "lifetime recovery pass", "host-claim console"), |
| "worker StartIncarnationMigrationPass": claimLogWorkerProbe("StartIncarnationMigrationPass", nil, "incarnation migration pass", "host-claim console"), |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 10ec5f335..69441b91e 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -207,6 +207,7 @@ 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", |
| + "sql/domain_purchases": "buying domains is off on a host-claim console: the buy doors are not registered and the purchase pass returns at once; TestBuyDoorsAbsentOnHostClaimConsole proves a live purchase is never advanced", |
| "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, " + |
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go| index 00e125718..c756569f2 100644 |
| --- a/internal/console/domainattach.go |
| +++ b/internal/console/domainattach.go |
| @@ -402,12 +402,11 @@ func (s *Server) detachDomain(ctx context.Context, acct *Account, app, host, pri |
| if msg, status := s.controlPlaneRefusal(acct, app, "detached"); msg != "" { |
| return &doorRefusal{Status: status, Msg: msg} |
| } |
| - notAttached := &doorRefusal{Status: http.StatusNotFound, Msg: "not attached to this app"} |
| // A host that is not even a hostname cannot be a claim key: refuse it |
| // here rather than handing it to a store as a key segment. |
| host, ok := domains.NormalizeAliasHost(host) |
| if !ok { |
| - return notAttached |
| + return domainNotAttached() |
| } |
| // A platform hostname's claim is the operator's to release (#209). |
| // Decided from the name alone, before the claim is read, so it says |
| @@ -420,6 +419,22 @@ func (s *Server) detachDomain(ctx context.Context, acct *Account, app, host, pri |
| if s.domainHostPolicy(namespaceView{}, host, acct.Sqid) == hostPlatform && !s.platformOperator(principal) { |
| return &doorRefusal{Status: http.StatusForbidden, Msg: platformOperatorMsg} |
| } |
| + return s.releaseDomainHost(ctx, acct, app, host, principal) |
| +} |
| + |
| +func domainNotAttached() *doorRefusal { |
| + return &doorRefusal{Status: http.StatusNotFound, Msg: "not attached to this app"} |
| +} |
| + |
| +// releaseDomainHost is detach's removal, after detach's own door checks: it |
| +// reads host's claim and, only when it is acct's app's, removes the |
| +// first-route record behind it (if any) and then the claim, announcing the |
| +// change. Anything else (no claim, another account's or another app's) is |
| +// the 404 refusal, with nothing touched. A finished purchase whose app has |
| +// 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 |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 61e142e27..07e10186b 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -23,8 +23,11 @@ func (s *Server) domainBuyReady() bool { |
| return s.domainPurchaseReady() && s.cfg.DomainCatalog != nil && s.cfg.DomainCatalog.DailyCap > 0 |
| } |
| +// domainPurchaseReady is false on a host-claim console: no purchase path |
| +// runs under the armed gate, so buying is off there (CARLOS_HOST_CLAIM is |
| +// shelved and off on every deployment that sells domains). |
| func (s *Server) domainPurchaseReady() bool { |
| - return s.cfg.Registrar != nil && s.cfg.ZoneHost != nil && s.cfg.Releases != nil && s.billing != nil && s.billing.ready.Load() |
| + return !s.cfg.HostClaim && s.cfg.Registrar != nil && s.cfg.ZoneHost != nil && s.cfg.Releases != nil && s.billing != nil && s.billing.ready.Load() |
| } |
| func domainBuyUnavailable() *doorRefusal { |
| @@ -125,10 +128,45 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string, |
| return q, nil |
| } |
| +// purchaseContactSelection is the registrant a purchase starts with: a saved |
| +// contact of the account, or a new one the purchase saves. Exactly one is |
| +// set. |
| +type purchaseContactSelection struct { |
| + ID string // a saved contact of the account |
| + New *registrar.Contact // or a new one, saved by the purchase |
| +} |
| + |
| +// domainPurchaseBeforeInsert, when set, runs under the billing hold just |
| +// before a start re-reads the account and inserts its purchase. A TEST SEAM. |
| +var domainPurchaseBeforeInsert func(ctx context.Context, s *Server, acct *Account) |
| + |
| +// purchaseContactFor reads the selected contact. ok is false when the |
| +// selection names both or neither, or a saved contact that is missing or |
| +// another account's; the caller answers that with the contact refusal. |
| +func (s *Server) purchaseContactFor(ctx context.Context, acct *Account, sel purchaseContactSelection) (c registrar.Contact, saved *SavedContact, ok bool, err error) { |
| + if (sel.ID == "") == (sel.New == nil) { |
| + return registrar.Contact{}, nil, false, nil |
| + } |
| + if sel.New != nil { |
| + return *sel.New, nil, true, nil |
| + } |
| + saved, err = s.store.SavedContact(ctx, acct.ID, sel.ID) |
| + if err != nil || saved == nil { |
| + return registrar.Contact{}, nil, false, err |
| + } |
| + return saved.Contact, saved, true, nil |
| +} |
| + |
| // A non-nil third result supplies the replacement quote for confirmation. |
| -func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string, confirmed domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) { |
| +// app "" is "Not yet" (§11.4): the purchase registers the domain and points |
| +// it at nothing. |
| +func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, contact purchaseContactSelection, principal string, confirmed domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) { |
| // Serialize starts so a concurrent buyer resumes the winning checkout. |
| defer s.planLock(acct)() |
| + c, saved, contactOK, err := s.purchaseContactFor(ctx, acct, contact) |
| + if err != nil { |
| + return nil, "", nil, domainBuyUnavailable() |
| + } |
| q, ref := s.admitDomainBuy(ctx, acct, name, c.Country) |
| if ref != nil { |
| return nil, "", nil, ref |
| @@ -146,20 +184,22 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return p, link, nil, ref |
| } |
| - exists, err := s.store.HasAppIn(acct.ID, app) |
| - if err != nil { |
| - return nil, "", nil, domainBuyUnavailable() |
| - } |
| - if !exists { |
| - return nil, "", nil, &doorRefusal{Status: http.StatusNotFound} |
| - } |
| - // The app comes from the request body, so no route policy saw it: a |
| - // linked app takes no custom domain (LD-C12), refused before any |
| - // billing. |
| - if ref := s.linkedRefusalFor(ctx, acct, app, linkedRefuseDomains); ref != nil { |
| - return nil, "", nil, ref |
| + if app != "" { |
| + exists, err := s.store.HasAppInContext(ctx, acct.ID, app) |
| + if err != nil { |
| + return nil, "", nil, domainBuyUnavailable() |
| + } |
| + if !exists { |
| + return nil, "", nil, &doorRefusal{Status: http.StatusNotFound} |
| + } |
| + // The app comes from the request body, so no route policy saw it: a |
| + // linked app takes no custom domain (LD-C12), refused before any |
| + // billing. |
| + if ref := s.linkedRefusalFor(ctx, acct, app, linkedRefuseDomains); ref != nil { |
| + return nil, "", nil, ref |
| + } |
| } |
| - if err := c.Validate(); err != nil { |
| + if !contactOK || c.Validate() != nil { |
| return nil, "", nil, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["contactError"]} |
| } |
| h, release, err := s.holdBilling(acct) |
| @@ -205,16 +245,13 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return nil, "", nil, domainBuyUnavailable() |
| } |
| _, err = s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true) |
| - release() |
| if err != nil { |
| + release() |
| log.Printf("console: domain buy billing %s: %v", acct.Sqid, err) |
| return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| } |
| - now := time.Now().UTC() |
| - p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: acct.ID, Domain: q.Domain, App: app, Currency: q.Currency, Amount: q.Price, |
| - State: PurchaseAwaitingPayment, CheckoutExpires: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now, |
| - purchaseDetails: purchaseDetails{Principal: principal, Contact: c}} |
| - err = s.store.withAutoAppSQL(ctx, acct.ID, app, "sql.CreateDomainPurchase", func(st *Store) error { return st.CreateDomainPurchase(p) }) |
| + p, err := s.insertDomainPurchaseLocked(ctx, acct, app, principal, q, c, saved) |
| + release() |
| if errors.Is(err, ErrDomainPurchaseLive) { |
| own, readErr := s.ownLiveDomainPurchase(ctx, acct.ID, name) |
| if readErr != nil { |
| @@ -233,10 +270,68 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| if err != nil { |
| return nil, "", nil, domainBuyUnavailable() |
| } |
| - purchase, link, ref := s.resumeDomainPurchase(ctx, &p) |
| + purchase, link, ref := s.resumeDomainPurchase(ctx, p) |
| return purchase, link, nil, ref |
| } |
| +// insertDomainPurchaseLocked writes the purchase row under the account's |
| +// billing hold, which account deletion holds from retireForDeletion through |
| +// DeleteAccount: the account is re-read here, and a start for an account |
| +// that is gone or being deleted writes nothing. So a purchase row either |
| +// exists before deletion checks for one, or is never written. |
| +// |
| +// The purchase freezes its contact (R12): a new contact is saved first and |
| +// the purchase takes that copy; a saved one is copied with its version and, |
| +// when it has one, its registrar handle. Later steps read only the copy. |
| +func (s *Server) insertDomainPurchaseLocked(ctx context.Context, acct *Account, app, principal string, q domainreg.Quote, c registrar.Contact, saved *SavedContact) (*DomainPurchase, error) { |
| + if domainPurchaseBeforeInsert != nil { |
| + domainPurchaseBeforeInsert(ctx, s, acct) |
| + } |
| + now := time.Now().UTC() |
| + fresh, err := s.store.AccountByID(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if fresh == nil { |
| + return nil, errAccountGoneOrRetiring |
| + } |
| + retiring, err := s.store.BillingRetiring(acct.ID, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if retiring { |
| + return nil, errAccountGoneOrRetiring |
| + } |
| + details := purchaseDetails{Principal: principal, Contact: c} |
| + added := false |
| + if saved == nil { |
| + sc, err := s.store.AddSavedContact(ctx, acct.ID, c, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + saved, added = &sc, true |
| + } |
| + details.ContactID, details.ContactVersion, details.OwnerHandle = saved.ID, saved.Version, saved.RegistrarHandle |
| + p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: acct.ID, Domain: q.Domain, App: app, Currency: q.Currency, Amount: q.Price, |
| + State: PurchaseAwaitingPayment, CheckoutExpires: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now, |
| + purchaseDetails: details} |
| + err = s.store.withAutoAppSQL(ctx, acct.ID, app, "sql.CreateDomainPurchase", func(st *Store) error { return st.CreateDomainPurchase(p) }) |
| + if err != nil && added { |
| + // The contact was saved for this purchase only; nothing refers to it. |
| + if rmErr := s.store.RemoveSavedContact(ctx, acct.ID, saved.ID); rmErr != nil { |
| + log.Printf("console: domain buy %s: removing an unused contact: %v", acct.Sqid, rmErr) |
| + } |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &p, nil |
| +} |
| + |
| +// errAccountGoneOrRetiring refuses a start whose account was deleted, or |
| +// marked for deletion, before the start held the billing hold. |
| +var errAccountGoneOrRetiring = errors.New("console: domain buy: the account is gone or being deleted") |
| + |
| 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) { |
| @@ -345,11 +440,10 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| return "", s.movePurchase(ctx, p, PurchaseExpired, nil) |
| } |
| if p.OwnerHandle == "" { |
| - _, existing, err := s.store.DomainContact(p.AccountID) |
| - if err != nil { |
| - return "", err |
| - } |
| - handle, err := s.cfg.Registrar.EnsureContact(ctx, existing, p.Contact) |
| + // The purchase's frozen copy gets a handle of its own (R12): no |
| + // stored handle, the saved contact's or the old account row's, is |
| + // ever passed to the registrar to be updated in place. |
| + handle, err := s.cfg.Registrar.EnsureContact(ctx, "", p.Contact) |
| if err != nil { |
| if errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrSetup) { |
| return "", errors.Join(err, s.movePurchase(ctx, p, PurchaseFailed, func(p *DomainPurchase) { p.Reason = "contact" })) |
| @@ -362,11 +456,17 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.OwnerHandle = handle }); err != nil { |
| return "", err |
| } |
| + if p.ContactID != "" { |
| + // Kept only while the saved contact is still the version this |
| + // purchase froze and has no handle; false means it was edited |
| + // (or removed) meanwhile, which is fine. |
| + if _, err := s.store.SetSavedContactHandle(ctx, p.AccountID, p.ContactID, p.ContactVersion, handle); err != nil { |
| + log.Printf("console: purchase %s: saving the contact handle: %v", p.ID, err) |
| + jobFailed(ctx, err) |
| + } |
| + } |
| } |
| if p.CheckoutPrepared == nil { |
| - if err := s.store.SetDomainContact(p.AccountID, p.Contact, p.OwnerHandle); err != nil { |
| - return "", err |
| - } |
| acct, err := s.store.AccountByID(p.AccountID) |
| if err != nil { |
| return "", err |
| @@ -408,19 +508,21 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.CheckoutSession = info.SessionID }); err != nil { |
| return "", err |
| } |
| + if p.ContactID != "" { |
| + if err := s.store.TouchSavedContact(ctx, p.AccountID, p.ContactID, time.Now()); err != nil { |
| + log.Printf("console: purchase %s: marking the contact used: %v", p.ID, err) |
| + jobFailed(ctx, err) |
| + } |
| + } |
| return info.URL, nil |
| } |
| +// purchaseMutation re-reads the purchase and runs call only when its state |
| +// and revision are still the snapshot's. A purchase for an app runs it |
| +// inside the app's mutation; one with no app has no app to hold. |
| func (s *Server) purchaseMutation(ctx context.Context, p *DomainPurchase, call func(context.Context) error) error { |
| - acct, err := s.store.AccountByID(p.AccountID) |
| - if err != nil { |
| - return err |
| - } |
| - if acct == nil { |
| - return sql.ErrNoRows |
| - } |
| var stepErr error |
| - err = s.claimAppMutation(ctx, acct, p.App, "domain-purchase", func(ctx context.Context) error { |
| + step := func(ctx context.Context) error { |
| fresh, err := s.store.DomainPurchase(p.ID) |
| if err != nil { |
| return err |
| @@ -432,7 +534,19 @@ func (s *Server) purchaseMutation(ctx context.Context, p *DomainPurchase, call f |
| // The journal owns retries after provider errors, including lost responses. |
| stepErr = call(ctx) |
| return nil |
| - }) |
| + } |
| + if p.App == "" { |
| + err := step(ctx) |
| + return errors.Join(err, stepErr) |
| + } |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return err |
| + } |
| + if acct == nil { |
| + return sql.ErrNoRows |
| + } |
| + err = s.claimAppMutation(ctx, acct, p.App, "domain-purchase", step) |
| return errors.Join(err, stepErr) |
| } |
| @@ -519,21 +633,10 @@ func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *D |
| return err |
| } |
| - source := s.cfg.DomainApex |
| - if source == nil { |
| - source = zonehost.StaticApex(s.dnsTargets(ctx).EdgeIPs) |
| - } |
| - apex, err := source.ApexTargets(ctx) |
| + m, err := s.purchaseManagedSet(ctx, p) |
| if err != nil { |
| return err |
| } |
| - m := zonehost.ManagedSet{Apex: apex, WWW: true} |
| - if s.cfg.DomainProof { |
| - for _, host := range []string{p.Domain, "www." + p.Domain} { |
| - txt := s.domainChallenge(host, acct.Sqid) |
| - m.TXT = append(m.TXT, zonehost.TXT{Name: txt.Name, Value: txt.Value}) |
| - } |
| - } |
| if err := s.cfg.ZoneHost.SetManaged(ctx, z, m); err != nil { |
| return err |
| } |
| @@ -577,31 +680,101 @@ func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *D |
| } |
| return billing.ErrIndeterminate |
| case PurchaseCaptured: |
| - // Reserve this revision before either attach; capacity refusals do not count as attempts. |
| - if err := s.movePurchase(ctx, p, p.State, nil); err != nil { |
| - return err |
| + return s.capturedPurchase(ctx, acct, p) |
| + } |
| + return nil |
| +} |
| + |
| +// purchaseManagedSet is the zone's managed records for the purchase: none |
| +// for a purchase with no app (an unpointed zone), otherwise the canonical |
| +// pointed set, with the apex and www proofs when DomainProof is on. A |
| +// failed apex read is an error, never the empty set. |
| +func (s *Server) purchaseManagedSet(ctx context.Context, p *DomainPurchase) (zonehost.ManagedSet, error) { |
| + if p.App == "" { |
| + return zonehost.ManagedSet{}, nil |
| + } |
| + source := s.cfg.DomainApex |
| + if source == nil { |
| + source = zonehost.StaticApex(s.dnsTargets(ctx).EdgeIPs) |
| + } |
| + apex, err := source.ApexTargets(ctx) |
| + if err != nil { |
| + return zonehost.ManagedSet{}, err |
| + } |
| + var proof func(host string) zonehost.TXT |
| + if s.cfg.DomainProof { |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return zonehost.ManagedSet{}, err |
| } |
| - for _, host := range []string{p.Domain, "www." + p.Domain} { |
| - _, ref := s.attachDomain(ctx, acct, p.App, host, "", "", p.Principal) |
| - if ref != nil { |
| - capacityRefused := ref.haCapacityRetryAfter > 0 |
| - if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { |
| - p.Reason = ref.Msg |
| - if !capacityRefused { |
| - p.Attempts++ |
| - } |
| - }); err != nil { |
| - return err |
| - } |
| - if !capacityRefused && p.Attempts == 10 { |
| - s.purchaseAlert(ctx, acct, p.Domain, p.ID, p.Reason) |
| + if acct == nil { |
| + return zonehost.ManagedSet{}, sql.ErrNoRows |
| + } |
| + proof = func(host string) zonehost.TXT { |
| + txt := s.domainChallenge(host, acct.Sqid) |
| + return zonehost.TXT{Name: txt.Name, Value: txt.Value} |
| + } |
| + } |
| + return zonehost.ManagedFor(p.Domain, apex, proof), nil |
| +} |
| + |
| +// capturedPurchase finishes a paid purchase. With no app it is done. With |
| +// an app it attaches the apex and www to it; when the app has been purged |
| +// or put in Trash since, it finishes unpointed instead. |
| +func (s *Server) capturedPurchase(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| + if p.App == "" { |
| + return s.movePurchase(ctx, p, PurchaseDone, func(p *DomainPurchase) { p.Reason = "" }) |
| + } |
| + // Reserve this revision before any attach or release; capacity refusals do not count as attempts. |
| + if err := s.movePurchase(ctx, p, p.State, nil); err != nil { |
| + return err |
| + } |
| + present, err := s.store.HasAppInContext(ctx, acct.ID, p.App) |
| + if err != nil { |
| + return err |
| + } |
| + if !present { |
| + return s.finishPurchaseUnpointed(ctx, acct, p) |
| + } |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + _, ref := s.attachDomain(ctx, acct, p.App, host, "", "", p.Principal) |
| + if ref != nil { |
| + capacityRefused := ref.haCapacityRetryAfter > 0 |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { |
| + p.Reason = ref.Msg |
| + if !capacityRefused { |
| + p.Attempts++ |
| } |
| - return nil |
| + }); err != nil { |
| + return err |
| } |
| + if !capacityRefused && p.Attempts == 10 { |
| + s.purchaseAlert(ctx, acct, p.Domain, p.ID, p.Reason) |
| + } |
| + return nil |
| } |
| - return s.movePurchase(ctx, p, PurchaseDone, func(p *DomainPurchase) { p.Reason = ""; p.Attempts++ }) |
| } |
| - return nil |
| + return s.movePurchase(ctx, p, PurchaseDone, func(p *DomainPurchase) { p.Reason = ""; p.Attempts++ }) |
| +} |
| + |
| +// finishPurchaseUnpointed finishes a paid purchase whose app is gone |
| +// (purged, or in Trash: attaching to it would serve nothing). It first |
| +// releases whatever an earlier pass attached to the app, the apex and www |
| +// claims and any first-route record behind them, through detach's own |
| +// removal, which never touches another holder's claim. Then it unpoints the |
| +// zone and finishes with no app. Any failure leaves the purchase captured |
| +// for the next pass. Buying is off under host claims, so this never runs |
| +// against an armed gate. |
| +func (s *Server) finishPurchaseUnpointed(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + if ref := s.releaseDomainHost(ctx, acct, p.App, host, p.Principal); ref != nil && ref.Status != http.StatusNotFound { |
| + return fmt.Errorf("console: purchase %s: releasing %s from %s: %d %s", p.ID, host, p.App, ref.Status, ref.Msg) |
| + } |
| + } |
| + if err := s.cfg.ZoneHost.SetManaged(ctx, zonehost.Zone{ID: p.ZoneID, Domain: p.Domain}, zonehost.ManagedSet{}); err != nil { |
| + return err |
| + } |
| + return s.movePurchase(ctx, p, PurchaseDone, func(p *DomainPurchase) { p.App = ""; p.Reason = "app_gone" }) |
| } |
| func (s *Server) reconcileRegisteringPurchase(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| @@ -736,14 +909,23 @@ func (s *Server) registeredPurchase(ctx context.Context, p *DomainPurchase, r re |
| return registrar.ErrIndeterminate |
| } |
| // Insert before advancing; after a crash the matching row is the same registration. |
| - err := s.store.AddDomainRegistration(DomainRegistration{Domain: p.Domain, AccountID: p.AccountID, RegistrarID: r.RegistrarID, ZoneID: p.ZoneID, Expires: r.Expires, AutoRenew: true}) |
| + // The registrant is the purchase's frozen contact, never the saved one. |
| + err := s.store.AddDomainRegistration(DomainRegistration{Domain: p.Domain, AccountID: p.AccountID, RegistrarID: r.RegistrarID, ZoneID: p.ZoneID, Expires: r.Expires, AutoRenew: true, Registrant: p.Contact}) |
| if err != nil { |
| var account int64 |
| var registrarID, zoneID string |
| - readErr := s.store.db.QueryRow(`SELECT account_id,registrar_id,zone_id FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&account, ®istrarID, &zoneID) |
| + readErr := s.store.db.QueryRowContext(ctx, `SELECT account_id,registrar_id,zone_id FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&account, ®istrarID, &zoneID) |
| if readErr != nil || account != p.AccountID || registrarID != r.RegistrarID || zoneID != p.ZoneID { |
| return err |
| } |
| + // The row an earlier attempt wrote may predate registrants. |
| + registrant, jsonErr := registrantJSON(p.Contact) |
| + if jsonErr != nil { |
| + return jsonErr |
| + } |
| + if _, err := s.store.db.ExecContext(ctx, `UPDATE domain_registrations SET registrant=? WHERE domain=? AND account_id=? AND registrant='{}'`, registrant, p.Domain, p.AccountID); err != nil { |
| + return err |
| + } |
| } |
| return s.movePurchase(ctx, p, PurchaseRegistered, func(p *DomainPurchase) { p.RegistrarID = r.RegistrarID; p.Reason = "" }) |
| } |
| @@ -812,6 +994,10 @@ func (s *Server) nudgePurchase(id string) { |
| } |
| func (s *Server) StartDomainPurchasePass(ctx context.Context) { |
| + if s.cfg.HostClaim { |
| + log.Printf("console: domain purchase pass: off on a host-claim console, where buying domains is off") |
| + return |
| + } |
| if s.cfg.Registrar == nil || s.cfg.ZoneHost == nil || s.billing == nil { |
| return |
| } |
diff --git a/internal/console/domainbuy_account_test.go b/internal/console/domainbuy_account_test.go| new file mode 100644 |
| index 000000000..b2032aead |
| --- /dev/null |
| +++ b/internal/console/domainbuy_account_test.go |
| @@ -0,0 +1,592 @@ |
| +package console |
| + |
| +// Plan 2a Task 4: purchases with no app, purchases bound to a frozen saved |
| +// contact, finishing unpointed when the app is gone, the start's insert |
| +// under the billing hold, and buying off while host claims are on. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// pausingRegistrar records the owner handle every Register names and, when |
| +// entered is set, stops the first EnsureContact until release is closed. |
| +type pausingRegistrar struct { |
| + *registrartest.Fake |
| + entered chan struct{} |
| + release chan struct{} |
| + once sync.Once |
| + mu sync.Mutex |
| + owners []string |
| +} |
| + |
| +func (r *pausingRegistrar) EnsureContact(ctx context.Context, existing string, c registrar.Contact) (string, error) { |
| + if r.entered != nil { |
| + r.once.Do(func() { |
| + close(r.entered) |
| + <-r.release |
| + }) |
| + } |
| + return r.Fake.EnsureContact(ctx, existing, c) |
| +} |
| + |
| +func (r *pausingRegistrar) Register(ctx context.Context, req registrar.Registration) (registrar.Registered, error) { |
| + r.mu.Lock() |
| + r.owners = append(r.owners, req.OwnerHandle) |
| + r.mu.Unlock() |
| + return r.Fake.Register(ctx, req) |
| +} |
| + |
| +func (r *pausingRegistrar) lastOwner() string { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if len(r.owners) == 0 { |
| + return "" |
| + } |
| + return r.owners[len(r.owners)-1] |
| +} |
| + |
| +func (f *purchaseFixture) startWith(t *testing.T, app string, sel purchaseContactSelection) *DomainPurchase { |
| + t.Helper() |
| + p, url, ref := startQuotedSelection(f.srv, context.Background(), f.acct, app, "shop.com", sel, "IE", "buyer@example.test") |
| + if ref != nil || p == nil || url == "" { |
| + t.Fatalf("start: %+v %q %+v", p, url, ref) |
| + } |
| + return p |
| +} |
| + |
| +func (f *purchaseFixture) saveContact(t *testing.T, c registrar.Contact) SavedContact { |
| + t.Helper() |
| + sc, err := f.st.AddSavedContact(context.Background(), f.acct.ID, c, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return sc |
| +} |
| + |
| +func (f *purchaseFixture) registrant(t *testing.T, domain string) registrar.Contact { |
| + t.Helper() |
| + r, err := f.st.DomainRegistrationFor(context.Background(), f.acct.ID, domain) |
| + if err != nil || r == nil { |
| + t.Fatalf("registration: %+v %v", r, err) |
| + } |
| + return r.Registrant |
| +} |
| + |
| +// assertUnpointed is the zone of an unpointed domain: SetManaged ran with |
| +// the empty set, so no apex, www or proof records stand. |
| +func (f *purchaseFixture) assertUnpointed(t *testing.T, domain string) { |
| + t.Helper() |
| + m, ok := f.zone.Managed[domain] |
| + if !ok || len(m.Apex) != 0 || m.WWW || len(m.TXT) != 0 { |
| + t.Fatalf("managed set: %+v (set %v)", m, ok) |
| + } |
| +} |
| + |
| +func (f *purchaseFixture) assertNoClaims(t *testing.T, domain string) { |
| + t.Helper() |
| + for _, host := range []string{domain, "www." + domain} { |
| + if c, err := domains.GetClaim(context.Background(), f.rel, host); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("claim %s: %+v %v", host, c, err) |
| + } |
| + } |
| +} |
| + |
| +func newContact() *registrar.Contact { |
| + c := purchaseContact() |
| + return &c |
| +} |
| + |
| +func TestPurchaseWithoutAppRegistersAndAttachesNothing(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.srv.cfg.DomainProof = true |
| + p := f.startWith(t, "", purchaseContactSelection{New: newContact()}) |
| + if p.App != "" || p.ContactID == "" || p.ContactVersion != 1 || p.Contact != purchaseContact() { |
| + t.Fatalf("started: %+v", p) |
| + } |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + f.assertUnpointed(t, p.Domain) |
| + p = f.until(t, p.ID, PurchaseDone) |
| + if p.App != "" || p.Reason != "" || f.sent(billing.PreparedCapture) != 1 || purchaseCalls(f.reg.Calls, "register:") != 1 { |
| + t.Fatalf("done: %+v %v", p, f.fake.Sent) |
| + } |
| + if got := f.registrant(t, p.Domain); got != purchaseContact() { |
| + t.Fatalf("registrant: %+v", got) |
| + } |
| + f.assertNoClaims(t, p.Domain) |
| + f.assertUnpointed(t, p.Domain) |
| +} |
| + |
| +func TestPurchaseAppPurgedMidwayFinishesUnpointed(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseRegistered) |
| + if len(f.zone.Managed[p.Domain].Apex) == 0 { |
| + t.Fatal("pointed zone expected before the app goes") |
| + } |
| + if err := f.st.TrashAppRow(f.acct.ID, "kass", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.st.PurgeAppRow(f.acct.ID, "kass"); err != nil { |
| + t.Fatal(err) |
| + } |
| + var rows int |
| + if err := f.st.db.QueryRow(`SELECT count(*) FROM apps WHERE account_id=? AND app='kass'`, f.acct.ID).Scan(&rows); err != nil || rows != 0 { |
| + t.Fatalf("app not purged: %d %v", rows, err) |
| + } |
| + p = f.until(t, p.ID, PurchaseDone) |
| + if p.App != "" || p.Reason != "app_gone" || f.sent(billing.PreparedCapture) != 1 || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatalf("done: %+v %v", p, f.fake.Sent) |
| + } |
| + f.assertUnpointed(t, p.Domain) |
| + f.assertNoClaims(t, p.Domain) |
| + if got := f.registrant(t, p.Domain); got != purchaseContact() { |
| + t.Fatalf("registrant: %+v", got) |
| + } |
| +} |
| + |
| +// failClaimDeleteStore fails the first Delete of one key. |
| +type failClaimDeleteStore struct { |
| + release.Store |
| + key string |
| + failed bool |
| +} |
| + |
| +func (s *failClaimDeleteStore) Delete(ctx context.Context, key string) error { |
| + if key == s.key && !s.failed { |
| + s.failed = true |
| + return errors.New("bucket unavailable") |
| + } |
| + return s.Store.Delete(ctx, key) |
| +} |
| + |
| +func TestPurchasePartialAttachThenTrashReleasesClaim(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + ctx := context.Background() |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseRegistered) |
| + foreign := domains.Claim{Schema: 1, Host: "www." + p.Domain, Account: "foreign", App: "other", CreatedBy: "other"} |
| + if _, _, err := domains.AttachClaim(ctx, f.rel, foreign); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Capture, then the apex attaches and www is refused. |
| + p = f.advance(t, p.ID) |
| + p = f.advance(t, p.ID) |
| + if p.State != PurchaseCaptured || p.Attempts != 1 { |
| + t.Fatalf("partial attach: %+v", p) |
| + } |
| + if c, err := domains.GetClaim(ctx, f.rel, p.Domain); err != nil || c.App != "kass" || c.Account != f.acct.Sqid { |
| + t.Fatalf("apex claim: %+v %v", c, err) |
| + } |
| + if err := f.st.TrashAppRow(f.acct.ID, "kass", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + failing := &failClaimDeleteStore{Store: f.srv.cfg.Releases, key: domains.ClaimKey(p.Domain)} |
| + f.srv.cfg.Releases = failing |
| + if err := f.srv.advancePurchase(ctx, p.ID); err == nil { |
| + t.Fatal("a failed release must be an error for the pass") |
| + } |
| + if p = f.read(t, p.ID); p.State != PurchaseCaptured || p.App != "kass" || !failing.failed { |
| + t.Fatalf("after a failed release: %+v", p) |
| + } |
| + if _, ok := f.zone.Managed[p.Domain]; !ok || len(f.zone.Managed[p.Domain].Apex) == 0 { |
| + t.Fatal("zone unpointed before the claims were released") |
| + } |
| + p = f.advance(t, p.ID) |
| + if p.State != PurchaseDone || p.App != "" || p.Reason != "app_gone" { |
| + t.Fatalf("finish: %+v", p) |
| + } |
| + if c, err := domains.GetClaim(ctx, f.rel, p.Domain); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("apex claim kept: %+v %v", c, err) |
| + } |
| + if c, err := domains.GetClaim(ctx, f.rel, "www."+p.Domain); err != nil || c.Account != "foreign" || c.App != "other" { |
| + t.Fatalf("foreign www claim touched: %+v %v", c, err) |
| + } |
| + f.assertUnpointed(t, p.Domain) |
| + if f.sent(billing.PreparedCapture) != 1 { |
| + t.Fatalf("captures: %v", f.fake.Sent) |
| + } |
| +} |
| + |
| +func TestBuyingOffWhileHostClaimOn(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + before := f.read(t, p.ID) |
| + zoneCalls, regCalls, sent := len(f.zone.Calls), len(f.reg.Calls), len(f.fake.Sent) |
| + |
| + f.srv.cfg.HostClaim = true |
| + if f.srv.domainBuyReady() || f.srv.domainPurchaseReady() { |
| + t.Fatal("buying is on while host claims are on") |
| + } |
| + tok := buyToken(t, f) |
| + for _, r := range []struct{ method, path, body string }{{"POST", "/check", `{"name":"shop.com"}`}, {"POST", "/purchases", buyBody()}, {"GET", "/purchases/" + p.ID, ""}} { |
| + if status, body := buyRequest(t, f, r.method, buyAPIPath(f)+r.path, tok, r.body); status != http.StatusNotFound { |
| + t.Fatalf("%s %s: %d %s", r.method, r.path, status, body) |
| + } |
| + } |
| + // The doors are not even registered on a host-claim console. |
| + for _, d := range routeDecls { |
| + if strings.Contains(d.Pattern, "/domains/buy") || strings.Contains(d.Pattern, "/domains/check") || strings.Contains(d.Pattern, "/domains/purchases") { |
| + if d.Gate != gateNoHostClaim { |
| + t.Errorf("%s is registered on a host-claim console", d.Pattern) |
| + } |
| + } |
| + } |
| + if err := f.srv.domainPurchasePass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + f.srv.StartDomainPurchasePass(context.Background()) |
| + close(done) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the purchase pass runs on a host-claim console") |
| + } |
| + after := f.read(t, p.ID) |
| + if after.State != before.State || after.Revision != before.Revision || len(f.zone.Calls) != zoneCalls || len(f.reg.Calls) != regCalls || len(f.fake.Sent) != sent { |
| + t.Fatalf("live purchase moved: %+v -> %+v", before, after) |
| + } |
| +} |
| + |
| +func TestPurchaseSavedContactWithHandleSkipsRegistrar(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + reg := &pausingRegistrar{Fake: f.reg} |
| + f.srv.cfg.Registrar = reg |
| + sc := f.saveContact(t, purchaseContact()) |
| + if ok, err := f.st.SetSavedContactHandle(context.Background(), f.acct.ID, sc.ID, sc.Version, "contact-saved"); err != nil || !ok { |
| + t.Fatal(ok, err) |
| + } |
| + p := f.startWith(t, "kass", purchaseContactSelection{ID: sc.ID}) |
| + if p.ContactID != sc.ID || p.ContactVersion != 1 || p.OwnerHandle != "contact-saved" || p.Contact != purchaseContact() { |
| + t.Fatalf("frozen: %+v", p.purchaseDetails) |
| + } |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + if n := purchaseCalls(f.reg.Calls, "contact:"); n != 0 || reg.lastOwner() != "contact-saved" { |
| + t.Fatalf("registrar contact calls=%d owner=%q", n, reg.lastOwner()) |
| + } |
| + used, err := f.st.SavedContact(context.Background(), f.acct.ID, sc.ID) |
| + if err != nil || used == nil || used.LastUsed.IsZero() { |
| + t.Fatalf("saved contact not touched: %+v %v", used, err) |
| + } |
| +} |
| + |
| +type startResult struct { |
| + p *DomainPurchase |
| + url string |
| + ref *doorRefusal |
| +} |
| + |
| +func (f *purchaseFixture) startPaused(t *testing.T, reg *pausingRegistrar, sel purchaseContactSelection) <-chan startResult { |
| + t.Helper() |
| + reg.entered, reg.release = make(chan struct{}), make(chan struct{}) |
| + f.srv.cfg.Registrar = reg |
| + out := make(chan startResult, 1) |
| + go func() { |
| + p, url, ref := startQuotedSelection(f.srv, context.Background(), f.acct, "kass", "shop.com", sel, "IE", "buyer@example.test") |
| + out <- startResult{p, url, ref} |
| + }() |
| + select { |
| + case <-reg.entered: |
| + case r := <-out: |
| + t.Fatalf("start finished without asking for a contact: %+v", r) |
| + } |
| + return out |
| +} |
| + |
| +func TestContactEditDuringPurchaseKeepsFrozenContact(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + ctx := context.Background() |
| + sc := f.saveContact(t, purchaseContact()) |
| + reg := &pausingRegistrar{Fake: f.reg} |
| + started := f.startPaused(t, reg, purchaseContactSelection{ID: sc.ID}) |
| + edited := purchaseContact() |
| + edited.FirstName = "Janet" |
| + if err := f.st.EditSavedContact(ctx, f.acct.ID, sc.ID, edited); err != nil { |
| + t.Fatal(err) |
| + } |
| + close(reg.release) |
| + r := <-started |
| + if r.ref != nil || r.p == nil || r.url == "" { |
| + t.Fatalf("start: %+v", r) |
| + } |
| + p := f.read(t, r.p.ID) |
| + if p.OwnerHandle == "" || p.Contact != purchaseContact() || p.ContactVersion != 1 { |
| + t.Fatalf("frozen: %+v", p.purchaseDetails) |
| + } |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + if reg.lastOwner() != p.OwnerHandle { |
| + t.Fatalf("registered with %q, want %q", reg.lastOwner(), p.OwnerHandle) |
| + } |
| + if got := f.registrant(t, p.Domain); got != purchaseContact() { |
| + t.Fatalf("registrant: %+v", got) |
| + } |
| + saved, err := f.st.SavedContact(ctx, f.acct.ID, sc.ID) |
| + if err != nil || saved == nil || saved.RegistrarHandle != "" || saved.Version != 2 || saved.Contact != edited { |
| + t.Fatalf("saved contact: %+v %v", saved, err) |
| + } |
| +} |
| + |
| +func TestContactRemovedDuringPurchaseStillFinishes(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + ctx := context.Background() |
| + sc := f.saveContact(t, purchaseContact()) |
| + reg := &pausingRegistrar{Fake: f.reg} |
| + started := f.startPaused(t, reg, purchaseContactSelection{ID: sc.ID}) |
| + if err := f.st.RemoveSavedContact(ctx, f.acct.ID, sc.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + close(reg.release) |
| + r := <-started |
| + if r.ref != nil || r.p == nil { |
| + t.Fatalf("start: %+v", r) |
| + } |
| + p := f.read(t, r.p.ID) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseDone) |
| + if got := f.registrant(t, p.Domain); got != purchaseContact() { |
| + t.Fatalf("registrant: %+v", got) |
| + } |
| + if reg.lastOwner() == "" || reg.lastOwner() != p.OwnerHandle { |
| + t.Fatalf("owner: %q vs %q", reg.lastOwner(), p.OwnerHandle) |
| + } |
| + if c, err := f.st.SavedContact(ctx, f.acct.ID, sc.ID); err != nil || c != nil { |
| + t.Fatalf("removed contact came back: %+v %v", c, err) |
| + } |
| +} |
| + |
| +// stripContactID turns a purchase into one made before saved contacts. |
| +func stripContactID(t *testing.T, f *purchaseFixture, id string) { |
| + 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) |
| + } |
| + delete(details, "ContactID") |
| + delete(details, "ContactVersion") |
| + 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 TestLegacyPurchaseFinishesFromItsOwnContact(t *testing.T) { |
| + t.Run("awaiting_payment", func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + // The old single contact row and its handle are never used again. |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), "contact-legacy"); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: f.acct.ID, App: "kass", Domain: "shop.com", Currency: "usd", Amount: 1500, |
| + State: PurchaseAwaitingPayment, CheckoutExpires: time.Now().Add(time.Hour), purchaseDetails: purchaseDetails{Principal: "buyer@example.test", Contact: purchaseContact()}} |
| + if err := f.st.CreateDomainPurchase(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := f.advance(t, p.ID) |
| + if got.OwnerHandle == "" || got.OwnerHandle == "contact-legacy" || got.CheckoutSession == "" { |
| + t.Fatalf("checkout: %+v", got) |
| + } |
| + for _, call := range f.reg.Calls { |
| + if strings.HasPrefix(call, "contact:") && call != "contact:" { |
| + t.Fatalf("legacy handle sent to the registrar: %v", f.reg.Calls) |
| + } |
| + } |
| + f.authorise(t, got) |
| + done := f.until(t, p.ID, PurchaseDone) |
| + if f.registrant(t, done.Domain) != purchaseContact() { |
| + t.Fatal("registrant") |
| + } |
| + if c, handle, err := f.st.DomainContact(f.acct.ID); err != nil || handle != "contact-legacy" || c != purchaseContact() { |
| + t.Fatalf("legacy contact row rewritten: %+v %q %v", c, handle, err) |
| + } |
| + if contacts, err := f.st.SavedContacts(context.Background(), f.acct.ID); err != nil || len(contacts) != 0 { |
| + t.Fatalf("legacy purchase wrote saved contacts: %+v %v", contacts, err) |
| + } |
| + }) |
| + t.Run("registering", func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + f.until(t, p.ID, PurchaseRegistering) |
| + stripContactID(t, f, p.ID) |
| + f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + ageRegisteringPurchase(t, f, p.ID, 11*time.Minute) |
| + done := f.until(t, p.ID, PurchaseDone) |
| + if done.ContactID != "" || f.registrant(t, done.Domain) != purchaseContact() { |
| + t.Fatalf("legacy registering: %+v", done) |
| + } |
| + }) |
| +} |
| + |
| +func TestRegisteredRetryBackfillsRegistrant(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseZoneReady) |
| + // A crash after the insert and before the state update, by a build that |
| + // wrote no registrant. |
| + if err := f.st.AddDomainRegistration(DomainRegistration{Domain: p.Domain, AccountID: f.acct.ID, RegistrarID: "registration-" + p.Domain, ZoneID: p.ZoneID, Expires: time.Now().AddDate(1, 0, 0), AutoRenew: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseRegistered) |
| + if got := f.registrant(t, p.Domain); got != purchaseContact() { |
| + t.Fatalf("registrant: %+v", got) |
| + } |
| +} |
| + |
| +func TestPurchaseOtherAccountsContactRefused(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + ctx := context.Background() |
| + other, err := f.st.AddSavedContact(ctx, f.acct.ID+1000, purchaseContact(), time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := purchaseContact() |
| + for name, sel := range map[string]purchaseContactSelection{ |
| + "other account": {ID: other.ID}, |
| + "missing": {ID: "dc_000000000000"}, |
| + "both": {ID: other.ID, New: &c}, |
| + "neither": {}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + _, _, ref := startQuotedSelection(f.srv, ctx, f.acct, "kass", "shop.com", sel, "IE", "buyer") |
| + if ref == nil || ref.Status != http.StatusUnprocessableEntity || ref.Msg != domainBuyCopy["contactError"] { |
| + t.Fatalf("refusal: %+v", ref) |
| + } |
| + var n int |
| + if err := f.st.db.QueryRow(`SELECT count(*) FROM domain_purchases`).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("purchases=%d %v", n, err) |
| + } |
| + if f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 { |
| + t.Fatal("refusal made provider writes") |
| + } |
| + }) |
| + } |
| + if contacts, err := f.st.SavedContacts(ctx, f.acct.ID); err != nil || len(contacts) != 0 { |
| + t.Fatalf("refused starts saved contacts: %+v %v", contacts, err) |
| + } |
| +} |
| + |
| +func TestStartWithoutAppStillNeedsPaidPlanAndCap(t *testing.T) { |
| + t.Run("plan", func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, ref := startQuotedSelection(f.srv, context.Background(), f.acct, "", "shop.com", purchaseContactSelection{New: newContact()}, "IE", "buyer") |
| + if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("free plan bought a domain with no app") |
| + } |
| + }) |
| + t.Run("cap", func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.srv.cfg.DomainCatalog.DailyCap = 1 |
| + if err := f.st.CreateDomainPurchase(DomainPurchase{AccountID: f.acct.ID, Domain: "earlier.com", State: PurchaseExpired}); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, ref := startQuotedSelection(f.srv, context.Background(), f.acct, "", "shop.com", purchaseContactSelection{New: newContact()}, "IE", "buyer") |
| + if ref == nil || ref.Status != http.StatusTooManyRequests || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatalf("cap bypassed with no app: %+v", ref) |
| + } |
| + }) |
| + t.Run("unknown app", func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + _, _, ref := startQuotedSelection(f.srv, context.Background(), f.acct, "nope", "shop.com", purchaseContactSelection{New: newContact()}, "IE", "buyer") |
| + if ref == nil || ref.Status != http.StatusNotFound { |
| + t.Fatalf("unknown app: %+v", ref) |
| + } |
| + }) |
| +} |
| + |
| +func TestStartRefusedOnceAccountRetiring(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + hooked := false |
| + previous := domainPurchaseBeforeInsert |
| + domainPurchaseBeforeInsert = func(ctx context.Context, s *Server, acct *Account) { |
| + hooked = true |
| + // Deletion marks the account under the same billing hold, so by |
| + // the time a start holds it the mark is either there or not yet. |
| + if err := s.store.BeginBillingRetirement(acct.ID, "owner@example.com", time.Now()); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + t.Cleanup(func() { domainPurchaseBeforeInsert = previous }) |
| + _, _, ref := startQuotedSelection(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContactSelection{New: newContact()}, "IE", "buyer") |
| + if !hooked || ref == nil || *ref != *domainBuyUnavailable() { |
| + t.Fatalf("hooked=%v refusal=%+v", hooked, ref) |
| + } |
| + var n int |
| + if err := f.st.db.QueryRow(`SELECT count(*) FROM domain_purchases`).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("purchases=%d %v", n, err) |
| + } |
| + if f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 { |
| + t.Fatal("refused start made provider writes") |
| + } |
| + if contacts, err := f.st.SavedContacts(context.Background(), f.acct.ID); err != nil || len(contacts) != 0 { |
| + t.Fatalf("refused start saved a contact: %+v %v", contacts, err) |
| + } |
| +} |
| + |
| +func TestStaleAppLessSnapshotHasNoEffects(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + ctx := context.Background() |
| + p := f.startWith(t, "", purchaseContactSelection{New: newContact()}) |
| + f.authorise(t, p) |
| + for _, state := range []PurchaseState{PurchaseAuthorised, PurchaseCaptured} { |
| + t.Run(string(state), func(t *testing.T) { |
| + p := f.until(t, p.ID, state) |
| + stale := *p |
| + if err := f.srv.movePurchase(ctx, p, p.State, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + zoneCalls, regCalls, sent := len(f.zone.Calls), len(f.reg.Calls), len(f.fake.Sent) |
| + err := f.srv.advancePurchaseStep(ctx, f.acct, &stale) |
| + if !errors.Is(err, ErrPurchaseStateMoved) { |
| + t.Fatalf("stale step: %v", err) |
| + } |
| + if len(f.zone.Calls) != zoneCalls || len(f.reg.Calls) != regCalls || len(f.fake.Sent) != sent { |
| + t.Fatalf("stale snapshot had effects: zone %v reg %v", f.zone.Calls[zoneCalls:], f.reg.Calls[regCalls:]) |
| + } |
| + if got := f.read(t, p.ID); got.State != state || got.Revision != p.Revision { |
| + t.Fatalf("stale snapshot moved the purchase: %+v", got) |
| + } |
| + }) |
| + } |
| + f.until(t, p.ID, PurchaseDone) |
| +} |
| + |
| +// addContact saves c for the fixture's account, the contact a door with no |
| +// contact in its request buys with and a quote takes its country from. |
| +func (f *purchaseFixture) addContact(c registrar.Contact) error { |
| + _, err := f.st.AddSavedContact(context.Background(), f.acct.ID, c, time.Now()) |
| + return err |
| +} |
diff --git a/internal/console/domainbuy_round1_test.go b/internal/console/domainbuy_round1_test.go| index 7d959b759..6329e70bb 100644 |
| --- a/internal/console/domainbuy_round1_test.go |
| +++ b/internal/console/domainbuy_round1_test.go |
| @@ -17,7 +17,7 @@ import ( |
| func TestPurchaseCheckUsesSavedCountry(t *testing.T) { |
| f := newPurchaseFixture(t) |
| firstPurchaseAccount(t, f) |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| tok := buyToken(t, f) |
| @@ -65,7 +65,7 @@ func TestPurchaseConfirmedPriceMismatch(t *testing.T) { |
| f := newPurchaseFixture(t) |
| firstPurchaseAccount(t, f) |
| f.reg.BalanceMoney.Minor = 0 // A changed price must refuse before balance alerts or billing. |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass",`+fields+`}`) |
| @@ -102,7 +102,7 @@ func assertNoPurchaseEffects(t *testing.T, f *purchaseFixture) { |
| func TestBrowserBuyConfirmedPrice(t *testing.T) { |
| f := newPurchaseFixture(t) |
| firstPurchaseAccount(t, f) |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| c := newBrowser(t) |
| @@ -228,7 +228,7 @@ func (r currencyChangeRegistrar) Check(ctx context.Context, name string) (regist |
| func TestPurchaseConfirmsCurrencyUnderBillingHold(t *testing.T) { |
| f := newPurchaseFixture(t) |
| firstPurchaseAccount(t, f) |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| f.srv.cfg.Registrar = currencyChangeRegistrar{f.reg, func() { |
| @@ -265,7 +265,7 @@ func TestPurchaseCheckDefaultAndFixedCurrency(t *testing.T) { |
| if err := f.st.SetBillingCustomer(f.acct.ID, "cus_fixed", time.Now(), "usd"); err != nil { |
| t.Fatal(err) |
| } |
| - if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + if err := f.addContact(purchaseContact()); err != nil { |
| t.Fatal(err) |
| } |
| } |
diff --git a/internal/console/domainbuy_round2_test.go b/internal/console/domainbuy_round2_test.go| index 4cb21af52..3d6fbfb05 100644 |
| --- a/internal/console/domainbuy_round2_test.go |
| +++ b/internal/console/domainbuy_round2_test.go |
| @@ -32,7 +32,7 @@ func TestPurchaseCheckCountry(t *testing.T) { |
| if tc.saved != "" { |
| c := purchaseContact() |
| c.Country = tc.saved |
| - if err := f.st.SetDomainContact(f.acct.ID, c, ""); err != nil { |
| + if err := f.addContact(c); err != nil { |
| t.Fatal(err) |
| } |
| } |
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go| index 54f82c7a4..9bc01868b 100644 |
| --- a/internal/console/domainbuy_test.go |
| +++ b/internal/console/domainbuy_test.go |
| @@ -14,7 +14,6 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| - "github.com/carlosframework/platform/internal/billing/billingtest" |
| "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/registrar" |
| @@ -485,39 +484,6 @@ func TestPurchaseSameStateCASRejectsStaleRetry(t *testing.T) { |
| } |
| } |
| -func TestPurchaseClaimGateBlocksZoneEffects(t *testing.T) { |
| - cx := newClaimCase(t) |
| - setupClaimPurchase(t, cx) |
| - p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := cx.srv.movePurchase(context.Background(), p, PurchaseAuthorised, nil); err != nil { |
| - t.Fatal(err) |
| - } |
| - zone := cx.srv.cfg.ZoneHost.(*zonehosttest.Fake) |
| - restore := cx.foreign(t, claimAppRef{Account: "bab", App: "kass"}) |
| - defer restore() |
| - if err := cx.srv.advancePurchase(context.Background(), p.ID); err == nil { |
| - t.Fatal("foreign operation allowed purchase") |
| - } |
| - if len(zone.Calls) != 0 { |
| - t.Fatalf("foreign operation reached zone host: %v", zone.Calls) |
| - } |
| -} |
| - |
| -func TestPurchaseClaimWorkerWritesThroughPermit(t *testing.T) { |
| - cx := newClaimCase(t) |
| - setupClaimPurchase(t, cx) |
| - if err := cx.srv.domainPurchasePass(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| - p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| - if err != nil || p.State != PurchaseExpired { |
| - t.Fatalf("pass: %+v %v", p, err) |
| - } |
| -} |
| - |
| func TestPurchaseExistingFlowContinuesWithBuyDoorDisabled(t *testing.T) { |
| f := newPurchaseFixture(t) |
| p := f.start(t) |
| @@ -647,51 +613,6 @@ func TestPurchaseAttachRefusalAlertsAfterTen(t *testing.T) { |
| } |
| } |
| -func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) { |
| - cx := newClaimCase(t) |
| - cx.claimedRoute(t) |
| - cx.settleRegistrations(t, "bab", "titogo") |
| - fake := enableBilling(t, cx.srv) |
| - acct, err := cx.st.AccountByID(OpsAccountID) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := cx.st.SetBillingCustomer(acct.ID, "cus_1", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - bf := &billingFixture{consoleFixture: cx.consoleFixture, fake: fake, acct: acct} |
| - bf.put(bf.personalSub("sub_1", "active", nil)) |
| - if err := bf.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil { |
| - t.Fatal(err) |
| - } |
| - reg := registrartest.New() |
| - reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100000} |
| - reg.Available["shop.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| - zone := zonehosttest.New("ns1.carloku.test", "ns2.carloku.test") |
| - cx.srv.cfg.Registrar = reg |
| - cx.srv.cfg.ZoneHost = zone |
| - cx.srv.cfg.EdgeIPs = []string{"192.0.2.10"} |
| - cx.srv.cfg.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| - cx.srv.billing.ready.Store(true) |
| - f := &purchaseFixture{billingFixture: bf, reg: reg, zone: zone} |
| - p, _, ref := startQuotedPurchase(f.srv, context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| - if ref != nil || p == nil { |
| - t.Fatalf("start: %+v", ref) |
| - } |
| - resumed, checkout, duplicate := startQuotedPurchase(f.srv, 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) |
| - for _, host := range []string{p.Domain, "www." + p.Domain} { |
| - claim, err := domains.GetClaim(context.Background(), cx.rel, host) |
| - if err != nil || claim.Account != acct.Sqid || claim.App != "titogo" { |
| - t.Fatalf("claim: %+v %v", claim, err) |
| - } |
| - } |
| -} |
| - |
| func TestPurchaseCheckoutUsesQuoteAndPurchaseReturnPage(t *testing.T) { |
| f := newPurchaseFixture(t) |
| p := f.start(t) |
| @@ -721,10 +642,14 @@ func TestPurchaseResumesContactSnapshotBeforeCheckout(t *testing.T) { |
| if err := f.st.CreateDomainPurchase(p); err != nil { |
| t.Fatal(err) |
| } |
| - f.advance(t, p.ID) |
| - contact, stored, err := f.st.DomainContact(f.acct.ID) |
| - if err != nil || stored != handle || contact != purchaseContact() { |
| - t.Fatalf("contact snapshot was not saved: handle=%q error=%v", stored, err) |
| + calls := purchaseCalls(f.reg.Calls, "contact:") |
| + p2 := f.advance(t, p.ID) |
| + if p2.OwnerHandle != handle || p2.CheckoutSession == "" || purchaseCalls(f.reg.Calls, "contact:") != calls { |
| + t.Fatalf("resumed purchase: handle=%q session=%q calls=%v", p2.OwnerHandle, p2.CheckoutSession, f.reg.Calls) |
| + } |
| + // Legacy purchases no longer write the account's single contact row. |
| + if contact, stored, err := f.st.DomainContact(f.acct.ID); err != nil || stored != "" || contact != (registrar.Contact{}) { |
| + t.Fatalf("legacy contact row written: %+v %q %v", contact, stored, err) |
| } |
| } |
| @@ -917,92 +842,14 @@ func TestLostCheckoutCreateAdoptsListedSession(t *testing.T) { |
| f.until(t, p.ID, PurchaseDone) |
| } |
| -type purchaseCountingStore struct { |
| - *claimCountingStore |
| - operations int |
| - before func(context.Context) error |
| -} |
| - |
| -func (s *purchaseCountingStore) RunAppMutation(ctx context.Context, account, app, action string, fn func(context.Context) error) error { |
| - s.operations++ |
| - return s.Store.(interface { |
| - RunAppMutation(context.Context, string, string, string, func(context.Context) error) error |
| - }).RunAppMutation(ctx, account, app, action, func(ctx context.Context) error { |
| - if s.before != nil { |
| - if err := s.before(ctx); err != nil { |
| - return err |
| - } |
| - } |
| - return fn(ctx) |
| - }) |
| -} |
| - |
| -func TestPollStepsTakeNoAppOperation(t *testing.T) { |
| - cx := newClaimCase(t) |
| - setupClaimPurchase(t, cx) |
| - // No transition on this pass: a live, open payment session is just a poll. |
| - fake := cx.srv.billing.cfg.Provider |
| - prepared, err := fake.PreparePaymentCheckout(billing.PaymentCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", Currency: "usd", Amount: 1500, Description: "shop.com", Reference: "dp_claim_purchase", SuccessURL: "https://example.test/ok", CancelURL: "https://example.test/back", ExpiresAt: time.Now().Add(time.Hour), Key: "dp_claim_purchase"}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - result, err := fake.Send(context.Background(), prepared) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := cx.srv.movePurchase(context.Background(), p, p.State, func(p *DomainPurchase) { |
| - p.CheckoutSession = result.Payment.SessionID |
| - p.CheckoutExpires = time.Now().Add(time.Hour) |
| - }); err != nil { |
| - t.Fatal(err) |
| - } |
| - counter := &purchaseCountingStore{claimCountingStore: &claimCountingStore{Store: cx.srv.cfg.Releases}} |
| - cx.srv.cfg.Releases = counter |
| - billingFake := fake.(*billingtest.Fake) |
| - reads := billingFake.CallsBy["PaymentCheckout"] |
| - err = cx.srv.domainPurchasePass(context.Background()) |
| - if billingFake.CallsBy["PaymentCheckout"] != reads+1 { |
| - t.Fatal("open poll must make exactly one Stripe session read") |
| - } |
| - if err != nil || counter.operations != 0 || counter.calls.Load() != 0 { |
| - t.Fatalf("pass=%v operations=%d store calls=%d", err, counter.operations, counter.calls.Load()) |
| - } |
| -} |
| - |
| -func TestPurchaseRereadsJournalInsideOperation(t *testing.T) { |
| - cx := newClaimCase(t) |
| - setupClaimPurchase(t, cx) |
| - p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := cx.srv.movePurchase(context.Background(), p, PurchaseAuthorised, nil); err != nil { |
| - t.Fatal(err) |
| - } |
| - counter := &purchaseCountingStore{claimCountingStore: &claimCountingStore{Store: cx.srv.cfg.Releases}} |
| - counter.before = func(ctx context.Context) error { |
| - return cx.srv.movePurchase(ctx, p, PurchaseFailed, nil) |
| - } |
| - cx.srv.cfg.Releases = counter |
| - if err := cx.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| - t.Fatal(err) |
| - } |
| - zone := cx.srv.cfg.ZoneHost.(*zonehosttest.Fake) |
| - if len(zone.Calls) != 0 { |
| - t.Fatalf("stale worker made zone effects: %v", zone.Calls) |
| - } |
| - fresh, err := cx.st.DomainPurchase(p.ID) |
| - if err != nil || fresh.State != PurchaseFailed { |
| - t.Fatalf("purchase=%+v error=%v", fresh, err) |
| - } |
| +func startQuotedPurchase(s *Server, ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| + return startQuotedSelection(s, ctx, acct, app, name, purchaseContactSelection{New: &c}, c.Country, principal) |
| } |
| -func startQuotedPurchase(s *Server, ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| - currency, _ := s.billing.cfg.Book.ChooseCurrency("", c.Country) |
| +// startQuotedSelection starts a purchase at the quote the account would be |
| +// shown for country. |
| +func startQuotedSelection(s *Server, ctx context.Context, acct *Account, app, name string, sel purchaseContactSelection, country, principal string) (*DomainPurchase, string, *doorRefusal) { |
| + currency, _ := s.billing.cfg.Book.ChooseCurrency("", country) |
| if b, _ := s.store.BillingAccount(acct.ID); b != nil && b.Currency != "" { |
| currency = b.Currency |
| } |
| @@ -1010,6 +857,6 @@ func startQuotedPurchase(s *Server, ctx context.Context, acct *Account, app, nam |
| if own, _ := s.ownLiveDomainPurchase(ctx, acct.ID, name); own != nil { |
| q.Currency, q.Price = own.Currency, own.Amount |
| } |
| - p, link, _, ref := s.startDomainPurchase(ctx, acct, app, name, c, principal, q) |
| + p, link, _, ref := s.startDomainPurchase(ctx, acct, app, name, sel, principal, q) |
| return p, link, ref |
| } |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index b2106f8b7..57d6b8ac0 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -50,7 +50,7 @@ var jobPassFuncs = map[string][]string{ |
| "StartPlanLimitsPass": {"planLimitsPass"}, |
| "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners", |
| "convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"}, |
| - "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| + "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice", "purchaseManagedSet", "capturedPurchase", "finishPurchaseUnpointed"}, |
| "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass", "billingSnapshotPass"}, |
| "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index 5c9de5fda..045b2a1df 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -214,7 +214,8 @@ var routeDecls = []routeDecl{ |
| // Plans 6b: an owner's way to the provider's locked portal for cards |
| // and invoices (billingportal.go). 404 with billing off. |
| {Pattern: "POST /a/{sqid}/billing/portal", Handler: (*Server).handleBillingPortal}, |
| - {Pattern: "POST /a/{sqid}/billing/card", Handler: (*Server).handleBillingCard}, |
| + // The card setup is for buying domains, so it goes where buying goes. |
| + {Pattern: "POST /a/{sqid}/billing/card", Gate: gateNoHostClaim, Handler: (*Server).handleBillingCard}, |
| // The billing page (billingpage.go): member-readable, its forms the |
| // owner's. 404 with billing off. |
| {Pattern: "GET /a/{sqid}/billing", Handler: (*Server).handleBilling}, |
| @@ -321,12 +322,13 @@ var routeDecls = []routeDecl{ |
| // (controlplane.go). |
| {Pattern: "POST /a/{sqid}/apps/{app}/control-plane/clear", Handler: (*Server).handleAppControlPlaneClear}, |
| {Pattern: "POST /a/{sqid}/apps/{app}/control-plane/set", Handler: (*Server).handleAppControlPlaneSet}, |
| - // Domain purchases: owner sessions, with CSRF on both form posts. |
| - {Pattern: "GET /a/{sqid}/apps/{app}/domains/buy", Handler: (*Server).handleAppDomainBuyForm}, |
| - {Pattern: "POST /a/{sqid}/apps/{app}/domains/check", Handler: (*Server).handleAppDomainBuyCheck}, |
| - {Pattern: "POST /a/{sqid}/apps/{app}/domains/buy", Handler: (*Server).handleAppDomainBuy}, |
| - {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}", Handler: (*Server).handleAppDomainPurchase}, |
| - {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", Handler: (*Server).handleAppDomainPurchaseStatus}, |
| + // Domain purchases: owner sessions, with CSRF on both form posts. Not |
| + // registered on a host-claim console, where buying is off. |
| + {Pattern: "GET /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyForm}, |
| + {Pattern: "POST /a/{sqid}/apps/{app}/domains/check", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyCheck}, |
| + {Pattern: "POST /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuy}, |
| + {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchase}, |
| + {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchaseStatus}, |
| // Custom domain attach/detach (appdomains.go, #82): owner-only, no |
| // passkey step-up (spec §6) — detach's guard is the typed-host confirm. |
| {Pattern: "POST /a/{sqid}/apps/{app}/domains/attach", Handler: (*Server).handleAppDomainAttach}, |
| @@ -828,9 +830,9 @@ var routeDecls = []routeDecl{ |
| // a team credential (no team set here) cannot reach it either. |
| {Pattern: "PUT /api/cli/apps/{account}/{app}/domains/{host}/placements", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPlacementsPut}, |
| {Pattern: "POST /api/cli/apps/{account}/{app}/domains", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Publish, svcrole.Instance), Target: scopeDomainBody, Handler: (*Server).handleAPIDomainAttach}, |
| - {Pattern: "POST /api/cli/accounts/{account}/domains/check", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainCheck}, |
| - {Pattern: "POST /api/cli/accounts/{account}/domains/purchases", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPurchase}, |
| - {Pattern: "GET /api/cli/accounts/{account}/domains/purchases/{id}", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPurchaseStatus}, |
| + {Pattern: "POST /api/cli/accounts/{account}/domains/check", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainCheck}, |
| + {Pattern: "POST /api/cli/accounts/{account}/domains/purchases", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPurchase}, |
| + {Pattern: "GET /api/cli/accounts/{account}/domains/purchases/{id}", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPurchaseStatus}, |
| {Pattern: "DELETE /api/cli/apps/{account}/{app}/domains/{host}", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Publish, svcrole.Instance), Target: scopeDomainHost, Handler: (*Server).handleAPIDomainDetach}, |
| // The prefix-map publish (path-based routing): replace the WHOLE map of |
| // leading path segments a claimed hostname splits its traffic by. The |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 7fd82b1bd..3c21faf02 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -23,6 +23,7 @@ import ( |
| "os" |
| "path/filepath" |
| "reflect" |
| + "slices" |
| "sort" |
| "strconv" |
| "strings" |
| @@ -438,6 +439,14 @@ var demoOperatorDoors = []string{ |
| "POST /api/cli/system/demos/reports/{id}/resolve", |
| } |
| +// domainBuyDoors are closed doors (in closedDoors) that a host-claim console |
| +// does not register: buying domains is off there. |
| +var domainBuyDoors = []string{ |
| + "GET /api/cli/accounts/{account}/domains/purchases/{id}", |
| + "POST /api/cli/accounts/{account}/domains/check", |
| + "POST /api/cli/accounts/{account}/domains/purchases", |
| +} |
| + |
| // TestEveryCLIDoorNamesItsRoles is the default-deny guarantee for the |
| // /api/cli/ half. A door declared plain would not appear in cliRoles at |
| // all (and the scan refuses it); a door declared with an accidental empty Set |
| @@ -505,6 +514,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| {regionHADoors, "gateRegionHA"}, |
| {movesDoors, "gateMoves"}, |
| {demoOperatorDoors, "gateNoHostClaim"}, |
| + {domainBuyDoors, "gateNoHostClaim"}, |
| } { |
| for _, pattern := range c.doors { |
| g, ok := cliGate[pattern] |
| @@ -555,6 +565,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| roles := tc.hostClaim && tc.regionHA |
| if tc.hostClaim { |
| wantClosed = append(wantClosed, hostClaimDoors...) |
| + wantClosed = slices.DeleteFunc(wantClosed, func(d string) bool { return slices.Contains(domainBuyDoors, d) }) |
| } |
| if roles { |
| wantClosed = append(wantClosed, regionHADoors...) |