console: neutral buy doors, own capability field, check limiter
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
12 files changed,
+505
−65
internal/console/apidomainbuy.go+13 −4internal/console/apidomainbuy_test.go+8 −14internal/console/appdomainbuy.go+5 −1internal/console/domainbuy.go+11 −11internal/console/domainbuy_copy.go+24 −22internal/console/domainbuy_fix_test.go+325 −0internal/console/domainbuy_limit.go+71 −0internal/console/domainstate.go+2 −10internal/console/server.go+2 −0internal/console/templates/domain_buy.html+1 −1internal/registrar/registrar.go+12 −2internal/registrar/registrar_test.go+31 −0
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go| index 3073a27ad..a0defe85f 100644 |
| --- a/internal/console/apidomainbuy.go |
| +++ b/internal/console/apidomainbuy.go |
| @@ -38,9 +38,15 @@ func (s *Server) domainBuyAPIGate(w http.ResponseWriter, r *http.Request) (strin |
| // Check cannot name an app, so any existing claim is unavailable here. The |
| // engine repeats its own checks before creating a purchase; this read reserves nothing. |
| func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| + if ref := s.customDomainRefusal(acct, name); ref != nil { |
| + return domainreg.Quote{}, ref |
| + } |
| name, err := domainreg.Normalize(name) |
| if err != nil { |
| - return domainreg.Quote{}, &doorRefusal{422, domainBuyCopy["nameError"]} |
| + return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| + } |
| + if !s.domainChecks.allow(acct.ID) { |
| + return domainreg.Quote{}, &doorRefusal{429, domainBuyCopy["rate"]} |
| } |
| for _, host := range []string{name, "www." + name} { |
| if s.domainHostDenied(host, acct.Sqid) { |
| @@ -60,8 +66,7 @@ func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name string) |
| if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil { |
| return domainreg.Quote{}, ref |
| } |
| - q, ref := s.quoteDomain(ctx, acct, name) |
| - return q, domainBuyDoorRefusal(ref) |
| + return s.quoteDomain(ctx, acct, name) |
| } |
| func (s *Server) liveDomainPurchaseRefusal(ctx context.Context, name string) *doorRefusal { |
| @@ -125,6 +130,10 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) |
| if !readJSONStrictLimit(w, r, &in, 16<<10) { |
| return |
| } |
| + if ref := s.customDomainRefusal(acct, in.Name); ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| c, ref := s.domainBuyContact(acct, in.Contact) |
| if ref != nil { |
| if ref.Status == 422 { |
| @@ -138,7 +147,7 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) |
| defer cancel() |
| p, checkout, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr) |
| if ref != nil { |
| - writeDoorRefusalJSON(w, r, domainBuyDoorRefusal(ref)) |
| + writeDoorRefusalJSON(w, r, ref) |
| return |
| } |
| writeJSON(w, 200, map[string]any{"id": p.ID, "checkout_url": checkout, "state": p.State}) |
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go| index 6576c4839..47e307af1 100644 |
| --- a/internal/console/apidomainbuy_test.go |
| +++ b/internal/console/apidomainbuy_test.go |
| @@ -74,13 +74,13 @@ func TestBuyDoorAbsentWhenNotConfigured(t *testing.T) { |
| t.Fatalf("%s %s: %d %s", missing, r.path, status, b) |
| } |
| } |
| - if _, ok := f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Features["buy"]; ok { |
| + if f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Buy { |
| t.Fatalf("buy advertised without %s", missing) |
| } |
| } |
| f.srv.cfg, f.srv.billing = original, billingRuntime |
| f.srv.billing.ready.Store(true) |
| - if f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Features["buy"] != "true" { |
| + if !f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Buy { |
| t.Fatal("buy not advertised when ready") |
| } |
| } |
| @@ -174,15 +174,12 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) { |
| csrf := sessionToken(t, f.consoleFixture, c) |
| base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass/domains" |
| status, _, body := postForm(t, c, base+"/check", url.Values{"csrf": {csrf}, "name": {"shop.com"}}) |
| - if status != 200 || !strings.Contains(body, "$15") || !strings.Contains(body, "PhoneCountryCode") { |
| - t.Fatalf("quote %d %s", status, body) |
| + if status != 200 || !strings.Contains(body, "$15") || strings.Contains(body, "$15 usd") || !strings.Contains(body, "PhoneCountryCode") { |
| + t.Fatalf("quote status=%d, has price=%v, duplicate currency=%v, has phone=%v", status, strings.Contains(body, "$15"), strings.Contains(body, "$15 usd"), strings.Contains(body, "PhoneCountryCode")) |
| } |
| values := url.Values{"csrf": {csrf}, "name": {"shop.com"}} |
| - raw, _ := json.Marshal(purchaseContact()) |
| - var fields map[string]string |
| - _ = json.Unmarshal(raw, &fields) |
| - for k, v := range fields { |
| - values.Set(k, v) |
| + for _, field := range buyContactFields(purchaseContact()) { |
| + values.Set(field.Name, field.Value) |
| } |
| status, loc, body := postForm(t, c, base+"/buy", values) |
| if status != 303 || !strings.HasPrefix(loc, "https://") { |
| @@ -241,12 +238,9 @@ func setupClaimBuyDoors(t *testing.T, cx *claimCase) { |
| 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 { |
| - raw, _ := json.Marshal(purchaseContact()) |
| - var fields map[string]string |
| - _ = json.Unmarshal(raw, &fields) |
| kv := []string{"name", "shop.com"} |
| - for k, v := range fields { |
| - kv = append(kv, k, v) |
| + for _, field := range buyContactFields(purchaseContact()) { |
| + kv = append(kv, field.Name, field.Value) |
| } |
| return cx.formReply(t, "/a/bab/apps/kass/domains/buy", kv...).Status |
| } |
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go| index a74f6ed11..b8e1c8fb3 100644 |
| --- a/internal/console/appdomainbuy.go |
| +++ b/internal/console/appdomainbuy.go |
| @@ -102,6 +102,10 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if ref := s.customDomainRefusal(acct, r.FormValue("name")); ref != nil { |
| + s.renderDoorRefusal(w, r, ref) |
| + return |
| + } |
| c := registrar.Contact{FirstName: r.FormValue("FirstName"), LastName: r.FormValue("LastName"), Company: r.FormValue("Company"), |
| Email: r.FormValue("Email"), PhoneCountryCode: r.FormValue("PhoneCountryCode"), Phone: r.FormValue("Phone"), Street: r.FormValue("Street"), HouseNumber: r.FormValue("HouseNumber"), |
| City: r.FormValue("City"), State: r.FormValue("State"), PostalCode: r.FormValue("PostalCode"), Country: r.FormValue("Country")} |
| @@ -113,7 +117,7 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) { |
| defer cancel() |
| _, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr) |
| if ref != nil { |
| - s.renderDoorRefusal(w, r, domainBuyDoorRefusal(ref)) |
| + s.renderDoorRefusal(w, r, ref) |
| return |
| } |
| http.Redirect(w, r, checkout, http.StatusSeeOther) |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index a638407ed..a24c41e63 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -40,7 +40,7 @@ func (s *Server) quoteDomain(ctx context.Context, acct *Account, name string) (d |
| } |
| name, err := domainreg.Normalize(name) |
| if err != nil { |
| - return domainreg.Quote{}, &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| } |
| b, err := s.store.BillingAccount(acct.ID) |
| if err != nil || b == nil || b.Currency == "" || b.Customer == "" { |
| @@ -48,11 +48,11 @@ func (s *Server) quoteDomain(ctx context.Context, acct *Account, name string) (d |
| } |
| a, err := s.cfg.Registrar.Check(ctx, name) |
| if err != nil { |
| - return domainreg.Quote{}, domainBuyUnavailable() |
| + return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| } |
| q, err := s.cfg.DomainCatalog.Quote(name, b.Currency, a) |
| if err != nil { |
| - return domainreg.Quote{}, &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| } |
| return q, nil |
| } |
| @@ -61,13 +61,13 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| if !s.domainBuyReady() { |
| return nil, "", &doorRefusal{Status: http.StatusNotFound} |
| } |
| - name, err := domainreg.Normalize(name) |
| - if err != nil { |
| - return nil, "", &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| - } |
| if ref := s.customDomainRefusal(acct, name); ref != nil { |
| return nil, "", ref |
| } |
| + name, err := domainreg.Normalize(name) |
| + if err != nil { |
| + return nil, "", domainBuyErrorRefusal(err) |
| + } |
| exists, err := s.store.HasAppIn(acct.ID, app) |
| if err != nil { |
| return nil, "", domainBuyUnavailable() |
| @@ -76,7 +76,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return nil, "", &doorRefusal{Status: http.StatusNotFound} |
| } |
| if err := c.Validate(); err != nil { |
| - return nil, "", &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + return nil, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| } |
| // Keep concurrent starts on this account inside the same daily-cap check. |
| defer s.planLock(acct)() |
| @@ -93,7 +93,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| } |
| if ref := s.heldElsewhere(ctx, host, acct.Sqid, app); ref != nil { |
| if ref.Status == http.StatusConflict { |
| - s.purchaseAlert(ctx, acct, name, "", "claim held elsewhere") |
| + log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name) |
| } |
| return nil, "", ref |
| } |
| @@ -102,7 +102,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return nil, "", domainBuyUnavailable() |
| } |
| if err == nil && (claim.Account != acct.Sqid || claim.App != app) { |
| - s.purchaseAlert(ctx, acct, name, "", "claim held elsewhere") |
| + log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name) |
| return nil, "", claimRefusal(host, domains.ErrHostUnavailable) |
| } |
| } |
| @@ -117,7 +117,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| } |
| balance, err := s.cfg.Registrar.Balance(ctx) |
| if err != nil { |
| - return nil, "", domainBuyUnavailable() |
| + return nil, "", domainBuyErrorRefusal(err) |
| } |
| if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor { |
| s.purchaseAlert(ctx, acct, name, "", "registrar balance") |
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go| index cc33046fc..da1241a43 100644 |
| --- a/internal/console/domainbuy_copy.go |
| +++ b/internal/console/domainbuy_copy.go |
| @@ -1,6 +1,14 @@ |
| package console |
| -import "github.com/carlosframework/platform/internal/domainreg" |
| +import ( |
| + "errors" |
| + "log" |
| + "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| +) |
| // Plan 1 drafts, replaced by the Luna pass (Task 11). |
| var domainBuyCopy = map[string]string{ |
| @@ -23,28 +31,22 @@ var domainBuyCopy = map[string]string{ |
| "City": "City", "State": "State or region (optional)", "PostalCode": "Postal code", "Country": "Country (two uppercase letters)", |
| } |
| -// Keep provider validation vocabulary out of the doors' customer copy. |
| -func domainBuyDoorRefusal(ref *doorRefusal) *doorRefusal { |
| - if ref == nil { |
| - return nil |
| - } |
| - key := "" |
| - switch ref.Msg { |
| - case domainreg.ErrNotRegistrable.Error(): |
| - key = "nameError" |
| - case domainreg.ErrTLDNotOffered.Error(): |
| - key = "notOffered" |
| - case domainreg.ErrPremium.Error(): |
| - key = "premium" |
| - case domainreg.ErrNotAvailable.Error(): |
| - key = "taken" |
| - case domainreg.ErrCostAboveCeiling.Error(): |
| - key = "unavailable" |
| - } |
| - if key != "" { |
| - return &doorRefusal{ref.Status, domainBuyCopy[key]} |
| +func domainBuyErrorRefusal(err error) *doorRefusal { |
| + switch { |
| + case errors.Is(err, domainreg.ErrNotAvailable), errors.Is(err, registrar.ErrUnavailable): |
| + return claimRefusal("", domains.ErrHostUnavailable) |
| + case errors.Is(err, domainreg.ErrNotRegistrable): |
| + return &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["nameError"]} |
| + case errors.Is(err, domainreg.ErrTLDNotOffered): |
| + return &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["notOffered"]} |
| + case errors.Is(err, domainreg.ErrPremium): |
| + return &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["premium"]} |
| + case errors.Is(err, domainreg.ErrCostAboveCeiling), errors.Is(err, registrar.ErrRefused), errors.Is(err, registrar.ErrIndeterminate): |
| + log.Printf("console: domain buy refused: %v", err) |
| + default: |
| + log.Printf("console: domain buy failed: %v", err) |
| } |
| - return ref |
| + return domainBuyUnavailable() |
| } |
| var domainPurchaseCopy = struct { |
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go| new file mode 100644 |
| index 000000000..9e5b77d00 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_fix_test.go |
| @@ -0,0 +1,325 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func holdBuyName(t *testing.T, f *purchaseFixture, host string) { |
| + t.Helper() |
| + if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: host, Account: "foreign", App: "other"}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestCheckDoorPlanGateFirst(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.start(t) |
| + holdBuyName(t, f, "held.com") |
| + holdBuyName(t, f, "www.wwwheld.com") |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + tok := buyToken(t, f) |
| + before := len(f.reg.Calls) |
| + wantStatus, wantBody := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"free.com"}`) |
| + ref := f.srv.customDomainRefusal(f.acct, "free.com") |
| + if ref == nil || wantStatus != ref.Status || !strings.Contains(wantBody, ref.Msg) { |
| + t.Fatalf("plan refusal: %d %s", wantStatus, wantBody) |
| + } |
| + for _, door := range []string{"check", "purchases"} { |
| + for _, name := range []string{"held.com", "wwwheld.com", "shop.com", "free.com"} { |
| + body := strings.ReplaceAll(buyBody(), "shop.com", name) |
| + if door == "check" { |
| + body = fmt.Sprintf(`{"name":%q}`, name) |
| + } |
| + status, got := buyRequest(t, f, "POST", buyAPIPath(f)+"/"+door, tok, body) |
| + if status != wantStatus || got != wantBody { |
| + t.Errorf("%s %s: %d %q, want %d %q", door, name, status, got, wantStatus, wantBody) |
| + } |
| + } |
| + } |
| + if len(f.reg.Calls) != before { |
| + t.Fatal("plan refusal reached registrar") |
| + } |
| +} |
| + |
| +func TestCheckAndBuyNeutralAcrossClaimLivePurchaseAndTaken(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + f.start(t) |
| + holdBuyName(t, f, "held.com") |
| + holdBuyName(t, f, "www.wwwheld.com") |
| + wantStatus, wantBody := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"held.com"}`) |
| + if wantStatus != 409 { |
| + t.Fatalf("held: %d %s", wantStatus, wantBody) |
| + } |
| + for _, door := range []string{"check", "purchases"} { |
| + for _, name := range []string{"held.com", "wwwheld.com", "shop.com", "taken.com"} { |
| + body := strings.ReplaceAll(buyBody(), "shop.com", name) |
| + if door == "check" { |
| + body = fmt.Sprintf(`{"name":%q}`, name) |
| + } |
| + status, got := buyRequest(t, f, "POST", buyAPIPath(f)+"/"+door, tok, body) |
| + if status != wantStatus || got != wantBody { |
| + t.Errorf("%s %s: %d %q, want %d %q", door, name, status, got, wantStatus, wantBody) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestCapabilityBuyIsOwnFieldFeaturesUntouched(t *testing.T) { |
| + for _, content := range []string{`{"schema":1,"app":"kass","features":{},"set_at":"2026-11-01T00:00:00Z"}`, `{"schema":1,"app":"kass","features":{"buy":"shop-setting","other":"on"},"set_at":"2026-11-01T00:00:00Z"}`, `{"schema":9}`} { |
| + f := newPurchaseFixture(t) |
| + if _, err := f.rel.Put(context.Background(), release.FeaturesKey(f.acct.Sqid, "kass"), []byte(content), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, ready := range []bool{true, false} { |
| + f.srv.billing.ready.Store(ready) |
| + want, stamp := f.srv.appFeatures(context.Background(), f.acct.Sqid, "kass") |
| + got := f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass") |
| + if !reflect.DeepEqual(got.Features, want) || got.FeaturesSetAt != stamp { |
| + t.Errorf("features changed: %+v want %v at %s", got, want, stamp) |
| + } |
| + raw, err := json.Marshal(got) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var wire map[string]json.RawMessage |
| + if err := json.Unmarshal(raw, &wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ready && string(wire["buy"]) != "true" { |
| + t.Errorf("missing own buy field: %s", raw) |
| + } |
| + if !ready && wire["buy"] != nil { |
| + t.Errorf("false buy must be omitted: %s", raw) |
| + } |
| + } |
| + } |
| +} |
| + |
| +type checkErrorRegistrar struct { |
| + registrar.Registrar |
| + err error |
| +} |
| + |
| +func (r checkErrorRegistrar) Check(context.Context, string) (registrar.Availability, error) { |
| + return registrar.Availability{}, r.err |
| +} |
| + |
| +func TestCatalogErrorsNeverReachCustomers(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, domain, key string |
| + status int |
| + err error |
| + }{ |
| + {"missing-currency", "shop.com", "notOffered", 422, nil}, |
| + {"not-registrable", "www.shop.com", "nameError", 422, nil}, |
| + {"wrapped-catalog", "shop.com", "notOffered", 422, fmt.Errorf("private: %w", domainreg.ErrTLDNotOffered)}, |
| + {"wrapped-name", "shop.com", "nameError", 422, fmt.Errorf("private: %w", domainreg.ErrNotRegistrable)}, |
| + {"catalog-taken", "shop.com", "neutral", 409, fmt.Errorf("private: %w", domainreg.ErrNotAvailable)}, |
| + {"registrar-taken", "shop.com", "neutral", 409, fmt.Errorf("private: %w", registrar.ErrUnavailable)}, |
| + {"indeterminate", "shop.com", "unavailable", 503, fmt.Errorf("private: %w", registrar.ErrIndeterminate)}, |
| + {"premium", "shop.com", "premium", 422, fmt.Errorf("private: %w", domainreg.ErrPremium)}, |
| + {"cost", "shop.com", "unavailable", 503, fmt.Errorf("private: %w", domainreg.ErrCostAboveCeiling)}, |
| + {"refused", "shop.com", "unavailable", 503, fmt.Errorf("private: %w", registrar.ErrRefused)}, |
| + {"unknown", "shop.com", "unavailable", 503, errors.New("private provider failure")}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + if tc.name == "missing-currency" { |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"eur": 1500} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| + } |
| + if tc.err != nil { |
| + f.srv.cfg.Registrar = checkErrorRegistrar{f.reg, tc.err} |
| + } |
| + tok := buyToken(t, f) |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + for _, door := range []string{"check", "purchases"} { |
| + body := strings.ReplaceAll(buyBody(), "shop.com", tc.domain) |
| + if door == "check" { |
| + body = fmt.Sprintf(`{"name":%q}`, tc.domain) |
| + } |
| + status, got := buyRequest(t, f, "POST", buyAPIPath(f)+"/"+door, tok, body) |
| + var reply map[string]string |
| + if err := json.Unmarshal([]byte(got), &reply); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := domainBuyCopy[tc.key] |
| + if tc.key == "neutral" { |
| + want = hostUnavailableMsg |
| + } |
| + if status != tc.status || reply["error"] != want { |
| + t.Errorf("%s: %d %s", door, status, got) |
| + } |
| + } |
| + if tc.name == "unknown" && !strings.Contains(logs.String(), "private provider failure") { |
| + t.Error("unknown error not logged") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCheckLimiterPerAccountAndDeployment(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + now := time.Now() |
| + f.srv.domainChecks.now = func() time.Time { return now } |
| + tok := buyToken(t, f) |
| + if err := f.st.AddMember(f.acct.ID, "second-owner@example.com", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + second := cliToken(t, f.consoleFixture, "second-owner@example.com", "second") |
| + for i := 0; i < 20; i++ { |
| + token := tok |
| + if i%2 != 0 { |
| + token = second |
| + } |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", token, `{"name":"shop.com"}`) |
| + if status != 200 { |
| + t.Fatalf("check %d: %d %s", i, status, body) |
| + } |
| + } |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", second, `{"name":"shop.com"}`) |
| + if status != 429 || !strings.Contains(body, domainBuyCopy["rate"]) { |
| + t.Errorf("account budget: %d %s", status, body) |
| + } |
| + if n := purchaseCalls(f.reg.Calls, "check:"); n != 20 { |
| + t.Errorf("registrar checks %d want 20", n) |
| + } |
| + // Browser checks spend the same account budget. |
| + browser := newBrowser(t) |
| + f.setUser("owner" + f.acct.Sqid + "@example.com") |
| + signUp(t, f.consoleFixture, browser, "limited") |
| + status, _, body = postForm(t, browser, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/check", map[string][]string{"csrf": {sessionToken(t, f.consoleFixture, browser)}, "name": {"shop.com"}}) |
| + if status != 429 { |
| + t.Errorf("browser budget: status %d", status) |
| + } |
| + // Six independent paid accounts can spend at most 120 deployment tokens. |
| + for i := 0; i < 6; i++ { |
| + acct := planAccount(t, f.consoleFixture, int64(700+i)) |
| + if _, err := f.st.SetAccountPlan(acct.ID, "personal", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.st.SetBillingCustomer(acct.ID, fmt.Sprintf("cus_limit_%d", i), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.st.PutBillingState(billingAccount{AccountID: acct.ID, Currency: "usd"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for j := 0; j < 20; j++ { |
| + _, ref := f.srv.checkDomainBuy(context.Background(), acct, "shop.com") |
| + if i < 5 && ref != nil { |
| + t.Fatalf("deployment %d/%d: %+v", i, j, ref) |
| + } |
| + if i == 5 && (ref == nil || ref.Status != 429 || ref.Msg != domainBuyCopy["rate"]) { |
| + t.Fatalf("deployment budget: %+v", ref) |
| + } |
| + } |
| + } |
| + if n := purchaseCalls(f.reg.Calls, "check:"); n != 120 { |
| + t.Errorf("deployment registrar checks %d want 120", n) |
| + } |
| +} |
| + |
| +func TestHeldElsewhereLogsNoAlert(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + holdBuyName(t, f, "shop.com") |
| + pages := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { pages++; return nil } |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + if ref == nil || ref.Status != 409 { |
| + t.Fatalf("refusal: %+v", ref) |
| + } |
| + if pages != 0 { |
| + t.Errorf("held claim paged %d times", pages) |
| + } |
| + if !strings.Contains(logs.String(), "claim held elsewhere") { |
| + t.Error("held claim not logged") |
| + } |
| +} |
| + |
| +func TestCheckLimiterRefillAndConcurrentAdmission(t *testing.T) { |
| + now := time.Now() |
| + l := domainCheckLimiter{now: func() time.Time { return now }} |
| + var accepted atomic.Int64 |
| + var wg sync.WaitGroup |
| + for i := 0; i < 200; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + if l.allow(1) { |
| + accepted.Add(1) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if got := accepted.Load(); got != 20 { |
| + t.Fatalf("concurrent account accepts %d", got) |
| + } |
| + now = now.Add(2999 * time.Millisecond) |
| + if l.allow(1) { |
| + t.Fatal("account refilled before three seconds") |
| + } |
| + now = now.Add(time.Millisecond) |
| + if !l.allow(1) || l.allow(1) { |
| + t.Fatal("account did not refill exactly one token") |
| + } |
| + now = now.Add(time.Minute) |
| + for i := 0; i < 20; i++ { |
| + if !l.allow(1) { |
| + t.Fatalf("idle account check %d refused", i) |
| + } |
| + } |
| + if l.allow(1) { |
| + t.Fatal("idle account exceeded burst") |
| + } |
| + |
| + l = domainCheckLimiter{now: func() time.Time { return now }} |
| + accepted.Store(0) |
| + for i := 0; i < 200; i++ { |
| + wg.Add(1) |
| + go func(id int64) { |
| + defer wg.Done() |
| + if l.allow(id) { |
| + accepted.Add(1) |
| + } |
| + }(int64(i)) |
| + } |
| + wg.Wait() |
| + if got := accepted.Load(); got != 120 { |
| + t.Fatalf("concurrent deployment accepts %d", got) |
| + } |
| + now = now.Add(499 * time.Millisecond) |
| + if l.allow(300) { |
| + t.Fatal("deployment refilled before half a second") |
| + } |
| + now = now.Add(time.Millisecond) |
| + if !l.allow(300) || l.allow(301) { |
| + t.Fatal("deployment did not refill exactly one token") |
| + } |
| +} |
diff --git a/internal/console/domainbuy_limit.go b/internal/console/domainbuy_limit.go| new file mode 100644 |
| index 000000000..e3aa5b3f7 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_limit.go |
| @@ -0,0 +1,71 @@ |
| +package console |
| + |
| +import ( |
| + "sync" |
| + "time" |
| +) |
| + |
| +const ( |
| + domainCheckAccountBudget = 20 |
| + domainCheckDeploymentBudget = 120 |
| +) |
| + |
| +type domainCheckBucket struct { |
| + credit time.Duration |
| + at time.Time |
| +} |
| + |
| +func (b *domainCheckBucket) refill(now time.Time) { |
| + if b.at.IsZero() { |
| + b.credit, b.at = time.Minute, now |
| + } else if now.After(b.at) { |
| + b.credit = min(time.Minute, b.credit+now.Sub(b.at)) |
| + b.at = now |
| + } |
| +} |
| + |
| +type domainCheckLimiter struct { |
| + mu sync.Mutex |
| + accounts map[int64]*domainCheckBucket |
| + deployment domainCheckBucket |
| + swept time.Time |
| + now func() time.Time |
| +} |
| + |
| +func (l *domainCheckLimiter) allow(account int64) bool { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + now := time.Now() |
| + if l.now != nil { |
| + now = l.now() |
| + } |
| + if l.accounts == nil { |
| + l.accounts = make(map[int64]*domainCheckBucket) |
| + } |
| + if now.Sub(l.swept) >= time.Minute { |
| + for id, b := range l.accounts { |
| + if now.Sub(b.at) >= time.Minute { |
| + delete(l.accounts, id) |
| + } |
| + } |
| + l.swept = now |
| + } |
| + l.deployment.refill(now) |
| + b := l.accounts[account] |
| + if b == nil { |
| + if len(l.accounts) >= maxRateKeys { |
| + return false |
| + } |
| + b = &domainCheckBucket{} |
| + l.accounts[account] = b |
| + } |
| + b.refill(now) |
| + const accountCost = time.Minute / domainCheckAccountBudget |
| + const deploymentCost = time.Minute / domainCheckDeploymentBudget |
| + if b.credit < accountCost || l.deployment.credit < deploymentCost { |
| + return false |
| + } |
| + b.credit -= accountCost |
| + l.deployment.credit -= deploymentCost |
| + return true |
| +} |
diff --git a/internal/console/domainstate.go b/internal/console/domainstate.go| index d21e612e3..27bd52aa4 100644 |
| --- a/internal/console/domainstate.go |
| +++ b/internal/console/domainstate.go |
| @@ -272,6 +272,7 @@ type deploymentCapability struct { |
| // implement DNS verification itself. This is what retires titogo's |
| // TITO_CUSTOM_DOMAINS switch. |
| ManagedDomains bool `json:"managed_domains"` |
| + Buy bool `json:"buy,omitempty"` |
| AppsDomain string `json:"apps_domain,omitempty"` |
| SteeringHost string `json:"steering_host,omitempty"` |
| EdgeIPs []string `json:"edge_ips,omitempty"` |
| @@ -293,17 +294,8 @@ type deploymentCapability struct { |
| func (s *Server) domainCapability(ctx context.Context, acct, app string) deploymentCapability { |
| t := s.dnsTargets(ctx) |
| features, setAt := s.appFeatures(ctx, acct, app) |
| - // The buy capability is deployment-owned, never an app-supplied flag. |
| - if features != nil { |
| - delete(features, "buy") |
| - } |
| - if s.domainBuyReady() { |
| - if features == nil { |
| - features = make(map[string]string) |
| - } |
| - features["buy"] = "true" |
| - } |
| return deploymentCapability{ |
| + Buy: s.domainBuyReady(), |
| ManagedDomains: true, |
| AppsDomain: strings.TrimSpace(s.cfg.AppsDomain), |
| SteeringHost: t.SteeringHost, |
diff --git a/internal/console/server.go b/internal/console/server.go| index f37963fd5..98c322027 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1111,6 +1111,8 @@ type Server struct { |
| instances *instanceFetcher |
| secure bool // Secure cookies iff the origin is https |
| cli *cliLimits // rate limits on the CLI-identity endpoints (authcli.go) |
| + |
| + domainChecks domainCheckLimiter |
| // boxCerts are AWS's instance-identity signing certificates by AWS |
| // region (boxid.EmbeddedCerts), loaded once at construction. The Phase |
| // 1 move door verifies each box's identity record with them; nil (a |
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html| index 8bd9534c0..f66605e16 100644 |
| --- a/internal/console/templates/domain_buy.html |
| +++ b/internal/console/templates/domain_buy.html |
| @@ -25,7 +25,7 @@ |
| </script> |
| {{else if .Quote}} |
| <p>{{$.DomainBuyCopy.name}}: <strong>{{.Quote.Domain}}</strong></p> |
| -<p>{{$.DomainBuyCopy.quote}}: {{.Price}} {{.Quote.Currency}}</p> |
| +<p>{{$.DomainBuyCopy.quote}}: {{.Price}}</p> |
| <p class="small">{{$.DomainBuyCopy.paymentDetails}}</p> |
| <h2>{{$.DomainBuyCopy.contact}}</h2> |
| <form method="post" action="{{.Base}}/buy"> |
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go| index ffc4dddf7..8c08b18b1 100644 |
| --- a/internal/registrar/registrar.go |
| +++ b/internal/registrar/registrar.go |
| @@ -21,8 +21,18 @@ type Availability struct { |
| type Contact struct { |
| // Country ISO 3166-1 alpha-2 |
| - FirstName, LastName, Company, Email, Phone, Street, City, State, PostalCode, Country string |
| - PhoneCountryCode, HouseNumber string |
| + FirstName string `json:"first_name"` |
| + LastName string `json:"last_name"` |
| + Company string `json:"company"` |
| + Email string `json:"email"` |
| + Phone string `json:"phone"` |
| + Street string `json:"street"` |
| + City string `json:"city"` |
| + State string `json:"state"` |
| + PostalCode string `json:"postal_code"` |
| + Country string `json:"country"` |
| + PhoneCountryCode string `json:"phone_country_code"` |
| + HouseNumber string `json:"house_number"` |
| } |
| type Registration struct { |
diff --git a/internal/registrar/registrar_test.go b/internal/registrar/registrar_test.go| index ec669885c..27ffebadf 100644 |
| --- a/internal/registrar/registrar_test.go |
| +++ b/internal/registrar/registrar_test.go |
| @@ -2,6 +2,7 @@ package registrar_test |
| import ( |
| "context" |
| + "encoding/json" |
| "errors" |
| "reflect" |
| "strings" |
| @@ -213,3 +214,33 @@ func TestFakeContactIdentity(t *testing.T) { |
| t.Fatalf("new identity = %q, %v", got, err) |
| } |
| } |
| + |
| +func TestContactJSONSnakeCase(t *testing.T) { |
| + wire := `{"first_name":"Alex","last_name":"Example","company":"Shop","email":"alex@example.com","phone_country_code":"44","phone":"2079460000","street":"Example Street","house_number":"1","city":"London","state":"London","postal_code":"SW1A 1AA","country":"GB"}` |
| + want := fullContact() |
| + want.Company = "Shop" |
| + want.Street = "Example Street" |
| + want.HouseNumber = "1" |
| + want.State = "London" |
| + var got registrar.Contact |
| + if err := json.Unmarshal([]byte(wire), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != want { |
| + t.Errorf("decoded %+v want %+v", got, want) |
| + } |
| + raw, err := json.Marshal(want) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var gotMap, wantMap map[string]string |
| + if err := json.Unmarshal(raw, &gotMap); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := json.Unmarshal([]byte(wire), &wantMap); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(gotMap, wantMap) { |
| + t.Errorf("wire %s", raw) |
| + } |
| +} |