domains: buy without a subscription; real refusal reasons
Allow sponsored accounts through the shared custom-domain gate. Create the billing customer and fix its currency at the first domain purchase. Keep neutral name refusals, explain account refusals, alert on registrar setup errors, preserve registry messages, and print purchase IDs.
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
16 files changed,
+476
−21
domains_buy_cli.go+1 −0domains_buy_cli_test.go+2 −2domains_buy_copy.go+2 −0internal/console/billingcard.go+11 −0internal/console/billingcard_test.go+14 −0internal/console/billingcustomer.go+1 −1internal/console/domainbuy.go+62 −10internal/console/domainbuy_admission_test.go+1 −1internal/console/domainbuy_copy.go+17 −0internal/console/domainbuy_fix_test.go+1 −1internal/console/domainbuy_nosub_test.go+268 −0internal/console/domainbuy_registry_test.go+54 −0internal/console/plancaps.go+3 −0internal/registrar/openprovider/client.go+9 −6internal/registrar/openprovider/client_test.go+27 −0internal/registrar/registrar.go+3 −0
diff --git a/domains_buy_cli.go b/domains_buy_cli.go| index df6a862f1..221ee07b1 100644 |
| --- a/domains_buy_cli.go |
| +++ b/domains_buy_cli.go |
| @@ -141,6 +141,7 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri |
| if err != nil { |
| return err |
| } |
| + fmt.Fprintf(o.out, domainsBuyCopy["purchaseID"], p.ID) |
| if p.CheckoutURL != "" { |
| fmt.Fprintf(o.out, domainsBuyCopy["checkout"], p.CheckoutURL) |
| } |
diff --git a/domains_buy_cli_test.go b/domains_buy_cli_test.go| index dc781d1a1..a030082a8 100644 |
| --- a/domains_buy_cli_test.go |
| +++ b/domains_buy_cli_test.go |
| @@ -94,7 +94,7 @@ func TestDomainsBuyPrintsCheckoutAndWaitsToLive(t *testing.T) { |
| if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil { |
| t.Fatal(err) |
| } |
| - for _, want := range []string{"https://checkout.example/p1", "awaiting_payment", "authorised", "registered", "captured", "done", "issuing-cert", "live"} { |
| + for _, want := range []string{"purchase: p1", "https://checkout.example/p1", "awaiting_payment", "authorised", "registered", "captured", "done", "issuing-cert", "live"} { |
| if strings.Count(out.String(), want) != 1 { |
| t.Fatalf("expected %q once: %s", want, &out) |
| } |
| @@ -234,7 +234,7 @@ func TestDomainsBuyContactInputs(t *testing.T) { |
| if calls != wantCalls { |
| t.Fatalf("purchase calls=%d want=%d", calls, wantCalls) |
| } |
| - if !strings.Contains(out.String(), "https://checkout.example/p1") { |
| + if !strings.Contains(out.String(), "https://checkout.example/p1") || !strings.Contains(out.String(), "purchase: p1") { |
| t.Fatalf("missing checkout: %s", &out) |
| } |
| }) |
diff --git a/domains_buy_copy.go b/domains_buy_copy.go| index bfe00c1e5..37f0d9191 100644 |
| --- a/domains_buy_copy.go |
| +++ b/domains_buy_copy.go |
| @@ -9,6 +9,8 @@ const domainsCheckUsage = "usage: carlos domains check <name> [--account <a>] [- |
| const domainsBuyUsage = "usage: carlos domains buy <name> --app <a> [--contact-file contact.json] [--yes] [--no-wait] [--account <a>] [--account-id <id>] [--console <origin>]\n" |
| var domainsBuyCopy = map[string]string{ |
| + // Draft for the Luna pass: domain registration Plan 2, slice 1. |
| + "purchaseID": "purchase: %s\n", |
| "appFlag": "app the domain will serve", |
| "accountFlag": "account (sqid or name)", |
| "accountIDFlag": "account sqid, matched as a sqid only", |
diff --git a/internal/console/billingcard.go b/internal/console/billingcard.go| index ea2208031..4c404d306 100644 |
| --- a/internal/console/billingcard.go |
| +++ b/internal/console/billingcard.go |
| @@ -50,6 +50,10 @@ func (s *Server) cardSetupLocked(h billingHold, ctx context.Context, acct *Accou |
| if err != nil { |
| return "", err |
| } |
| + stamp, err := s.providerNow(ctx) |
| + if err != nil { |
| + return "", errNoProviderTimeRefusal |
| + } |
| back := s.cfg.Origin + billingPagePath(acct.Sqid) |
| // Like a portal open, each attempt gets a fresh session. It cannot charge |
| // money or change a subscription, and an unknown response is never replayed. |
| @@ -57,6 +61,13 @@ func (s *Server) cardSetupLocked(h billingHold, ctx context.Context, acct *Accou |
| if err != nil { |
| return "", err |
| } |
| + now, err := s.providerNow(ctx) |
| + if err != nil { |
| + return "", errNoProviderTimeRefusal |
| + } |
| + if ok, _ := recoveryEligible(resendState{State: opSending, FirstSent: stamp, ContextCurrent: ctx.Err() == nil}, now); !ok { |
| + return "", errCheckoutFailed |
| + } |
| result, err := s.sendPreparedLocked(h, ctx, req) |
| if err != nil { |
| return "", err |
diff --git a/internal/console/billingcard_test.go b/internal/console/billingcard_test.go| index 579afdfa3..a9c69b066 100644 |
| --- a/internal/console/billingcard_test.go |
| +++ b/internal/console/billingcard_test.go |
| @@ -80,3 +80,17 @@ func TestBillingAddCardGates(t *testing.T) { |
| t.Fatal("gate sent provider writes") |
| } |
| } |
| + |
| +func TestBillingAddCardNoProviderTimeSendsNothing(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + o.stepUp(t) |
| + o.reset() |
| + o.fake.ProbeErr = billing.ErrNoResponse |
| + r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil) |
| + if r.Status != 303 || r.Loc != o.billingBase() || r.FlashMsg != billingCopy["card.failed"] { |
| + t.Fatalf("clock refusal: %+v", r) |
| + } |
| + if len(o.fake.Sent) != 0 { |
| + t.Fatal("setup sent without provider time") |
| + } |
| +} |
diff --git a/internal/console/billingcustomer.go b/internal/console/billingcustomer.go| index a1528bbe3..ac1adc833 100644 |
| --- a/internal/console/billingcustomer.go |
| +++ b/internal/console/billingcustomer.go |
| @@ -36,7 +36,7 @@ func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct |
| if err != nil { |
| return nil, err |
| } |
| - if prior != nil && !intentTerminal(prior) && prior.Currency != currency { |
| + if prior != nil && (!intentTerminal(prior) || prior.State == intentCompleted) && prior.Currency != currency { |
| return nil, errCheckoutUncertain |
| } |
| b.Currency = currency |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 971e829a5..a3b6f446d 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -36,11 +36,14 @@ func domainBuyUnavailable() *doorRefusal { |
| // Other holders may only produce the neutral refusal: |
| // name-only refusals and the shared budget come first, then registrar availability, |
| // then the claim/live checks, and finally premium and price checks. |
| -func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| +func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string, country ...string) (domainreg.Quote, *doorRefusal) { |
| if !s.domainBuyReady() { |
| return domainreg.Quote{}, &doorRefusal{Status: http.StatusNotFound} |
| } |
| if ref := s.customDomainRefusal(acct, name); ref != nil { |
| + if ref.Status == http.StatusConflict { |
| + return domainreg.Quote{}, domainBuyStateRefusal("plan", http.StatusConflict) |
| + } |
| return domainreg.Quote{}, ref |
| } |
| name, err := domainreg.Normalize(name) |
| @@ -55,20 +58,37 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil |
| } |
| b, err := s.store.BillingAccount(acct.ID) |
| - if err != nil || b == nil || b.Currency == "" || b.Customer == "" { |
| - return domainreg.Quote{}, domainBuyUnavailable() |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + currency := "" |
| + if b != nil { |
| + currency = b.Currency |
| + } |
| + if currency == "" { |
| + location := "" |
| + if len(country) > 0 { |
| + location = country[0] |
| + } |
| + currency, err = s.billing.cfg.Book.ChooseCurrency("", location) |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| } |
| suffix, _ := publicsuffix.PublicSuffix(name) |
| tld, offered := s.cfg.DomainCatalog.TLDs[suffix] |
| - if !offered || tld.Register[b.Currency] <= 0 { |
| + if !offered { |
| return domainreg.Quote{}, domainBuyErrorRefusal(domainreg.ErrTLDNotOffered) |
| } |
| + if tld.Register[currency] <= 0 { |
| + return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| if !s.domainChecks.allow(acct.ID) { |
| return domainreg.Quote{}, &doorRefusal{http.StatusTooManyRequests, domainBuyCopy["rate"]} |
| } |
| a, err := s.cfg.Registrar.Check(ctx, name) |
| if err != nil { |
| - return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| + return domainreg.Quote{}, s.domainBuyRegistrarRefusal(ctx, acct, name, err) |
| } |
| if !a.Available { |
| return domainreg.Quote{}, claimRefusal(name, domains.ErrHostUnavailable) |
| @@ -95,7 +115,7 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil { |
| return domainreg.Quote{}, ref |
| } |
| - q, err := s.cfg.DomainCatalog.Quote(name, b.Currency, a) |
| + q, err := s.cfg.DomainCatalog.Quote(name, currency, a) |
| if errors.Is(err, domainreg.ErrCostAboveCeiling) { |
| s.purchaseRefusalAlert(ctx, acct, name, "cost:"+suffix, "registrar cost above ceiling") |
| } |
| @@ -108,7 +128,7 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| // Serialize starts so a concurrent buyer resumes the winning checkout. |
| defer s.planLock(acct)() |
| - q, ref := s.admitDomainBuy(ctx, acct, name) |
| + q, ref := s.admitDomainBuy(ctx, acct, name, c.Country) |
| if ref != nil { |
| return nil, "", ref |
| } |
| @@ -140,12 +160,28 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| } |
| balance, err := s.cfg.Registrar.Balance(ctx) |
| if err != nil { |
| - return nil, "", domainBuyErrorRefusal(err) |
| + return nil, "", s.domainBuyRegistrarRefusal(ctx, acct, name, err) |
| } |
| if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor { |
| s.purchaseRefusalAlert(ctx, acct, name, "balance", "registrar balance") |
| return nil, "", domainBuyUnavailable() |
| } |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return nil, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + b, err := s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true) |
| + release() |
| + if err != nil { |
| + log.Printf("console: domain buy billing %s: %v", acct.Sqid, err) |
| + return nil, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + // Subscription checkout or card setup may have acquired the billing hold first. |
| + q.Currency = b.Currency |
| + q.Price = s.cfg.DomainCatalog.TLDs[q.TLD].Register[q.Currency] |
| + if q.Price <= 0 { |
| + return nil, "", domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| 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, |
| @@ -183,6 +219,16 @@ func (s *Server) resumeDomainPurchase(ctx context.Context, p *DomainPurchase) (* |
| } |
| if err != nil { |
| log.Printf("console: purchase %s: checkout: %v", p.ID, err) |
| + if errors.Is(err, registrar.ErrSetup) { |
| + acct, readErr := s.store.AccountByID(p.AccountID) |
| + if readErr == nil && acct != nil { |
| + s.domainBuyRegistrarRefusal(ctx, acct, p.Domain, err) |
| + } |
| + return p, "", domainBuyUnavailable() |
| + } |
| + if p.State == PurchaseFailed && p.Reason == "payment_setup" { |
| + return p, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| if p.State == PurchaseFailed && p.Reason == "contact" { |
| return p, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| } |
| @@ -271,7 +317,7 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| } |
| handle, err := s.cfg.Registrar.EnsureContact(ctx, existing, p.Contact) |
| if err != nil { |
| - if errors.Is(err, registrar.ErrRefused) { |
| + 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" })) |
| } |
| return "", err |
| @@ -613,6 +659,12 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| if err == nil { |
| return s.registeredPurchase(ctx, p, r) |
| } |
| + if errors.Is(err, registrar.ErrSetup) { |
| + acct, readErr := s.store.AccountByID(p.AccountID) |
| + if readErr == nil && acct != nil { |
| + s.domainBuyRegistrarRefusal(ctx, acct, p.Domain, err) |
| + } |
| + } |
| if p.Attempts > 1 { |
| // Any earlier attempt may have registered it. Even a definite refusal of this request cannot disprove that. |
| r, found, readErr := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| @@ -627,7 +679,7 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| reason := "" |
| if errors.Is(err, registrar.ErrUnavailable) { |
| reason = "taken" |
| - } else if errors.Is(err, registrar.ErrRefused) { |
| + } else if errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrSetup) { |
| reason = "refused" |
| } |
| if reason == "" { |
diff --git a/internal/console/domainbuy_admission_test.go b/internal/console/domainbuy_admission_test.go| index 935ded5ee..9db74fc56 100644 |
| --- a/internal/console/domainbuy_admission_test.go |
| +++ b/internal/console/domainbuy_admission_test.go |
| @@ -22,7 +22,7 @@ func TestBuyAdmissionNeutralityGuard(t *testing.T) { |
| {name: "offered", suffix: "com", status: 409, checks: 8}, |
| {name: "outside-catalog", suffix: "io", key: "notOffered", status: 422}, |
| {name: "non-registrable", suffix: "shop.com", key: "nameError", status: 422}, |
| - {name: "missing-currency", suffix: "com", key: "notOffered", status: 422}, |
| + {name: "missing-currency", suffix: "com", key: "currency", status: 422}, |
| {name: "held-premium", suffix: "com", status: 409, checks: 8, premium: true}, |
| {name: "held-high-cost", suffix: "com", status: 409, checks: 8}, |
| {name: "registered-premium", suffix: "com", status: 409, checks: 8, premium: true}, |
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go| index 5e91517e2..b4524af3e 100644 |
| --- a/internal/console/domainbuy_copy.go |
| +++ b/internal/console/domainbuy_copy.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "log" |
| "net/http" |
| @@ -14,6 +15,11 @@ import ( |
| // docs/superpowers/specs/LUNA-COPY-RESULT-DOMAINS-1.md, plus controller rulings |
| // on four flags. Apply later edits through a copy pass. |
| var domainBuyCopy = map[string]string{ |
| + // Drafts for the Luna pass: domain registration Plan 2, slice 1. |
| + "plan": capMessage("cli.cap.custom_domain"), // Existing approved plan refusal. |
| + "billingSetup": "we could not set up billing for your account. try again later", |
| + "currency": "there is no price for this domain ending in your account currency", |
| + |
| "title": "Buy a domain", |
| "name": "Domain", |
| "check": "Check availability", |
| @@ -89,3 +95,14 @@ var domainPurchaseCopy = struct { |
| OperatorSubject: "Domain purchase needs attention", |
| OperatorBody: "Domain: %s\nPurchase: %s\nAccount: %s\nReason: %s\n", |
| } |
| + |
| +func domainBuyStateRefusal(key string, status int) *doorRefusal { |
| + return &doorRefusal{status, domainBuyCopy[key]} |
| +} |
| + |
| +func (s *Server) domainBuyRegistrarRefusal(ctx context.Context, acct *Account, name string, err error) *doorRefusal { |
| + if errors.Is(err, registrar.ErrSetup) { |
| + s.purchaseRefusalAlert(ctx, acct, name, "registrar-setup", err.Error()) |
| + } |
| + return domainBuyErrorRefusal(err) |
| +} |
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go| index 70c884cb4..fafcfc2cb 100644 |
| --- a/internal/console/domainbuy_fix_test.go |
| +++ b/internal/console/domainbuy_fix_test.go |
| @@ -133,7 +133,7 @@ func TestCatalogErrorsNeverReachCustomers(t *testing.T) { |
| status int |
| err error |
| }{ |
| - {"missing-currency", "shop.com", "notOffered", 422, nil}, |
| + {"missing-currency", "shop.com", "currency", 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)}, |
diff --git a/internal/console/domainbuy_nosub_test.go b/internal/console/domainbuy_nosub_test.go| new file mode 100644 |
| index 000000000..70443332b |
| --- /dev/null |
| +++ b/internal/console/domainbuy_nosub_test.go |
| @@ -0,0 +1,268 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "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/registry" |
| +) |
| + |
| +func firstPurchaseAccount(t *testing.T, f *purchaseFixture) { |
| + t.Helper() |
| + f.acct = planAccount(t, f.consoleFixture, 503) |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.st.CreateAppIn(f.acct.ID, "kass", "buyer@example.test", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"usd": 1500, "eur": 1600, "gbp": 1700} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| +} |
| + |
| +func TestPurchaseWithoutSubscription(t *testing.T) { |
| + for _, country := range []string{"IE", "GB", "US"} { |
| + t.Run(country, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + c := purchaseContact() |
| + c.Country = country |
| + p, link, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test") |
| + if ref != nil || p == nil || link == "" { |
| + t.Fatalf("start: %+v %q %+v", p, link, ref) |
| + } |
| + currency, _ := f.srv.billing.cfg.Book.ChooseCurrency("", country) |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || b == nil || b.Customer == "" || b.Currency != currency || p.Currency != currency || b.Subscription != "" { |
| + t.Fatalf("billing/purchase currency: %+v %+v %v", b, p, err) |
| + } |
| + if p.Amount != f.srv.cfg.DomainCatalog.TLDs["com"].Register[currency] { |
| + t.Fatalf("wrong quote: %+v", p) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatal("expected exactly one customer create") |
| + } |
| + for _, req := range f.fake.Sent { |
| + if req.Kind == billing.PreparedCustomer { |
| + var body map[string]any |
| + if err := json.Unmarshal(req.Body, &body); err != nil { |
| + t.Fatal(err) |
| + } |
| + details, _ := body["details"].(map[string]any) |
| + if details["Country"] != country || details["PostalCode"] != c.PostalCode || details["Email"] != "owner"+f.acct.Sqid+"@example.com" { |
| + t.Fatalf("customer details: %v", details) |
| + } |
| + } |
| + } |
| + if ref := f.srv.customDomainRefusal(f.acct, "shop.com"); ref != nil { |
| + t.Fatalf("sponsored attach refused: %+v", ref) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseConcurrentFirstCustomer(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + var wg sync.WaitGroup |
| + errs := make(chan *doorRefusal, 2) |
| + for _, name := range []string{"shop.com", "second.com"} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test") |
| + errs <- ref |
| + }() |
| + } |
| + wg.Wait() |
| + close(errs) |
| + for ref := range errs { |
| + if ref != nil { |
| + t.Fatalf("start: %+v", ref) |
| + } |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatalf("customer creates: %d", f.sent(billing.PreparedCustomer)) |
| + } |
| +} |
| + |
| +func TestPurchaseOwnStateReasons(t *testing.T) { |
| + for _, reason := range []string{"billingSetup", "currency", "plan", "daily"} { |
| + t.Run(reason, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + switch reason { |
| + case "billingSetup": |
| + firstPurchaseAccount(t, f) |
| + f.fake.Err = billing.ErrRefused |
| + case "currency": |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"eur": 1500} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| + case "plan": |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "daily": |
| + f.srv.cfg.DomainCatalog.DailyCap = 1 |
| + f.start(t) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + } |
| + name := "shop.com" |
| + if reason == "daily" { |
| + name = "second.com" |
| + } |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test") |
| + if ref == nil || ref.Msg == domainBuyCopy["unavailable"] || strings.TrimSpace(ref.Msg) == "" { |
| + t.Fatalf("%s: %+v", reason, ref) |
| + } |
| + if reason == "currency" && !strings.Contains(ref.Msg, "currency") { |
| + t.Fatalf("missing currency reason: %+v", ref) |
| + } |
| + if reason != "daily" && f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("refusal created checkout") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseWithoutSubscriptionRefusalsHaveNoCustomer(t *testing.T) { |
| + for _, cause := range []string{"contact", "held", "currency", "balance"} { |
| + t.Run(cause, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + c := purchaseContact() |
| + switch cause { |
| + case "contact": |
| + c.FirstName = "" |
| + case "held": |
| + holdBuyName(t, f, "shop.com") |
| + case "currency": |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"gbp": 1500} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| + case "balance": |
| + f.reg.BalanceMoney.Minor = 0 |
| + } |
| + p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test") |
| + if p != nil || ref == nil { |
| + t.Fatalf("expected refusal: %+v %+v", p, ref) |
| + } |
| + if b, err := f.st.BillingAccount(f.acct.ID); err != nil || b != nil { |
| + t.Fatalf("refusal wrote billing: %+v %v", b, err) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 0 || f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 { |
| + t.Fatal("refusal made side effects") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseKeepsFirstCurrency(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + first := f.start(t) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + c := purchaseContact() |
| + c.Country = "GB" |
| + p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "second.com", c, "buyer@example.test") |
| + if ref != nil || p == nil || p.Currency != first.Currency || p.Amount != first.Amount { |
| + t.Fatalf("currency moved: %+v %+v %+v", first, p, ref) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatal("second customer created") |
| + } |
| +} |
| + |
| +func TestPurchaseAndCardShareCustomer(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + var wg sync.WaitGroup |
| + wg.Add(2) |
| + errs := make(chan error, 1) |
| + refs := make(chan *doorRefusal, 1) |
| + go func() { |
| + defer wg.Done() |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + refs <- ref |
| + }() |
| + go func() { |
| + defer wg.Done() |
| + h, release, err := f.srv.holdBilling(f.acct) |
| + if err != nil { |
| + errs <- err |
| + return |
| + } |
| + defer release() |
| + _, err = f.srv.cardSetupLocked(h, f.srv.billingClock(context.Background()), f.acct) |
| + errs <- err |
| + }() |
| + wg.Wait() |
| + if err := <-errs; err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref := <-refs; ref != nil { |
| + t.Fatalf("purchase: %+v", ref) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatalf("customer creates: %d", f.sent(billing.PreparedCustomer)) |
| + } |
| +} |
| + |
| +func TestPurchaseSponsoredReachesAttached(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: "app.example.test", Account: f.acct.Sqid, App: "kass", Kind: "static", Status: "ready", Channel: "canary/live"}) |
| + p := f.start(t) |
| + 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(), f.rel, host) |
| + if err != nil || claim.Account != f.acct.Sqid || claim.App != "kass" { |
| + t.Fatalf("sponsored attachment: %+v %v", claim, err) |
| + } |
| + } |
| + row, err := f.st.AccountPlan(f.acct.ID) |
| + if err != nil || row.Source != PlanSourceSponsored || row.Plan != "free" { |
| + t.Fatalf("plan changed: %+v %v", row, err) |
| + } |
| +} |
| + |
| +func TestPaymentCustomerRefusesConflictingSubscriptionCurrency(t *testing.T) { |
| + for _, state := range []string{intentOpen, intentCompleted} { |
| + t.Run(state, func(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + r := o.checkout(t, "plan", "personal", "currency", "usd") |
| + if r.Status != 303 || r.Flash != "" { |
| + t.Fatalf("checkout: %+v", r) |
| + } |
| + ci := o.intent(t) |
| + ci.State = state |
| + if err := o.st.PutCheckoutIntent(*ci); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := len(o.fake.Sent) |
| + h, release, err := o.srv.holdBilling(o.acct) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer release() |
| + _, err = o.srv.paymentCustomerLocked(h, o.srv.billingClock(context.Background()), o.acct, "IE", "D01 A123", true) |
| + if err != errCheckoutUncertain { |
| + t.Fatalf("conflicting subscription: %v", err) |
| + } |
| + b, err := o.st.BillingAccount(o.acct.ID) |
| + if err != nil || b.Currency != "" || len(o.fake.Sent) != sent { |
| + t.Fatalf("conflict wrote billing or sent requests: %+v %v", b, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/domainbuy_registry_test.go b/internal/console/domainbuy_registry_test.go| new file mode 100644 |
| index 000000000..7bcf05ae3 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_registry_test.go |
| @@ -0,0 +1,54 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registrar/openprovider" |
| +) |
| + |
| +func TestPurchaseRegistryErrors(t *testing.T) { |
| + for _, code := range []int{399, 309, 19010} { |
| + t.Run(fmt.Sprint(code), func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + const message = "Nameserver creation or update failed: Parent domain does not exist for host" |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/v1/auth/login" { |
| + fmt.Fprint(w, `{"code":0,"data":{"token":"test-token"}}`) |
| + return |
| + } |
| + fmt.Fprintf(w, `{"code":%d,"desc":%q}`, code, message) |
| + })) |
| + defer ts.Close() |
| + reg, err := openprovider.New(openprovider.Config{BaseURL: ts.URL + "/v1", Username: "test-user", Password: "test-pass", HTTP: ts.Client()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.srv.cfg.Registrar = reg |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + alerts := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| + for i := 0; i < 2; i++ { |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if ref == nil || ref.Msg != domainBuyCopy["unavailable"] { |
| + t.Fatalf("refusal: %+v", ref) |
| + } |
| + } |
| + if !strings.Contains(logs.String(), message) { |
| + t.Fatalf("missing registry message: %s", logs.String()) |
| + } |
| + if code != 399 && alerts != 1 { |
| + t.Fatalf("alerts=%d", alerts) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go| index 412745eee..cb1f788fd 100644 |
| --- a/internal/console/plancaps.go |
| +++ b/internal/console/plancaps.go |
| @@ -211,6 +211,9 @@ func (s *Server) checkFleets(acct *Account) error { |
| // checkCustomDomains refuses a custom domain on a plan without them. |
| // Platform hostnames are not custom domains; callers check those first. |
| func (s *Server) checkCustomDomains(acct *Account) error { |
| + if sponsored, err := s.planSponsored(acct); err != nil || sponsored { |
| + return err |
| + } |
| l, err := s.EffectiveLimits(acct) |
| if err != nil || l == nil || l.CustomDomains { |
| return err |
diff --git a/internal/registrar/openprovider/client.go b/internal/registrar/openprovider/client.go| index 4bb8fbfc1..e3d419bc4 100644 |
| --- a/internal/registrar/openprovider/client.go |
| +++ b/internal/registrar/openprovider/client.go |
| @@ -459,8 +459,14 @@ func (c *Client) send(ctx context.Context, method, path string, payload []byte, |
| if answer.Code != nil { |
| code = *answer.Code |
| } |
| + message := answer.Description |
| + for _, secret := range []string{c.username, c.password, token} { |
| + if secret != "" { |
| + message = strings.ReplaceAll(message, secret, "[redacted]") |
| + } |
| + } |
| if status >= 500 || status < 200 || (status >= 300 && status < 400) { |
| - return nil, status, responseError(method, path, fmt.Sprintf("HTTP %d", status)) |
| + return nil, status, &providerError{kind: responseError(method, path, fmt.Sprintf("HTTP %d", status)), status: status, code: code, message: message} |
| } |
| if status >= 400 || (decodeErr == nil && answer.Code != nil && code != 0) { |
| kind := registrar.ErrRefused |
| @@ -472,11 +478,8 @@ func (c *Client) send(ctx context.Context, method, path string, payload []byte, |
| if code == 311 { |
| kind = registrar.ErrUnavailable |
| } |
| - message := answer.Description |
| - for _, secret := range []string{c.username, c.password, token} { |
| - if secret != "" { |
| - message = strings.ReplaceAll(message, secret, "[redacted]") |
| - } |
| + if code == 309 || code == 19010 { |
| + kind = errors.Join(registrar.ErrRefused, registrar.ErrSetup) |
| } |
| return nil, status, &providerError{kind: kind, status: status, code: code, message: message} |
| } |
diff --git a/internal/registrar/openprovider/client_test.go b/internal/registrar/openprovider/client_test.go| index e79b57b89..ee84296ed 100644 |
| --- a/internal/registrar/openprovider/client_test.go |
| +++ b/internal/registrar/openprovider/client_test.go |
| @@ -536,3 +536,30 @@ func TestRegisterUnknownProviderOutcomeIsIndeterminate(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +func TestRegistryErrorMessagesAndSetupCodes(t *testing.T) { |
| + for _, status := range []int{200, 400, 500} { |
| + for _, code := range []int{399, 309, 19010} { |
| + t.Run(fmt.Sprintf("%d/%d", status, code), func(t *testing.T) { |
| + const message = "Nameserver creation or update failed: Parent domain does not exist for host" |
| + c := newClient(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(status) |
| + fmt.Fprintf(w, `{"code":%d,"desc":%q}`, code, message+" "+password+" "+token) |
| + }, time.Second) |
| + _, err := c.Register(context.Background(), registration()) |
| + if err == nil || !strings.Contains(err.Error(), message) { |
| + t.Fatalf("missing registry message: %v", err) |
| + } |
| + if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), token) { |
| + t.Fatal("credentials leaked") |
| + } |
| + if status < 500 && (code == 309 || code == 19010) && (!errors.Is(err, registrar.ErrSetup) || !errors.Is(err, registrar.ErrRefused)) { |
| + t.Fatalf("setup not refused: %v", err) |
| + } |
| + if status == 500 && !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatalf("ambiguous register was made definite: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go| index 8c08b18b1..d2c019d5a 100644 |
| --- a/internal/registrar/registrar.go |
| +++ b/internal/registrar/registrar.go |
| @@ -94,3 +94,6 @@ func (c Contact) Validate() error { |
| } |
| return nil |
| } |
| + |
| +// ErrSetup requires the operator to complete the registrar account setup. |
| +var ErrSetup = errors.New("registrar: account setup incomplete") |