carlos / platform Public

console: transfer engine (submit, capture on acceptance, wait, refund)

decideTransfer (domaintransfer_decide.go) is the one pure settlement
function; the engine gathers registrar, payment and refund facts,
performs the one action it names and records in CAS moves. The request
is sent at most once after the move that clears the auth code; definite
outcomes are sticky; unknown stays live until a status read or the
operator resolve door (POST /api/cli/system/domains/purchases/{id}/
resolve, store operators only, service-closed, audited). Refund attempts
are persisted before send and adopted by purchase and attempt.

Also: kind-aware resume at every buy and transfer door, shared admission
and registration recording, delivery-aware alertOperator, the DS lookup
(dnsds.go), the transfer start with its refusals, owner emails, an
opt-in authorisation lapse and a decline on the billing fake, and the
point door refusing a zoneless (transferred) domain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 44d3292ff30cae42db09e7f46254726274f7243e parent edf0a3b
24 files changed, +3,919 −203
  • .amadan/code-health.tsv +1 −1
  • internal/billing/billingtest/fake.go +31 −1
  • internal/billing/billingtest/payment_test.go +75 −0
  • internal/console/accountdomainbuy.go +3 −3
  • internal/console/billingwebhook.go +2 −0
  • internal/console/dnsds.go +210 −0
  • internal/console/dnsds_test.go +179 −0
  • internal/console/domainalert.go +36 −0
  • internal/console/domainbuy.go +41 −190
  • internal/console/domainpoint.go +3 −1
  • internal/console/domainpurchase_shared.go +312 −0
  • internal/console/domainstore.go +4 −0
  • internal/console/domaintransfer.go +583 −0
  • internal/console/domaintransfer_copy.go +94 −0
  • internal/console/domaintransfer_decide.go +212 −0
  • internal/console/domaintransfer_decide_test.go +870 −0
  • internal/console/domaintransfer_facts.go +7 −2
  • internal/console/domaintransfer_resolve.go +130 −0
  • internal/console/domaintransfer_start.go +180 −0
  • internal/console/domaintransfer_test.go +919 −0
  • internal/console/jobs_test.go +5 −3
  • internal/console/routedecls.go +5 −0
  • internal/console/server.go +12 −0
  • internal/console/svcroutes_test.go +5 −2
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index 7b99e06ea..d03a4db10 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2222,7 +2222,7 @@ file-lines . apimode.go - 4184
file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals
file-lines internal/activator activator.go - 3783 # raised: #1290 step 2c, the call to protectBeforeStart (its body and interface live in replicatebeforestart.go)
file-lines internal/activator activator_test.go - 5471
-file-lines internal/console server.go - 4219 # raised: platform accounts pre-flight C1, the one line embedding platformSeams in Server
+file-lines internal/console server.go - 4223 # raised: domain transfers Task 6, Config.LookupNS, LookupDS and DNSServer (the brief puts them on Config) and the transfer engine clock seam on Server
file-lines internal/host agent.go - 3214
file-lines internal/provision reconcile_test.go - 3094
file-lines internal/registry registry_test.go - 3261
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go
index afae55113..3e1ab3bc6 100644
--- a/internal/billing/billingtest/fake.go
+++ b/internal/billing/billingtest/fake.go
@@ -231,6 +231,11 @@ type Fake struct {
// makes stays capturable (PaymentInfo.CaptureBefore): 0 is seven days,
// as for most cards; negative is a provider that does not say.
CaptureWindow time.Duration
+ // LapseAuthorisations, when set, makes an uncaptured authorisation
+ // lapse at its CaptureBefore, as a card's does: the PaymentIntent turns
+ // canceled and a capture refuses. Off by default (authorisations never
+ // lapse), so tests that do not ask for it are unchanged.
+ LapseAuthorisations bool
// BeforeSend, when set, runs at the start of every Send, outside the
// Fake's lock, after CrashBeforeSend is checked: something that happens
// at the provider just before the request arrives (a buyer completing a
@@ -452,6 +457,9 @@ func (f *Fake) settle() {
if s.Status == "open" && !now.Before(s.Request.ExpiresAt) {
s.Status = "expired"
}
+ if f.LapseAuthorisations && s.IntentStatus == "requires_capture" && !s.CaptureBefore.IsZero() && !now.Before(s.CaptureBefore) {
+ s.IntentStatus, s.Authorised = "canceled", false
+ }
}
for id, s := range f.Subs {
for i := range s.Items {
@@ -1590,7 +1598,9 @@ func (f *Fake) CompletePaymentCheckout(sessionID string) (string, error) {
return "", billing.ErrRefused
}
s.Status = "complete"
- s.PaymentIntent = f.nextID("pi")
+ if s.PaymentIntent == "" {
+ s.PaymentIntent = f.nextID("pi")
+ }
s.IntentStatus = "requires_capture"
s.Authorised = true
switch {
@@ -1602,6 +1612,26 @@ func (f *Fake) CompletePaymentCheckout(sessionID string) (string, error) {
return s.PaymentIntent, nil
}
+// DeclinePaymentCheckout simulates a buyer's card declined in an open
+// session: the session stays open, so the buyer may try again, and its
+// PaymentIntent needs a new payment method. A session that is not open
+// refuses.
+func (f *Fake) DeclinePaymentCheckout(sessionID string) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ f.settle()
+ s, ok := f.paymentSessions[sessionID]
+ if !ok || s.Status != "open" {
+ return billing.ErrRefused
+ }
+ if s.PaymentIntent == "" {
+ s.PaymentIntent = f.nextID("pi")
+ }
+ s.IntentStatus, s.Authorised = "requires_payment_method", false
+ return nil
+}
+
func (f *Fake) PrepareSetupCheckout(req billing.SetupCheckoutRequest) (billing.Prepared, error) {
if req.Customer == "" || req.AccountSqid == "" || req.SuccessURL == "" || req.CancelURL == "" {
return billing.Prepared{}, billing.ErrRefused
diff --git a/internal/billing/billingtest/payment_test.go b/internal/billing/billingtest/payment_test.go
index e58c60930..c12becd29 100644
--- a/internal/billing/billingtest/payment_test.go
+++ b/internal/billing/billingtest/payment_test.go
@@ -260,3 +260,78 @@ func TestFakeRefundLifecyclePendingToSucceededOrFailed(t *testing.T) {
})
}
}
+
+// TestFakeAuthorisationLapsesOnlyWhenAsked: by default an authorisation
+// never lapses; with LapseAuthorisations it turns canceled at its
+// CaptureBefore and a capture then refuses.
+func TestFakeAuthorisationLapsesOnlyWhenAsked(t *testing.T) {
+ for _, lapse := range []bool{false, true} {
+ f := newFake(t)
+ f.LapseAuthorisations = lapse
+ f.CaptureWindow = 48 * time.Hour
+ ctx := context.Background()
+ prep, err := f.PreparePaymentCheckout(fakePaymentRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ res, err := f.Send(ctx, prep)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pi, err := f.CompletePaymentCheckout(res.Payment.SessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.AdvanceProvider(48*time.Hour - time.Second)
+ if info, _ := f.PaymentCheckout(ctx, res.Payment.SessionID); info.IntentStatus != "requires_capture" {
+ t.Fatalf("lapse=%v: before the deadline: %+v", lapse, info)
+ }
+ f.AdvanceProvider(time.Second)
+ info, err := f.PaymentCheckout(ctx, res.Payment.SessionID)
+ want := "requires_capture"
+ if lapse {
+ want = "canceled"
+ }
+ if err != nil || info.IntentStatus != want || info.Authorised != !lapse {
+ t.Fatalf("lapse=%v: at the deadline: %+v %v", lapse, info, err)
+ }
+ capture, err := f.PrepareCapture(pi, "capture-key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = f.Send(ctx, capture)
+ if lapse != errors.Is(err, billing.ErrRefused) || (!lapse && err != nil) {
+ t.Fatalf("lapse=%v: capture: %v", lapse, err)
+ }
+ }
+}
+
+// TestFakeDeclineThenAuthoriseInSameSession: a declined card leaves the
+// session open with its PaymentIntent needing a payment method; a retry
+// in the same session authorises that same PaymentIntent.
+func TestFakeDeclineThenAuthoriseInSameSession(t *testing.T) {
+ f := newFake(t)
+ ctx := context.Background()
+ prep, err := f.PreparePaymentCheckout(fakePaymentRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ res, err := f.Send(ctx, prep)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.DeclinePaymentCheckout(res.Payment.SessionID); err != nil {
+ t.Fatal(err)
+ }
+ info, err := f.PaymentCheckout(ctx, res.Payment.SessionID)
+ if err != nil || info.Status != "open" || info.IntentStatus != "requires_payment_method" || info.Authorised || info.PaymentIntent == "" {
+ t.Fatalf("declined: %+v %v", info, err)
+ }
+ pi, err := f.CompletePaymentCheckout(res.Payment.SessionID)
+ if err != nil || pi != info.PaymentIntent {
+ t.Fatalf("retry: %q %v, want %q", pi, err, info.PaymentIntent)
+ }
+ if err := f.DeclinePaymentCheckout(res.Payment.SessionID); !errors.Is(err, billing.ErrRefused) {
+ t.Fatalf("decline after completion: %v", err)
+ }
+}
diff --git a/internal/console/accountdomainbuy.go b/internal/console/accountdomainbuy.go
index 970632777..3be80cb77 100644
--- a/internal/console/accountdomainbuy.go
+++ b/internal/console/accountdomainbuy.go
@@ -142,9 +142,9 @@ func (s *Server) buyStepQuote(ctx context.Context, acct *Account, name, country
if err != nil {
return domainreg.Quote{}, domainBuyErrorRefusal(err)
}
- own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
- if err != nil {
- return domainreg.Quote{}, domainBuyUnavailable()
+ own, ref := s.ownLivePurchaseOfKind(ctx, acct.ID, name, PurchaseKindBuy)
+ if ref != nil {
+ return domainreg.Quote{}, ref
}
if own != nil {
return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil
diff --git a/internal/console/billingwebhook.go b/internal/console/billingwebhook.go
index 8bab509fd..a20f84d15 100644
--- a/internal/console/billingwebhook.go
+++ b/internal/console/billingwebhook.go
@@ -75,6 +75,8 @@ func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) {
}
for _, p := range purchases {
if p.CheckoutSession == ev.Object {
+ // Either kind: the nudge only wakes the purchase pass, which
+ // sends a transfer to its own steps (advancePurchaseStep).
s.nudgePurchase(p.ID)
w.WriteHeader(http.StatusNoContent)
return
diff --git a/internal/console/dnsds.go b/internal/console/dnsds.go
new file mode 100644
index 000000000..92d094273
--- /dev/null
+++ b/internal/console/dnsds.go
@@ -0,0 +1,210 @@
+package console
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "slices"
+ "strings"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// dnsTypeDS is the DS record type (RFC 4034). dnsmessage has no constant
+// for it, so its answers are read as UnknownResource.
+const dnsTypeDS = dnsmessage.Type(43)
+
+const dsLookupTimeout = 5 * time.Second
+
+// lookupDS reports whether name has a DS record at its parent, asking
+// server (host:port) over UDP and again over TCP when the UDP answer is
+// truncated. NXDOMAIN and an empty answer are "no DS". Anything else that
+// is not a clean answer to this exact question is an error: SERVFAIL or
+// another failure code, a reply to a different ID or question, a reply
+// that does not parse, a timeout.
+func lookupDS(ctx context.Context, server string, name string) (bool, error) {
+ if server == "" {
+ return false, errors.New("console: DS lookup: no DNS server")
+ }
+ qname, err := dnsmessage.NewName(strings.TrimSuffix(name, ".") + ".")
+ if err != nil {
+ return false, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ var idb [2]byte
+ if _, err := rand.Read(idb[:]); err != nil {
+ return false, err
+ }
+ q := dnsmessage.Question{Name: qname, Type: dnsTypeDS, Class: dnsmessage.ClassINET}
+ query := dnsmessage.Message{Header: dnsmessage.Header{ID: binary.BigEndian.Uint16(idb[:]), RecursionDesired: true}, Questions: []dnsmessage.Question{q}}
+ packed, err := query.Pack()
+ if err != nil {
+ return false, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ if _, ok := ctx.Deadline(); !ok {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, dsLookupTimeout)
+ defer cancel()
+ }
+ reply, err := dnsExchange(ctx, "udp", server, packed)
+ if err != nil {
+ return false, err
+ }
+ found, truncated, err := dsAnswer(reply, query.ID, q)
+ if err != nil || !truncated {
+ return found, err
+ }
+ reply, err = dnsExchange(ctx, "tcp", server, packed)
+ if err != nil {
+ return false, err
+ }
+ found, truncated, err = dsAnswer(reply, query.ID, q)
+ if err == nil && truncated {
+ err = errors.New("console: DS lookup: truncated answer over TCP")
+ }
+ return found, err
+}
+
+// dnsExchange sends one query and reads one reply.
+func dnsExchange(ctx context.Context, network, server string, query []byte) ([]byte, error) {
+ var d net.Dialer
+ c, err := d.DialContext(ctx, network, server)
+ if err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ defer c.Close()
+ if deadline, ok := ctx.Deadline(); ok {
+ if err := c.SetDeadline(deadline); err != nil {
+ return nil, err
+ }
+ }
+ if network == "tcp" {
+ msg := binary.BigEndian.AppendUint16(nil, uint16(len(query)))
+ if _, err := c.Write(append(msg, query...)); err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ var l [2]byte
+ if _, err := io.ReadFull(c, l[:]); err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ reply := make([]byte, binary.BigEndian.Uint16(l[:]))
+ if _, err := io.ReadFull(c, reply); err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ return reply, nil
+ }
+ if _, err := c.Write(query); err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ buf := make([]byte, 65535)
+ n, err := c.Read(buf)
+ if err != nil {
+ return nil, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ return buf[:n], nil
+}
+
+// dsAnswer reads a reply to q: whether it holds a DS for q's name, and
+// whether it was truncated.
+func dsAnswer(reply []byte, id uint16, q dnsmessage.Question) (found, truncated bool, err error) {
+ var p dnsmessage.Parser
+ h, err := p.Start(reply)
+ if err != nil {
+ return false, false, fmt.Errorf("console: DS lookup: malformed reply: %w", err)
+ }
+ if !h.Response || h.ID != id {
+ return false, false, errors.New("console: DS lookup: reply is not an answer to this query")
+ }
+ qs, err := p.AllQuestions()
+ if err != nil {
+ return false, false, fmt.Errorf("console: DS lookup: malformed reply: %w", err)
+ }
+ if len(qs) != 1 || qs[0].Type != q.Type || qs[0].Class != q.Class || !strings.EqualFold(qs[0].Name.String(), q.Name.String()) {
+ return false, false, errors.New("console: DS lookup: reply is for another question")
+ }
+ if h.Truncated {
+ return false, true, nil
+ }
+ switch h.RCode {
+ case dnsmessage.RCodeSuccess:
+ case dnsmessage.RCodeNameError:
+ return false, false, nil
+ default:
+ return false, false, fmt.Errorf("console: DS lookup: %v", h.RCode)
+ }
+ for {
+ a, err := p.AnswerHeader()
+ if errors.Is(err, dnsmessage.ErrSectionDone) {
+ break
+ }
+ if err != nil {
+ return false, false, fmt.Errorf("console: DS lookup: malformed reply: %w", err)
+ }
+ if a.Type == dnsTypeDS && a.Class == dnsmessage.ClassINET && strings.EqualFold(a.Name.String(), q.Name.String()) {
+ found = true
+ }
+ if err := p.SkipAnswer(); err != nil {
+ return false, false, fmt.Errorf("console: DS lookup: malformed reply: %w", err)
+ }
+ }
+ return found, false, nil
+}
+
+// resolvConfServer is the first nameserver in a resolv.conf body, as
+// host:port, or "".
+func resolvConfServer(body string) string {
+ for _, line := range strings.Split(body, "\n") {
+ f := strings.Fields(line)
+ if len(f) >= 2 && f[0] == "nameserver" {
+ return net.JoinHostPort(f[1], "53")
+ }
+ }
+ return ""
+}
+
+// lookupDomainDS is Config.LookupDS, defaulting to lookupDS against
+// Config.DNSServer, else the system's first nameserver.
+func (s *Server) lookupDomainDS(ctx context.Context, name string) (bool, error) {
+ if s.cfg.LookupDS != nil {
+ return s.cfg.LookupDS(ctx, name)
+ }
+ server := s.cfg.DNSServer
+ if server == "" {
+ b, err := os.ReadFile("/etc/resolv.conf")
+ if err != nil {
+ return false, fmt.Errorf("console: DS lookup: %w", err)
+ }
+ server = resolvConfServer(string(b))
+ }
+ return lookupDS(ctx, server, name)
+}
+
+// lookupDomainNS is the domain's nameservers from public DNS (Config.LookupNS,
+// defaulting to the system resolver): lower case, no trailing dot, sorted,
+// without duplicates.
+func (s *Server) lookupDomainNS(ctx context.Context, name string) ([]string, error) {
+ lookup := s.cfg.LookupNS
+ if lookup == nil {
+ lookup = net.DefaultResolver.LookupNS
+ }
+ records, err := lookup(ctx, name)
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, r := range records {
+ if r == nil {
+ continue
+ }
+ if host := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(r.Host)), "."); host != "" {
+ out = append(out, host)
+ }
+ }
+ slices.Sort(out)
+ return slices.Compact(out), nil
+}
diff --git a/internal/console/dnsds_test.go b/internal/console/dnsds_test.go
new file mode 100644
index 000000000..ab6077589
--- /dev/null
+++ b/internal/console/dnsds_test.go
@@ -0,0 +1,179 @@
+package console
+
+import (
+ "context"
+ "encoding/binary"
+ "io"
+ "net"
+ "strconv"
+ "testing"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// dsResponder is a local DNS server on 127.0.0.1 answering UDP and TCP on
+// the same ephemeral port. answer builds the reply to a parsed query; nil
+// sends nothing (a timeout).
+type dsResponder struct {
+ addr string
+ udp net.PacketConn
+ tcp net.Listener
+}
+
+func newDSResponder(t *testing.T, udpAnswer, tcpAnswer func(q dnsmessage.Message) []byte) *dsResponder {
+ t.Helper()
+ var r dsResponder
+ for try := 0; ; try++ {
+ udp, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ port := udp.LocalAddr().(*net.UDPAddr).Port
+ tcp, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
+ if err != nil {
+ udp.Close()
+ if try < 20 {
+ continue
+ }
+ t.Fatal(err)
+ }
+ r = dsResponder{addr: udp.LocalAddr().String(), udp: udp, tcp: tcp}
+ break
+ }
+ t.Cleanup(func() { r.udp.Close(); r.tcp.Close() })
+ go func() {
+ buf := make([]byte, 1500)
+ for {
+ n, from, err := r.udp.ReadFrom(buf)
+ if err != nil {
+ return
+ }
+ var q dnsmessage.Message
+ if q.Unpack(buf[:n]) != nil {
+ continue
+ }
+ if reply := udpAnswer(q); reply != nil {
+ _, _ = r.udp.WriteTo(reply, from)
+ }
+ }
+ }()
+ go func() {
+ for {
+ c, err := r.tcp.Accept()
+ if err != nil {
+ return
+ }
+ go func() {
+ defer c.Close()
+ var l [2]byte
+ if _, err := io.ReadFull(c, l[:]); err != nil {
+ return
+ }
+ b := make([]byte, binary.BigEndian.Uint16(l[:]))
+ if _, err := io.ReadFull(c, b); err != nil {
+ return
+ }
+ var q dnsmessage.Message
+ if q.Unpack(b) != nil || tcpAnswer == nil {
+ return
+ }
+ reply := tcpAnswer(q)
+ binary.BigEndian.PutUint16(l[:], uint16(len(reply)))
+ _, _ = c.Write(append(l[:], reply...))
+ }()
+ }
+ }()
+ return &r
+}
+
+// dsReply answers q with rcode and, when withDS, one DS record for the
+// question's name. edit may change the message before packing.
+func dsReply(q dnsmessage.Message, rcode dnsmessage.RCode, withDS bool, edit func(*dnsmessage.Message)) []byte {
+ m := dnsmessage.Message{Header: dnsmessage.Header{ID: q.ID, Response: true, RecursionDesired: true, RecursionAvailable: true, RCode: rcode},
+ Questions: q.Questions}
+ if withDS {
+ m.Answers = []dnsmessage.Resource{{
+ Header: dnsmessage.ResourceHeader{Name: q.Questions[0].Name, Type: dnsTypeDS, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.UnknownResource{Type: dnsTypeDS, Data: []byte{0x30, 0x39, 13, 2, 0xde, 0xad, 0xbe, 0xef}},
+ }}
+ }
+ if edit != nil {
+ edit(&m)
+ }
+ b, err := m.Pack()
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
+
+func TestLookupDSAnswersAndFailures(t *testing.T) {
+ cases := []struct {
+ name string
+ udp func(q dnsmessage.Message) []byte
+ tcp func(q dnsmessage.Message) []byte
+ want bool
+ wantErr bool
+ }{
+ {name: "DS present", udp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeSuccess, true, nil) }, want: true},
+ {name: "NODATA", udp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeSuccess, false, nil) }},
+ {name: "NXDOMAIN", udp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeNameError, false, nil) }},
+ {name: "SERVFAIL", udp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeServerFailure, false, nil) }, wantErr: true},
+ {name: "mismatched ID", udp: func(q dnsmessage.Message) []byte {
+ return dsReply(q, dnsmessage.RCodeSuccess, true, func(m *dnsmessage.Message) { m.ID++ })
+ }, wantErr: true},
+ {name: "mismatched question", udp: func(q dnsmessage.Message) []byte {
+ return dsReply(q, dnsmessage.RCodeSuccess, true, func(m *dnsmessage.Message) {
+ m.Questions = []dnsmessage.Question{{Name: dnsmessage.MustNewName("other.com."), Type: dnsTypeDS, Class: dnsmessage.ClassINET}}
+ })
+ }, wantErr: true},
+ {name: "not a response", udp: func(q dnsmessage.Message) []byte {
+ return dsReply(q, dnsmessage.RCodeSuccess, true, func(m *dnsmessage.Message) { m.Response = false })
+ }, wantErr: true},
+ {name: "malformed", udp: func(q dnsmessage.Message) []byte {
+ b := dsReply(q, dnsmessage.RCodeSuccess, true, nil)
+ return b[:len(b)-6]
+ }, wantErr: true},
+ {name: "timeout", udp: func(q dnsmessage.Message) []byte { return nil }, wantErr: true},
+ {name: "truncated UDP, then TCP", udp: func(q dnsmessage.Message) []byte {
+ return dsReply(q, dnsmessage.RCodeSuccess, false, func(m *dnsmessage.Message) { m.Truncated = true })
+ }, tcp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeSuccess, true, nil) }, want: true},
+ {name: "truncated UDP, TCP answers NODATA", udp: func(q dnsmessage.Message) []byte {
+ return dsReply(q, dnsmessage.RCodeSuccess, true, func(m *dnsmessage.Message) { m.Truncated = true })
+ }, tcp: func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeSuccess, false, nil) }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ r := newDSResponder(t, c.udp, c.tcp)
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+ got, err := lookupDS(ctx, r.addr, "Shop.com")
+ if (err != nil) != c.wantErr || got != c.want {
+ t.Fatalf("lookupDS = %v, %v; want %v, error %v", got, err, c.want, c.wantErr)
+ }
+ })
+ }
+
+ // The server's default reads Config.DNSServer; LookupDS replaces it.
+ r := newDSResponder(t, func(q dnsmessage.Message) []byte { return dsReply(q, dnsmessage.RCodeSuccess, true, nil) }, nil)
+ s := &Server{cfg: Config{DNSServer: r.addr}}
+ if got, err := s.lookupDomainDS(context.Background(), "shop.com"); err != nil || !got {
+ t.Fatalf("server DS lookup = %v, %v", got, err)
+ }
+ if _, err := lookupDS(context.Background(), "", "shop.com"); err == nil {
+ t.Fatal("no server: no error")
+ }
+}
+
+func TestResolvConfServer(t *testing.T) {
+ for in, want := range map[string]string{
+ "# comment\nsearch example.test\nnameserver 192.0.2.53\nnameserver 192.0.2.54\n": "192.0.2.53:53",
+ "nameserver 2001:db8::53\n": "[2001:db8::53]:53",
+ "search example.test\n": "",
+ } {
+ if got := resolvConfServer(in); got != want {
+ t.Errorf("resolvConfServer(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/internal/console/domainalert.go b/internal/console/domainalert.go
new file mode 100644
index 000000000..38842632f
--- /dev/null
+++ b/internal/console/domainalert.go
@@ -0,0 +1,36 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "log"
+
+ "github.com/carlosframework/platform/internal/alerting"
+)
+
+// pageDomainPurchase is the operator paging sink domain purchases and
+// transfers use. A TEST SEAM.
+var pageDomainPurchase = alerting.Page
+
+// alertOperator pages the operator and says whether the page was delivered:
+// a nil error is delivered (or, with no sink configured at all, logged by
+// alerting as undeliverable once and treated as sent, so an unconfigured
+// console never retries forever). A caller that must alert exactly once
+// records the alert only when this returns nil, and tries again otherwise.
+func (s *Server) alertOperator(ctx context.Context, subject, body string) error {
+ if err := pageDomainPurchase(ctx, alerting.LevelWarning, subject, body); err != nil {
+ return fmt.Errorf("operator alert: %w", err)
+ }
+ return nil
+}
+
+// purchaseAlert is the best-effort alert: it logs the reason, pages, and
+// logs (and fails the job on) a page that was not delivered.
+func (s *Server) purchaseAlert(ctx context.Context, acct *Account, domain, id, reason string) {
+ log.Printf("console: domain purchase: account=%s domain=%s purchase=%s reason=%s", acct.Sqid, domain, id, reason)
+ body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, domain, id, acct.Sqid, reason)
+ if err := s.alertOperator(ctx, domainPurchaseCopy.OperatorSubject, body); err != nil {
+ log.Printf("console: purchase %s: %v", id, err)
+ jobFailed(ctx, err)
+ }
+}
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go
index 328d92410..e1bb1a437 100644
--- a/internal/console/domainbuy.go
+++ b/internal/console/domainbuy.go
@@ -7,16 +7,13 @@ import (
"fmt"
"log"
"net/http"
- "os"
"time"
- "github.com/carlosframework/platform/internal/alerting"
"github.com/carlosframework/platform/internal/billing"
"github.com/carlosframework/platform/internal/domainreg"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/registrar"
"github.com/carlosframework/platform/internal/zonehost"
- "golang.org/x/net/publicsuffix"
)
func (s *Server) domainBuyReady() bool {
@@ -43,88 +40,37 @@ func domainBuyUnavailable() *doorRefusal {
// §8): buying creates a payment customer, and a linked account never gets
// one. Every caller has already answered 404 when buying is off.
func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string, country ...string) (domainreg.Quote, *doorRefusal) {
- if ref := s.linkedDomainBuyRefusal(ctx, acct); ref != nil {
- return domainreg.Quote{}, ref
- }
- 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)
- }
+ a, ref := s.admitDomainDoor(ctx, acct, name, PurchaseKindBuy, country...)
+ if ref != nil {
return domainreg.Quote{}, ref
}
- name, err := domainreg.Normalize(name)
- if err != nil {
- return domainreg.Quote{}, domainBuyErrorRefusal(err)
- }
- own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
- if err != nil {
- return domainreg.Quote{}, domainBuyUnavailable()
- }
- if own != nil {
- return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil
- }
- b, err := s.store.BillingAccount(acct.ID)
- if err != nil {
- 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)
- }
+ if a.own != nil {
+ return domainreg.Quote{Domain: a.own.Domain, Currency: a.own.Currency, Price: a.own.Amount}, nil
}
- suffix, _ := publicsuffix.PublicSuffix(name)
- tld, offered := s.cfg.DomainCatalog.TLDs[suffix]
- if !offered {
+ name, currency, suffix := a.name, a.currency, a.suffix
+ if !a.offered {
return domainreg.Quote{}, domainBuyErrorRefusal(domainreg.ErrTLDNotOffered)
}
- if tld.Register[currency] <= 0 {
+ if a.tld.Register[currency] <= 0 {
return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
}
if !s.domainChecks.allow(acct.ID) {
return domainreg.Quote{}, &doorRefusal{Status: http.StatusTooManyRequests, Msg: domainBuyCopy["rate"]}
}
- a, err := s.cfg.Registrar.Check(ctx, name)
+ av, err := s.cfg.Registrar.Check(ctx, name)
if err != nil {
return domainreg.Quote{}, s.domainBuyRegistrarRefusal(ctx, acct, name, err)
}
- if !a.Available {
+ if !av.Available {
return domainreg.Quote{}, claimRefusal(name, domains.ErrHostUnavailable)
}
- for _, host := range []string{name, "www." + name} {
- if s.domainHostDenied(host, acct.Sqid) {
- return domainreg.Quote{}, claimRefusal(host, domains.ErrHostUnavailable)
- }
- if ref := s.heldElsewhere(ctx, host, acct.Sqid, ""); ref != nil {
- if ref.Status == http.StatusConflict {
- log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name)
- }
- return domainreg.Quote{}, ref
- }
- _, err := domains.GetClaim(ctx, s.cfg.Releases, host)
- if err == nil {
- log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name)
- return domainreg.Quote{}, claimRefusal(host, domains.ErrHostUnavailable)
- }
- if !errors.Is(err, os.ErrNotExist) {
- return domainreg.Quote{}, domainBuyUnavailable()
- }
+ if ref := s.domainHostsRefusal(ctx, acct, name, PurchaseKindBuy); ref != nil {
+ return domainreg.Quote{}, ref
}
if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil {
return domainreg.Quote{}, ref
}
- q, err := s.cfg.DomainCatalog.Quote(name, currency, a)
+ q, err := s.cfg.DomainCatalog.Quote(name, currency, av)
if errors.Is(err, domainreg.ErrCostAboveCeiling) {
s.purchaseRefusalAlert(ctx, acct, name, "cost:"+suffix, "registrar cost above ceiling")
}
@@ -178,9 +124,9 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
return nil, "", nil, ref
}
name = q.Domain
- own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
- if err != nil {
- return nil, "", nil, domainBuyUnavailable()
+ own, ref := s.ownLivePurchaseOfKind(ctx, acct.ID, name, PurchaseKindBuy)
+ if ref != nil {
+ return nil, "", nil, ref
}
if own != nil {
if confirmed.Currency != q.Currency || confirmed.Price != q.Price {
@@ -208,76 +154,9 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
if !contactOK || c.Validate() != nil {
return nil, "", nil, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["contactError"]}
}
- h, release, err := s.holdBilling(acct)
- if err != nil {
- return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
- }
- // Choose and confirm under the same hold that creates the customer. A
- // subscription may have fixed currency since admission read the account.
- b, err := s.store.BillingAccount(acct.ID)
- if err != nil {
- release()
- return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
- }
- if b != nil && b.Currency != "" {
- q.Currency = b.Currency
- }
- q.Price = s.cfg.DomainCatalog.TLDs[q.TLD].Register[q.Currency]
- if q.Price <= 0 {
- release()
- return nil, "", nil, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
- }
- if confirmed.Currency != q.Currency || confirmed.Price != q.Price {
- release()
- return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict)
- }
- count, err := s.store.PurchasesToday(acct.ID, time.Now())
- if err != nil {
- release()
- return nil, "", nil, domainBuyUnavailable()
- }
- if count >= s.cfg.DomainCatalog.DailyCap {
- release()
- return nil, "", nil, &doorRefusal{Status: http.StatusTooManyRequests, Msg: domainPurchaseCopy.DailyCap}
- }
- balance, err := s.cfg.Registrar.Balance(ctx)
- if err != nil {
- release()
- return nil, "", 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")
- release()
- return nil, "", nil, domainBuyUnavailable()
- }
- _, err = s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true)
- if err != nil {
- release()
- log.Printf("console: domain buy billing %s: %v", acct.Sqid, err)
- return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
- }
- 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 {
- return nil, "", nil, domainBuyUnavailable()
- }
- if own != nil {
- if confirmed.Currency != own.Currency || confirmed.Price != own.Amount {
- changed := domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}
- return nil, "", &changed, domainBuyStateRefusal("priceChanged", http.StatusConflict)
- }
- p, link, ref := s.resumeDomainPurchase(ctx, own)
- return p, link, nil, ref
- }
- return nil, "", nil, claimRefusal(name, domains.ErrHostUnavailable)
- }
- if err != nil {
- return nil, "", nil, domainBuyUnavailable()
- }
- purchase, link, ref := s.resumeDomainPurchase(ctx, p)
- return purchase, link, nil, ref
+ tld := q.TLD
+ return s.startPurchaseCheckout(ctx, acct, purchaseStart{Kind: PurchaseKindBuy, App: app, Principal: principal, Confirmed: confirmed,
+ Contact: c, Saved: saved, Price: func(currency string) int64 { return s.cfg.DomainCatalog.TLDs[tld].Register[currency] }}, q)
}
// insertDomainPurchaseLocked writes the purchase row under the account's
@@ -290,7 +169,8 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
// (unless an equal one is already saved, which is used instead) 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) {
+func (s *Server) insertDomainPurchaseLocked(ctx context.Context, acct *Account, ps purchaseStart, q domainreg.Quote) (*DomainPurchase, error) {
+ app, c, saved := ps.App, ps.Contact, ps.Saved
if domainPurchaseBeforeInsert != nil {
domainPurchaseBeforeInsert(ctx, s, acct)
}
@@ -309,7 +189,8 @@ func (s *Server) insertDomainPurchaseLocked(ctx context.Context, acct *Account,
if retiring {
return nil, errAccountGoneOrRetiring
}
- details := purchaseDetails{Principal: principal, Contact: c}
+ details := ps.Details
+ details.Principal, details.Contact = ps.Principal, c
added := false
if saved == nil {
// A new contact equal, field for field, to a saved one is that one:
@@ -334,7 +215,7 @@ func (s *Server) insertDomainPurchaseLocked(ctx context.Context, acct *Account,
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,
+ p := DomainPurchase{ID: newDomainPurchaseID(), Kind: ps.Kind, 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) })
@@ -409,6 +290,17 @@ func (s *Server) resumeDomainPurchase(ctx context.Context, p *DomainPurchase) (*
}
func (s *Server) movePurchase(ctx context.Context, p *DomainPurchase, to PurchaseState, set func(*DomainPurchase)) error {
+ if purchaseKindOf(p) == PurchaseKindTransfer && to != PurchaseAwaitingPayment && to != PurchaseAuthorised {
+ // The auth code goes in the move that submits, and on every terminal
+ // path before it, whoever makes the move.
+ inner := set
+ set = func(p *DomainPurchase) {
+ if inner != nil {
+ inner(p)
+ }
+ p.AuthCode = ""
+ }
+ }
err := s.store.withAutoAppSQL(ctx, p.AccountID, p.App, "sql.AdvanceDomainPurchase", func(st *Store) error { return st.compareDomainPurchase(*p, to, set) })
if err != nil {
return err
@@ -620,6 +512,10 @@ func (s *Server) advancePurchase(ctx context.Context, id string) error {
}
func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *DomainPurchase) error {
+ if purchaseKindOf(p) == PurchaseKindTransfer {
+ // A transfer never reaches a buy step: no zone, no registration.
+ return s.advanceTransferStep(ctx, acct, p)
+ }
provider := s.billing.cfg.Provider
switch p.State {
case PurchaseAwaitingPayment:
@@ -981,27 +877,9 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error
}
func (s *Server) registeredPurchase(ctx context.Context, p *DomainPurchase, r registrar.Registered) error {
- if r.Domain != p.Domain || r.RegistrarID == "" {
- return registrar.ErrIndeterminate
- }
// Insert before advancing; after a crash the matching row is the same registration.
- // 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.QueryRowContext(ctx, `SELECT account_id,registrar_id,zone_id FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&account, &registrarID, &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
- }
+ if err := s.recordPurchaseRegistration(ctx, p, r, p.ZoneID, true); err != nil {
+ return err
}
return s.movePurchase(ctx, p, PurchaseRegistered, func(p *DomainPurchase) { p.RegistrarID = r.RegistrarID; p.Reason = "" })
}
@@ -1112,35 +990,8 @@ func (s *Server) domainPurchasePass(ctx context.Context) error {
return errors.Join(errs...)
}
-var pageDomainPurchase = alerting.Page
-
-func (s *Server) purchaseAlert(ctx context.Context, acct *Account, domain, id, reason string) {
- log.Printf("console: domain purchase: account=%s domain=%s purchase=%s reason=%s", acct.Sqid, domain, id, reason)
- body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, domain, id, acct.Sqid, reason)
- if err := pageDomainPurchase(ctx, alerting.LevelWarning, domainPurchaseCopy.OperatorSubject, body); err != nil {
- log.Printf("console: purchase %s: operator alert: %v", id, err)
- jobFailed(ctx, err)
- }
-}
-
func (s *Server) purchaseOwnerNotice(ctx context.Context, acct *Account, p *DomainPurchase) {
- members, err := s.store.Members(acct.ID)
- if err != nil {
- log.Printf("console: purchase %s: owners: %v", p.ID, err)
- jobFailed(ctx, err)
- return
- }
- subject := fmt.Sprintf(domainPurchaseCopy.UnpaidSubject, p.Domain)
- body := domainPurchaseCopy.UnpaidBody
- for _, member := range members {
- if member.Role != RoleOwner {
- continue
- }
- if _, err := s.deliver(ctx, member.Name, subject, body, 8*time.Second); err != nil {
- log.Printf("console: purchase %s: owner notice: %v", p.ID, err)
- jobFailed(ctx, err)
- }
- }
+ s.ownerNotice(ctx, acct, p.ID, fmt.Sprintf(domainPurchaseCopy.UnpaidSubject, p.Domain), domainPurchaseCopy.UnpaidBody)
}
func (s *Server) purchaseRefusalAlert(ctx context.Context, acct *Account, name, key, reason string) {
diff --git a/internal/console/domainpoint.go b/internal/console/domainpoint.go
index f4d18d589..e55a5c9ec 100644
--- a/internal/console/domainpoint.go
+++ b/internal/console/domainpoint.go
@@ -139,7 +139,9 @@ func (s *Server) pointBoughtDomain(ctx context.Context, acct *Account, app, doma
log.Printf("console: point %s/%s %s: registration: %v", acct.Sqid, app, domain, err)
return false, pointUnavailable()
}
- if reg == nil {
+ if reg == nil || reg.ZoneID == "" {
+ // A transferred domain has no zone here (its DNS is hosted
+ // elsewhere), so there is nothing to point: the attach door is its way.
return false, &doorRefusal{Status: http.StatusNotFound}
}
live, err := s.ownLiveDomainPurchase(ctx, acct.ID, domain)
diff --git a/internal/console/domainpurchase_shared.go b/internal/console/domainpurchase_shared.go
new file mode 100644
index 000000000..eae4ac4db
--- /dev/null
+++ b/internal/console/domainpurchase_shared.go
@@ -0,0 +1,312 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "log"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domainreg"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/registrar"
+ "golang.org/x/net/publicsuffix"
+)
+
+// What buying a domain and transferring one in share: admission, the
+// kind-aware resume, the claim checks, the start under the billing hold,
+// recording a registration, and the owner's email.
+
+// purchaseKindOf is p's kind; a row written before kinds is a buy.
+func purchaseKindOf(p *DomainPurchase) PurchaseKind {
+ if p.Kind == "" {
+ return PurchaseKindBuy
+ }
+ return p.Kind
+}
+
+// purchaseUnavailable is the kind's "unavailable right now" refusal.
+func purchaseUnavailable(kind PurchaseKind) *doorRefusal {
+ if kind == PurchaseKindTransfer {
+ return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: domainTransferCopy["unavailable"]}
+ }
+ return domainBuyUnavailable()
+}
+
+// domainAdmission is what admitDomainDoor established: the normalised name,
+// the account's currency, and the name's TLD in the catalog (offered false
+// when it is not there). own is the owner's live purchase of the name, of
+// this kind, which the caller resumes at its stored price.
+type domainAdmission struct {
+ name, currency, suffix string
+ tld domainreg.TLD
+ offered bool
+ own *DomainPurchase
+}
+
+// admitDomainDoor is the start of every buy and transfer door after owner
+// or person authorization, in this order: a linked account is refused
+// (platform accounts spec §8: starting creates a payment customer, and a
+// linked account never gets one); 404 when buying is off; the custom-domain
+// entitlement; the name; the owner's live purchase of it (of another kind:
+// the neutral refusal, never a resume); the currency; the TLD.
+func (s *Server) admitDomainDoor(ctx context.Context, acct *Account, name string, kind PurchaseKind, country ...string) (domainAdmission, *doorRefusal) {
+ if ref := s.linkedDomainBuyRefusal(ctx, acct); ref != nil {
+ return domainAdmission{}, ref
+ }
+ if !s.domainBuyReady() {
+ return domainAdmission{}, &doorRefusal{Status: http.StatusNotFound}
+ }
+ if ref := s.customDomainRefusal(acct, name); ref != nil {
+ if ref.Status == http.StatusConflict {
+ return domainAdmission{}, domainBuyStateRefusal("plan", http.StatusConflict)
+ }
+ return domainAdmission{}, ref
+ }
+ name, err := domainreg.Normalize(name)
+ if err != nil {
+ return domainAdmission{}, domainBuyErrorRefusal(err)
+ }
+ own, ref := s.ownLivePurchaseOfKind(ctx, acct.ID, name, kind)
+ if ref != nil {
+ return domainAdmission{}, ref
+ }
+ if own != nil {
+ return domainAdmission{name: name, own: own}, nil
+ }
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return domainAdmission{}, 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 domainAdmission{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ }
+ suffix, _ := publicsuffix.PublicSuffix(name)
+ tld, offered := s.cfg.DomainCatalog.TLDs[suffix]
+ return domainAdmission{name: name, currency: currency, suffix: suffix, tld: tld, offered: offered}, nil
+}
+
+// ownLivePurchaseOfKind is the account's live purchase of name when it is of
+// kind. A live purchase of the other kind is the neutral refusal: a buy
+// never resumes a transfer, nor a transfer a buy.
+func (s *Server) ownLivePurchaseOfKind(ctx context.Context, account int64, name string, kind PurchaseKind) (*DomainPurchase, *doorRefusal) {
+ own, err := s.ownLiveDomainPurchase(ctx, account, name)
+ if err != nil {
+ return nil, purchaseUnavailable(kind)
+ }
+ if own != nil && purchaseKindOf(own) != kind {
+ log.Printf("console: domain purchase: domain=%s reason=a live purchase of another kind", name)
+ return nil, claimRefusal(name, domains.ErrHostUnavailable)
+ }
+ return own, nil
+}
+
+// domainHostsRefusal checks the apex and www against platform names and
+// existing claims. Buying refuses every existing claim. A transfer refuses
+// only another account's: this account's own claims (its apps', live, in
+// Trash or purged) are expected on a domain registered elsewhere, and the
+// transfer leaves them alone (spec §12.3, builder check T4).
+func (s *Server) domainHostsRefusal(ctx context.Context, acct *Account, name string, kind PurchaseKind) *doorRefusal {
+ for _, host := range []string{name, "www." + name} {
+ if s.domainHostDenied(host, acct.Sqid) {
+ return claimRefusal(host, domains.ErrHostUnavailable)
+ }
+ if kind == PurchaseKindTransfer {
+ c, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return purchaseUnavailable(kind)
+ }
+ if err == nil && c != nil && c.Account == acct.Sqid {
+ continue
+ }
+ if ref := s.heldElsewhere(ctx, host, acct.Sqid, ""); ref != nil {
+ return ref
+ }
+ if err == nil {
+ log.Printf("console: domain transfer: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name)
+ return claimRefusal(host, domains.ErrHostUnavailable)
+ }
+ continue
+ }
+ if ref := s.heldElsewhere(ctx, host, acct.Sqid, ""); ref != nil {
+ if ref.Status == http.StatusConflict {
+ log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name)
+ }
+ return ref
+ }
+ _, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ if err == nil {
+ log.Printf("console: domain purchase: account=%s domain=%s reason=claim held elsewhere", acct.Sqid, name)
+ return claimRefusal(host, domains.ErrHostUnavailable)
+ }
+ if !errors.Is(err, os.ErrNotExist) {
+ return domainBuyUnavailable()
+ }
+ }
+ return nil
+}
+
+// purchaseStart is a start that passed admission and its own checks.
+type purchaseStart struct {
+ Kind PurchaseKind
+ App, Principal string
+ Confirmed domainreg.Quote
+ Contact registrar.Contact
+ Saved *SavedContact
+ Price func(currency string) int64 // the catalog's price for this kind
+ Details purchaseDetails // kind-specific details; the contact fields are set on insert
+}
+
+// startPurchaseCheckout is the start's second half: under the billing hold
+// it confirms the currency and price, applies the daily cap and the
+// registrar balance, creates the payment customer, writes the purchase and
+// opens its Checkout. A concurrent start of the same name resumes the
+// winner's purchase when it is of this kind.
+func (s *Server) startPurchaseCheckout(ctx context.Context, acct *Account, ps purchaseStart, q domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) {
+ name := q.Domain
+ h, release, err := s.holdBilling(acct)
+ if err != nil {
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ }
+ // Choose and confirm under the same hold that creates the customer. A
+ // subscription may have fixed currency since admission read the account.
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ release()
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ }
+ if b != nil && b.Currency != "" {
+ q.Currency = b.Currency
+ }
+ q.Price = ps.Price(q.Currency)
+ if q.Price <= 0 {
+ release()
+ return nil, "", nil, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ if ps.Confirmed.Currency != q.Currency || ps.Confirmed.Price != q.Price {
+ release()
+ return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict)
+ }
+ count, err := s.store.PurchasesToday(acct.ID, time.Now())
+ if err != nil {
+ release()
+ return nil, "", nil, purchaseUnavailable(ps.Kind)
+ }
+ if count >= s.cfg.DomainCatalog.DailyCap {
+ release()
+ return nil, "", nil, &doorRefusal{Status: http.StatusTooManyRequests, Msg: domainPurchaseCopy.DailyCap}
+ }
+ balance, err := s.cfg.Registrar.Balance(ctx)
+ if err != nil {
+ release()
+ return nil, "", 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")
+ release()
+ return nil, "", nil, purchaseUnavailable(ps.Kind)
+ }
+ _, err = s.paymentCustomerLocked(h, s.billingClock(ctx), acct, ps.Contact.Country, ps.Contact.PostalCode, true)
+ if err != nil {
+ release()
+ log.Printf("console: domain buy billing %s: %v", acct.Sqid, err)
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ }
+ p, err := s.insertDomainPurchaseLocked(ctx, acct, ps, q)
+ release()
+ if errors.Is(err, ErrDomainPurchaseLive) {
+ own, ref := s.ownLivePurchaseOfKind(ctx, acct.ID, name, ps.Kind)
+ if ref != nil {
+ return nil, "", nil, ref
+ }
+ if own != nil {
+ if ps.Confirmed.Currency != own.Currency || ps.Confirmed.Price != own.Amount {
+ changed := domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}
+ return nil, "", &changed, domainBuyStateRefusal("priceChanged", http.StatusConflict)
+ }
+ p, link, ref := s.resumeDomainPurchase(ctx, own)
+ return p, link, nil, ref
+ }
+ return nil, "", nil, claimRefusal(name, domains.ErrHostUnavailable)
+ }
+ if err != nil {
+ return nil, "", nil, purchaseUnavailable(ps.Kind)
+ }
+ purchase, link, ref := s.resumeDomainPurchase(ctx, p)
+ return purchase, link, nil, ref
+}
+
+// recordPurchaseRegistration records r as p's registration, idempotently:
+// when an earlier attempt already wrote the same registration (same
+// account, registrar ID and zone), that row stands, given the frozen
+// registrant if it predates registrants. zoneID is "" for a transferred
+// domain, which has no hosted zone. The registrant is the purchase's frozen
+// contact, never the saved one.
+func (s *Server) recordPurchaseRegistration(ctx context.Context, p *DomainPurchase, r registrar.Registered, zoneID string, autoRenew bool) error {
+ if r.Domain != p.Domain || r.RegistrarID == "" {
+ return registrar.ErrIndeterminate
+ }
+ err := s.store.AddDomainRegistration(DomainRegistration{Domain: p.Domain, AccountID: p.AccountID, RegistrarID: r.RegistrarID, ZoneID: zoneID, Expires: r.Expires, AutoRenew: autoRenew, Registrant: p.Contact})
+ if err == nil {
+ return nil
+ }
+ var account int64
+ var registrarID, storedZone string
+ readErr := s.store.db.QueryRowContext(ctx, `SELECT account_id,registrar_id,zone_id FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&account, &registrarID, &storedZone)
+ if readErr != nil || account != p.AccountID || registrarID != r.RegistrarID || storedZone != 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 nil
+}
+
+// domainRegisteredHere reports whether any account holds a registration
+// for domain.
+func (s *Server) domainRegisteredHere(ctx context.Context, domain string) (bool, error) {
+ var n int
+ err := s.store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM domain_registrations WHERE domain=?`, domain).Scan(&n)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return n > 0, err
+}
+
+// ownerNotice emails every owner of acct, best effort: a failure is logged
+// and fails the job.
+func (s *Server) ownerNotice(ctx context.Context, acct *Account, id, subject, body string) {
+ members, err := s.store.Members(acct.ID)
+ if err != nil {
+ log.Printf("console: purchase %s: owners: %v", id, err)
+ jobFailed(ctx, err)
+ return
+ }
+ for _, member := range members {
+ if member.Role != RoleOwner {
+ continue
+ }
+ if _, err := s.deliver(ctx, member.Name, subject, body, 8*time.Second); err != nil {
+ log.Printf("console: purchase %s: owner notice: %v", id, err)
+ jobFailed(ctx, err)
+ }
+ }
+}
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go
index 2a095228c..645cc69cf 100644
--- a/internal/console/domainstore.go
+++ b/internal/console/domainstore.go
@@ -97,6 +97,10 @@ type purchaseDetails struct {
NextStatusAt time.Time `json:",omitzero"`
// ResolvedBy names the operator who recorded Facts.Resolution.
ResolvedBy string `json:",omitempty"`
+ // RefundPrepared is the current refund attempt's create request
+ // (Facts.RefundAttempt), stored before its first send and resent only
+ // verbatim, as CheckoutPrepared is.
+ RefundPrepared *billing.Prepared `json:",omitempty"`
}
// purchaseDetailsFields is purchaseDetails without its formatting methods,
diff --git a/internal/console/domaintransfer.go b/internal/console/domaintransfer.go
new file mode 100644
index 000000000..fcfc67bf8
--- /dev/null
+++ b/internal/console/domaintransfer.go
@@ -0,0 +1,583 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "maps"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// The transfer engine: one pass per live transfer purchase, from the
+// purchase pass (advancePurchaseStep dispatches by kind). Each pass gathers
+// the facts (registrar status, payment, refund), asks decideTransfer what
+// to do, does that one thing and records the facts and the result in CAS
+// moves. Whatever a send answers, the next pass's facts decide what
+// happened: a send's reply never settles anything, except a definite
+// refusal of the transfer request itself.
+
+// The status cadence after submit: every 30 minutes for a week, then daily.
+const (
+ transferStatusEvery = 30 * time.Minute
+ transferStatusFastFor = 7 * 24 * time.Hour
+ transferStatusSlowEvery = 24 * time.Hour
+ // transferCaptureFallback is CaptureBefore when the provider does not
+ // say: from the purchase's creation, a day short of the usual card
+ // authorisation (seven days).
+ transferCaptureFallback = 6 * 24 * time.Hour
+ // transferCheckoutGrace is how long after its expiry a Checkout whose
+ // create answer was lost is waited for before the customer's sessions
+ // are listed for it, as the buy engine does.
+ transferCheckoutGrace = time.Hour
+)
+
+func nextTransferStatusAt(now, submitted time.Time) time.Time {
+ if now.Before(submitted.Add(transferStatusFastFor)) {
+ return now.Add(transferStatusEvery)
+ }
+ return now.Add(transferStatusSlowEvery)
+}
+
+func (s *Server) transferNow() time.Time {
+ if s.transferClock != nil {
+ return s.transferClock().UTC()
+ }
+ return time.Now().UTC()
+}
+
+// transferStepHook, when set, runs after each step of a transfer pass that
+// wrote to the store or sent to a provider; an error stops the pass there,
+// as a crash would. A TEST SEAM.
+var transferStepHook func(step string) error
+
+func transferStep(step string) error {
+ if transferStepHook != nil {
+ return transferStepHook(step)
+ }
+ return nil
+}
+
+// transferObservation is what one pass gathered, ready to record.
+type transferObservation struct {
+ facts transferFacts
+ paymentIntent string
+ session string
+ nextStatusAt time.Time
+ // payment is the last good read of the Checkout, to compare a refund
+ // with what was captured.
+ payment billing.PaymentInfo
+ paymentOK bool
+}
+
+// advanceTransferStep is one pass over a live transfer.
+func (s *Server) advanceTransferStep(ctx context.Context, acct *Account, p *DomainPurchase) error {
+ now := s.transferNow()
+ if p.Facts.Registrar == rNotSent && p.CheckoutSession == "" && now.Before(p.CheckoutExpires) {
+ // The start's Checkout, made here when the start stopped short of it
+ // (a lost answer, a crash). Nothing is authorised without it.
+ if _, err := s.purchaseCheckout(ctx, p); err != nil {
+ return err
+ }
+ if !purchaseLive(p.State) || p.CheckoutSession == "" {
+ return nil
+ }
+ }
+ o := s.gatherTransfer(ctx, p, now)
+ d := decideTransfer(o.facts)
+ return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.actTransfer(ctx, acct, p, &o, d) })
+}
+
+func purchaseLive(state PurchaseState) bool {
+ switch state {
+ case PurchaseDone, PurchaseFailed, PurchaseExpired, PurchaseUnpaid:
+ return false
+ }
+ return true
+}
+
+func cloneTransferFacts(f transferFacts) transferFacts {
+ f.Alerts = maps.Clone(f.Alerts)
+ if f.Completed != nil {
+ c := *f.Completed
+ c.Nameservers = slices.Clone(c.Nameservers)
+ f.Completed = &c
+ }
+ return f
+}
+
+// gatherTransfer reads what the providers say now. A read that fails is
+// logged and counts as not knowing: rUnknown, pUnknown or a pending refund,
+// never a failure.
+func (s *Server) gatherTransfer(ctx context.Context, p *DomainPurchase, now time.Time) transferObservation {
+ o := transferObservation{facts: cloneTransferFacts(p.Facts), paymentIntent: p.PaymentIntent, session: p.CheckoutSession, nextStatusAt: p.NextStatusAt}
+ o.facts.Now = now
+ // The checkout_expires column is the authority.
+ o.facts.CheckoutExpires = p.CheckoutExpires
+ s.gatherTransferRegistrar(ctx, p, &o, now)
+ s.gatherTransferPayment(ctx, p, &o, now)
+ s.gatherTransferRefund(ctx, p, &o)
+ return o
+}
+
+// gatherTransferRegistrar reads the transfer's status at NextStatusAt.
+// Before submit it is rNotSent and nothing is read. A definite outcome
+// once recorded (or an operator's resolution) is never read again, so no
+// later answer can replace it (I9).
+func (s *Server) gatherTransferRegistrar(ctx context.Context, p *DomainPurchase, o *transferObservation, now time.Time) {
+ f := &o.facts
+ switch f.Registrar {
+ case rNotSent, rCompleted, rFailed:
+ return
+ }
+ if f.Resolution != "" || now.Before(p.NextStatusAt) {
+ return
+ }
+ st, err := s.cfg.Registrar.TransferStatus(ctx, p.Domain)
+ o.nextStatusAt = nextTransferStatusAt(now, f.SubmittedAt)
+ if err != nil {
+ log.Printf("console: transfer %s: status: %v", p.ID, err)
+ jobFailed(ctx, err)
+ f.Registrar = rUnknown
+ return
+ }
+ switch st.State {
+ case registrar.TransferPending:
+ f.Registrar, f.Accepted = rPending, true
+ case registrar.TransferCompleted:
+ r := st.Registered
+ if r.Domain == "" {
+ r.Domain = p.Domain
+ }
+ if r.Domain != p.Domain || r.RegistrarID == "" {
+ // A completion the adapter could not read in full: not yet an
+ // outcome to record.
+ f.Registrar = rUnknown
+ return
+ }
+ r.Nameservers = slices.Clone(r.Nameservers)
+ f.Registrar, f.Accepted, f.Completed = rCompleted, true, &r
+ case registrar.TransferFailed:
+ f.Registrar, f.RegistrarReason = rFailed, st.Reason
+ default:
+ // None (or a state this build does not know): sent, outcome
+ // unknown. After a pending read this is unknown-after-acceptance:
+ // Accepted stays, and it is never read as failed.
+ f.Registrar = rUnknown
+ }
+}
+
+// gatherTransferPayment reads the Checkout. Before any authorisation an
+// open session is pAwaiting whatever its PaymentIntent says (a declined
+// card may be retried in it) and an expired one pCancelled. After: the
+// recorded PaymentIntent's status, requires_payment_method reading as
+// pFailed only once a capture was sent.
+func (s *Server) gatherTransferPayment(ctx context.Context, p *DomainPurchase, o *transferObservation, now time.Time) {
+ f := &o.facts
+ if o.session == "" {
+ switch {
+ case p.CheckoutPrepared == nil:
+ // No Checkout was ever asked for, so nothing can be authorised.
+ f.Payment = pAwaiting
+ if !now.Before(p.CheckoutExpires) {
+ f.Payment = pCancelled
+ }
+ return
+ case now.Before(p.CheckoutExpires):
+ f.Payment = pAwaiting
+ return
+ case now.Before(p.CheckoutExpires.Add(transferCheckoutGrace)):
+ f.Payment = pUnknown
+ return
+ }
+ session, found, err := s.adoptTransferCheckout(ctx, p)
+ if err != nil {
+ log.Printf("console: transfer %s: checkout sessions: %v", p.ID, err)
+ jobFailed(ctx, err)
+ f.Payment = pUnknown
+ return
+ }
+ if !found {
+ f.Payment = pCancelled
+ return
+ }
+ o.session = session
+ }
+ info, err := s.billing.cfg.Provider.PaymentCheckout(ctx, o.session)
+ if err != nil {
+ log.Printf("console: transfer %s: payment: %v", p.ID, err)
+ jobFailed(ctx, err)
+ f.Payment = pUnknown
+ return
+ }
+ if o.paymentIntent == "" {
+ switch {
+ case info.Authorised && info.IntentStatus == "requires_capture" && info.PaymentIntent != "" && info.Currency == p.Currency && info.Amount == p.Amount:
+ f.Payment, o.paymentIntent = pAuthorised, info.PaymentIntent
+ case info.Authorised:
+ f.Payment = pUnknown
+ case info.Status == "open":
+ f.Payment = pAwaiting
+ case info.Status == "expired", info.Status == "complete" && info.IntentStatus == "canceled":
+ f.Payment = pCancelled
+ default:
+ f.Payment = pUnknown
+ }
+ } else if info.PaymentIntent != o.paymentIntent {
+ f.Payment = pUnknown
+ } else {
+ o.payment, o.paymentOK = info, true
+ switch info.IntentStatus {
+ case "requires_capture":
+ f.Payment = pAuthorised
+ case "succeeded":
+ f.Payment = pCaptured
+ case "canceled":
+ f.Payment = pCancelled
+ case "requires_payment_method":
+ f.Payment = pUnknown
+ if f.CaptureAttempted {
+ f.Payment = pFailed
+ }
+ default:
+ f.Payment = pUnknown
+ }
+ }
+ if o.paymentIntent != "" {
+ if !info.CaptureBefore.IsZero() {
+ f.CaptureBefore = info.CaptureBefore.UTC()
+ } else if f.CaptureBefore.IsZero() {
+ f.CaptureBefore = p.CreatedAt.Add(transferCaptureFallback).UTC()
+ }
+ }
+}
+
+// adoptTransferCheckout finds the purchase's session among the customer's,
+// for a Checkout whose create answer was lost and has since expired.
+func (s *Server) adoptTransferCheckout(ctx context.Context, p *DomainPurchase) (string, bool, error) {
+ b, err := s.store.BillingAccount(p.AccountID)
+ if err != nil {
+ return "", false, err
+ }
+ if b == nil {
+ return "", false, errors.New("console: transfer: no billing account")
+ }
+ sessions, err := s.billing.cfg.Provider.CustomerCheckouts(ctx, b.Customer, time.Unix(0, 0))
+ if err != nil {
+ return "", false, err
+ }
+ for _, c := range sessions {
+ if c.Customer == b.Customer && c.Reference == p.ID && c.ID != "" {
+ return c.ID, true, nil
+ }
+ }
+ return "", false, nil
+}
+
+// gatherTransferRefund reads the current refund attempt: by its ID, or,
+// when the create answer was lost, from the PaymentIntent's refunds tagged
+// with this purchase and this attempt (other attempts, failed ones among
+// them, are ignored). Succeeded counts only for the full captured amount
+// and currency.
+func (s *Server) gatherTransferRefund(ctx context.Context, p *DomainPurchase, o *transferObservation) {
+ f := &o.facts
+ if f.RefundAttempt < 1 {
+ return
+ }
+ provider := s.billing.cfg.Provider
+ var r billing.RefundInfo
+ if f.RefundID != "" {
+ got, err := provider.Refund(ctx, f.RefundID)
+ if err != nil {
+ log.Printf("console: transfer %s: refund: %v", p.ID, err)
+ jobFailed(ctx, err)
+ f.Refund = fPending
+ return
+ }
+ r = got
+ } else {
+ list, err := provider.Refunds(ctx, o.paymentIntent)
+ if err != nil {
+ log.Printf("console: transfer %s: refunds: %v", p.ID, err)
+ jobFailed(ctx, err)
+ f.Refund = fPending
+ return
+ }
+ found := false
+ for _, c := range list {
+ if c.Purchase == p.ID && c.Attempt == f.RefundAttempt && c.ID != "" {
+ r, found = c, true
+ }
+ }
+ if !found {
+ f.Refund = fNone
+ return
+ }
+ f.RefundID = r.ID
+ }
+ switch r.Status {
+ case billing.RefundSucceeded:
+ f.Refund = fPending
+ if o.paymentOK && r.PaymentIntent == o.paymentIntent && r.Amount == o.payment.AmountTotal && r.Currency == o.payment.Currency {
+ f.Refund = fSucceeded
+ } else if o.paymentOK {
+ err := fmt.Errorf("console: transfer %s: refund %s is not the full capture", p.ID, r.ID)
+ log.Print(err)
+ jobFailed(ctx, err)
+ }
+ case billing.RefundFailed, billing.RefundCanceled:
+ f.Refund = fFailed
+ default:
+ f.Refund = fPending
+ }
+}
+
+// transferLiveState is the live state that names where the facts stand.
+func transferLiveState(f transferFacts, current PurchaseState) PurchaseState {
+ switch effectiveRegistrar(f) {
+ case rNotSent:
+ if f.Payment == pAuthorised {
+ return PurchaseAuthorised
+ }
+ case rUnknown:
+ return PurchaseTransferSubmitting
+ case rPending, rCompleted:
+ return PurchaseTransferPending
+ case rFailed:
+ if f.Payment == pCaptured {
+ return PurchaseTransferRefunding
+ }
+ }
+ return current
+}
+
+// recordTransfer writes the observation, and whatever extra sets, in one CAS
+// move to to. A definite registrar outcome already recorded stands (I9).
+func (s *Server) recordTransfer(ctx context.Context, p *DomainPurchase, o *transferObservation, to PurchaseState, extra func(*DomainPurchase)) error {
+ facts := cloneTransferFacts(o.facts)
+ facts.Now = time.Time{}
+ if stored := p.Facts.Registrar; stored == rCompleted || stored == rFailed {
+ facts.Registrar, facts.RegistrarReason, facts.Completed = stored, p.Facts.RegistrarReason, p.Facts.Completed
+ }
+ return s.movePurchase(ctx, p, to, func(q *DomainPurchase) {
+ q.Facts = cloneTransferFacts(facts)
+ q.NextStatusAt, q.PaymentIntent, q.CheckoutSession = o.nextStatusAt, o.paymentIntent, o.session
+ if extra != nil {
+ extra(q)
+ }
+ })
+}
+
+// recordTransferIfChanged records the observation only when it differs
+// from what is stored, so a quiet pass writes nothing.
+func (s *Server) recordTransferIfChanged(ctx context.Context, p *DomainPurchase, o *transferObservation) error {
+ to := transferLiveState(o.facts, p.State)
+ if to == p.State && sameTransferRecord(p, o) {
+ return nil
+ }
+ return s.recordTransfer(ctx, p, o, to, nil)
+}
+
+func sameTransferRecord(p *DomainPurchase, o *transferObservation) bool {
+ type rec struct {
+ Facts transferFacts
+ NextStatusAt time.Time
+ PaymentIntent, Session string
+ }
+ stored, _ := json.Marshal(rec{p.Facts, p.NextStatusAt, p.PaymentIntent, p.CheckoutSession})
+ seen, _ := json.Marshal(rec{o.facts, o.nextStatusAt, o.paymentIntent, o.session})
+ return string(stored) == string(seen)
+}
+
+// actTransfer does d's one action under the purchase's CAS, then records.
+func (s *Server) actTransfer(ctx context.Context, acct *Account, p *DomainPurchase, o *transferObservation, d transferDecision) error {
+ provider := s.billing.cfg.Provider
+ switch d.Action {
+ case aWait:
+ return s.recordTransferIfChanged(ctx, p, o)
+ case aAlert:
+ return s.alertTransfer(ctx, acct, p, o, d.Alert)
+ case aSubmit:
+ return s.submitTransfer(ctx, p, o)
+ case aCapture:
+ // Recorded before the send: only then can requires_payment_method
+ // read as a failed capture.
+ o.facts.CaptureAttempted = true
+ if err := s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil); err != nil {
+ return err
+ }
+ if err := transferStep("capture:recorded"); err != nil {
+ return err
+ }
+ prepared, err := provider.PrepareCapture(o.paymentIntent, p.ID+":capture")
+ if err != nil {
+ return err
+ }
+ _, err = provider.Send(ctx, prepared)
+ return err
+ case aCancelAuthorisation:
+ if err := s.recordTransferIfChanged(ctx, p, o); err != nil {
+ return err
+ }
+ if err := transferStep("cancel:recorded"); err != nil {
+ return err
+ }
+ prepared, err := provider.PrepareCancelPayment(o.paymentIntent, p.ID+":cancel")
+ if err != nil {
+ return err
+ }
+ _, err = provider.Send(ctx, prepared)
+ return err
+ case aCreateRefund:
+ return s.refundTransfer(ctx, acct, p, o, d)
+ case aRecordDone, aRecordUnpaid:
+ return s.completeTransfer(ctx, acct, p, o, d)
+ case aFinishFailed:
+ reason := ""
+ if d.Terminal == PurchaseFailed {
+ reason = o.facts.RegistrarReason
+ }
+ if err := s.recordTransfer(ctx, p, o, d.Terminal, func(q *DomainPurchase) { q.Reason = reason }); err != nil {
+ return err
+ }
+ if effectiveRegistrar(o.facts) == rFailed {
+ body := transferFailureWords(o.facts.RegistrarReason) + " " + transferOwnerCopy.FailedNothingTaken
+ if o.facts.Payment == pCaptured {
+ body = transferFailureWords(o.facts.RegistrarReason) + " " + transferOwnerCopy.FailedRefunded
+ }
+ s.ownerNotice(ctx, acct, p.ID, fmt.Sprintf(transferOwnerCopy.FailedSubject, p.Domain), body)
+ }
+ return nil
+ }
+ return fmt.Errorf("console: transfer %s: no such action %v", p.ID, d.Action)
+}
+
+// alertTransfer delivers one due alert and records it only when it was
+// delivered; an undelivered alert stays due for the next pass.
+func (s *Server) alertTransfer(ctx context.Context, acct *Account, p *DomainPurchase, o *transferObservation, kind string) error {
+ log.Printf("console: domain transfer: account=%s domain=%s purchase=%s alert=%s", acct.Sqid, p.Domain, p.ID, kind)
+ body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, p.Domain, p.ID, acct.Sqid, transferAlertReason(kind))
+ if err := s.alertOperator(ctx, domainPurchaseCopy.OperatorSubject, body); err != nil {
+ return errors.Join(err, s.recordTransferIfChanged(ctx, p, o))
+ }
+ if o.facts.Alerts == nil {
+ o.facts.Alerts = map[string]time.Time{}
+ }
+ o.facts.Alerts[kind] = o.facts.Now
+ return s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil)
+}
+
+// submitTransfer sends the transfer request at most once. The move to
+// transfer_submitting records the submit (rUnknown) and clears the auth
+// code first; the request is then sent from memory. After that move,
+// nothing ever sends it again: a crash or an ambiguous answer is settled
+// only by a status read or an operator. A definite refusal is recorded as
+// rFailed with its reason, and stays.
+func (s *Server) submitTransfer(ctx context.Context, p *DomainPurchase, o *transferObservation) error {
+ req := registrar.TransferRequest{Domain: p.Domain, AuthCode: p.AuthCode, OwnerHandle: p.OwnerHandle, Key: p.ID, Nameservers: slices.Clone(p.Nameservers)}
+ if req.AuthCode == "" || req.OwnerHandle == "" || len(req.Nameservers) == 0 || o.paymentIntent == "" {
+ return fmt.Errorf("console: transfer %s: not ready to submit", p.ID)
+ }
+ o.facts.Registrar, o.facts.SubmittedAt = rUnknown, o.facts.Now
+ o.nextStatusAt = time.Time{} // the next pass reads the status
+ if err := s.recordTransfer(ctx, p, o, PurchaseTransferSubmitting, nil); err != nil {
+ return err
+ }
+ if err := transferStep("submit:recorded"); err != nil {
+ return err
+ }
+ st, err := s.cfg.Registrar.RequestTransfer(ctx, req)
+ req.AuthCode = ""
+ if stepErr := transferStep("submit:sent"); stepErr != nil {
+ return stepErr
+ }
+ if err == nil {
+ return nil
+ }
+ if !errors.Is(err, registrar.ErrRefused) {
+ return err
+ }
+ log.Printf("console: transfer %s: refused at submit (%s)", p.ID, st.Reason)
+ o.facts.Registrar, o.facts.RegistrarReason = rFailed, st.Reason
+ return s.recordTransfer(ctx, p, o, PurchaseTransferSubmitting, nil)
+}
+
+// refundTransfer sends refund attempt n. A new attempt is persisted first:
+// one move sets the attempt, clears the refund ID and stores the prepared
+// request, and only then is it sent (the persist-before-send contract). The
+// current attempt again, when no refund for it is listed, resends its
+// stored request verbatim.
+func (s *Server) refundTransfer(ctx context.Context, acct *Account, p *DomainPurchase, o *transferObservation, d transferDecision) error {
+ provider := s.billing.cfg.Provider
+ n := d.RefundAttempt
+ if n != o.facts.RefundAttempt || p.RefundPrepared == nil {
+ prepared, err := provider.PrepareRefund(o.paymentIntent, p.ID, n, fmt.Sprintf("%s:refund:%d", p.ID, n))
+ if err != nil {
+ return err
+ }
+ o.facts.RefundAttempt, o.facts.RefundID, o.facts.Refund = n, "", fNone
+ if err := s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), func(q *DomainPurchase) { q.RefundPrepared = &prepared }); err != nil {
+ return err
+ }
+ } else if err := s.recordTransferIfChanged(ctx, p, o); err != nil {
+ return err
+ }
+ if err := transferStep("refund:recorded"); err != nil {
+ return err
+ }
+ if d.Alert != "" && o.facts.Alerts[d.Alert].IsZero() {
+ // Delivered or not, the refund goes out; undelivered, it stays due.
+ if err := s.alertTransfer(ctx, acct, p, o, d.Alert); err != nil {
+ log.Printf("console: transfer %s: %v", p.ID, err)
+ jobFailed(ctx, err)
+ }
+ }
+ res, err := provider.Send(ctx, *p.RefundPrepared)
+ if stepErr := transferStep("refund:sent"); stepErr != nil {
+ return stepErr
+ }
+ if err != nil {
+ return err
+ }
+ if res.Refund == nil || res.Refund.ID == "" {
+ return nil
+ }
+ o.facts.RefundID = res.Refund.ID
+ return s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil)
+}
+
+// completeTransfer records the registration (no zone: the domain's DNS
+// stays where it is) and ends the purchase done or, with nothing captured,
+// unpaid with Carloku's renewal off, the operator alerted and the owner
+// emailed. A crash between the two is replayed by the next pass, which
+// finds the same registration.
+func (s *Server) completeTransfer(ctx context.Context, acct *Account, p *DomainPurchase, o *transferObservation, d transferDecision) error {
+ r := *o.facts.Completed
+ paid := d.Action == aRecordDone
+ if err := s.recordPurchaseRegistration(ctx, p, r, "", paid); err != nil {
+ return err
+ }
+ if !paid {
+ if _, err := s.store.db.ExecContext(ctx, `UPDATE domain_registrations SET auto_renew=0 WHERE domain=? AND account_id=? AND registrar_id=?`, p.Domain, p.AccountID, r.RegistrarID); err != nil {
+ return err
+ }
+ }
+ if err := transferStep("complete:recorded"); err != nil {
+ return err
+ }
+ if err := s.recordTransfer(ctx, p, o, d.Terminal, func(q *DomainPurchase) { q.RegistrarID = r.RegistrarID; q.Reason = "" }); err != nil {
+ return err
+ }
+ if paid {
+ s.ownerNotice(ctx, acct, p.ID, fmt.Sprintf(transferOwnerCopy.DoneSubject, p.Domain), transferOwnerCopy.DoneBody)
+ return nil
+ }
+ s.purchaseAlert(ctx, acct, p.Domain, p.ID, transferAlertReason("unpaid"))
+ s.ownerNotice(ctx, acct, p.ID, fmt.Sprintf(transferOwnerCopy.UnpaidSubject, p.Domain), transferOwnerCopy.UnpaidBody)
+ return nil
+}
diff --git a/internal/console/domaintransfer_copy.go b/internal/console/domaintransfer_copy.go
new file mode 100644
index 000000000..54fc72f37
--- /dev/null
+++ b/internal/console/domaintransfer_copy.go
@@ -0,0 +1,94 @@
+package console
+
+import (
+ "net/http"
+ "strings"
+)
+
+// DRAFT copy for transfers in (spec §12.3), pending copy review. No
+// registrar or DNS host is named; nothing says the domain renews.
+
+// domainTransferCopy is the start door's refusals.
+var domainTransferCopy = map[string]string{
+ "authCode": "Enter the transfer code from the domain’s current registrar.",
+ "notOffered": "Moving domains with this ending isn’t offered yet.",
+ "dnssec": "This domain uses DNSSEC, which can’t be moved here yet. Turn DNSSEC off where its DNS is hosted, wait a day, then try again.",
+ "dnsUnread": "We couldn’t check this domain’s DNS just now. Try again in a minute.",
+ "nameservers": "We couldn’t read this domain’s nameservers. Check that it’s registered and its DNS works, then try again.",
+ "unavailable": "moving domains here is unavailable right now",
+}
+
+// domainTransferNotNow is the refusal when the registrar's transfer check
+// says the domain cannot move now, chosen by the check's reason (never by
+// parsing an error). An empty or unknown reason gets the generic line.
+var domainTransferNotNow = map[string]string{
+ "locked": "This domain is locked at its current registrar. Unlock it there, then try again.",
+ "recent": "This domain was registered or moved in the last 60 days, so it can’t move yet. Try again once 60 days have passed.",
+ "expired": "This domain expired too long ago to move. Renew it at its current registrar first.",
+ "not_registered": "This domain isn’t registered, so there’s nothing to move. You can buy it instead.",
+ "": "This domain can’t be moved right now.",
+}
+
+func transferNotNowRefusal(reason string) *doorRefusal {
+ msg, ok := domainTransferNotNow[reason]
+ if !ok {
+ msg = domainTransferNotNow[""]
+ }
+ return &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: msg}
+}
+
+// transferFailureReason is a failed transfer's reason in plain words, for
+// the owner's email and the card. An empty or unknown reason gets the
+// generic line.
+var transferFailureReason = map[string]string{
+ "auth_code": "The transfer code was wrong or out of date.",
+ "rejected": "The current registrar turned the transfer down.",
+ "timeout": "The current registrar didn’t answer in time.",
+ "locked": "The domain was still locked at its current registrar.",
+ "recent": "The domain was registered or moved in the last 60 days.",
+ "expired": "The domain had expired too long ago to move.",
+ "not_registered": "The domain isn’t registered.",
+ "": "The transfer didn’t go through.",
+}
+
+func transferFailureWords(reason string) string {
+ if msg, ok := transferFailureReason[reason]; ok {
+ return msg
+ }
+ return transferFailureReason[""]
+}
+
+// transferOwnerCopy is the owner's email when a transfer finishes after
+// it was sent. Each subject takes the domain.
+var transferOwnerCopy = struct {
+ DoneSubject, DoneBody, UnpaidSubject, UnpaidBody string
+ FailedSubject, FailedRefunded, FailedNothingTaken string
+}{
+ DoneSubject: "%s has moved",
+ DoneBody: "Your domain’s registration has moved here, with a year added to it. Its DNS and email haven’t changed.",
+ UnpaidSubject: "Payment for %s needs attention",
+ UnpaidBody: "Your domain’s registration has moved here, but the payment didn’t go through. We’ll contact you about paying for it.",
+ FailedSubject: "%s didn’t move",
+ FailedRefunded: "We’ve refunded your payment in full. The domain stays where it was, and nothing about it has changed.",
+ FailedNothingTaken: "Nothing was charged, and the hold on your card has been released. The domain stays where it was, and nothing about it has changed.",
+}
+
+// transferAlertCopy is the operator's alert reason for each alert kind
+// (operator-facing; the body is domainPurchaseCopy.OperatorBody).
+var transferAlertCopy = map[string]string{
+ alertUnknown24h: "transfer outcome still unknown a day after submit; check the registrar, then resolve it",
+ alertLapse: "transfer outcome unknown and the card authorisation lapses within a day",
+ alertUnknownWeekly: "transfer outcome still unknown; resolve it once the registrar says",
+ alertCaptureRefused: "transfer accepted but the capture was refused or the hold ended",
+ "unpaid": "transfer completed but nothing was captured: recorded unpaid",
+}
+
+func transferAlertReason(kind string) string {
+ if msg, ok := transferAlertCopy[kind]; ok {
+ return msg
+ }
+ if attempt, ok := strings.CutPrefix(kind, alertRefundFailed); ok {
+ return "transfer failed and refund attempt " + attempt + " failed; a new attempt is under way"
+ }
+ return kind
+}
diff --git a/internal/console/domaintransfer_decide.go b/internal/console/domaintransfer_decide.go
new file mode 100644
index 000000000..622dd487c
--- /dev/null
+++ b/internal/console/domaintransfer_decide.go
@@ -0,0 +1,212 @@
+package console
+
+import (
+ "fmt"
+ "time"
+)
+
+// decideTransfer is the only place that chooses a transfer's next action or
+// terminal state. It is pure: the engine (domaintransfer.go) gathers the
+// facts, calls it, performs the one action it names and records the
+// result; the next pass's facts, never an action's reply, say what
+// happened.
+//
+// Money first: when an action moves money or settles the purchase it is
+// returned; only when there is nothing to do but wait is a due operator
+// alert returned instead (aAlert), at most one per pass.
+func decideTransfer(f transferFacts) transferDecision {
+ d := decideTransferMoney(f)
+ if d.Action == aWait {
+ if kind := dueTransferAlert(f); kind != "" {
+ return transferDecision{Action: aAlert, Alert: kind}
+ }
+ }
+ return d
+}
+
+// transferAction is the one thing a pass does.
+type transferAction int
+
+const (
+ aWait transferAction = iota
+ aSubmit
+ aCapture
+ aCancelAuthorisation
+ aCreateRefund
+ aRecordDone
+ aRecordUnpaid
+ aFinishFailed
+ aAlert
+)
+
+var transferActionNames = []string{
+ aWait: "wait", aSubmit: "submit", aCapture: "capture", aCancelAuthorisation: "cancel-authorisation",
+ aCreateRefund: "create-refund", aRecordDone: "record-done", aRecordUnpaid: "record-unpaid",
+ aFinishFailed: "finish-failed", aAlert: "alert",
+}
+
+func (a transferAction) String() string {
+ if a < 0 || int(a) >= len(transferActionNames) {
+ return fmt.Sprintf("action(%d)", int(a))
+ }
+ return transferActionNames[a]
+}
+
+type transferDecision struct {
+ Action transferAction
+ // Alert is the alert kind to deliver: aAlert's only work, or, beside
+ // aCreateRefund after a failed attempt, the alert for that failure
+ // (sent once the new attempt is persisted; dueTransferAlert keeps it due
+ // until it is delivered).
+ Alert string
+ // Terminal is the state the action ends the purchase in; "" unless it
+ // does.
+ Terminal PurchaseState
+ // RefundAttempt is, for aCreateRefund, the attempt to send: the current
+ // one again while no answer for it exists (its stored request is
+ // resent), or the next after a failed one. A failed attempt is never
+ // sent again.
+ RefundAttempt int
+}
+
+// The operator alert kinds, the keys of transferFacts.Alerts.
+const (
+ alertUnknown24h = "24h-unknown" // the outcome is still unknown a day after submit
+ alertLapse = "lapse" // the authorisation lapses within a day, outcome unknown
+ alertUnknownWeekly = "weekly-unknown" // weekly while the outcome stays unknown
+ alertCaptureRefused = "capture-refused" // accepted, but the capture was refused or the hold ended
+ alertRefundFailed = "refund-failed:" // + the attempt number: a refund attempt failed
+)
+
+const (
+ transferUnknownAlertAfter = 24 * time.Hour
+ transferLapseAlertBefore = 24 * time.Hour
+ transferUnknownRepeat = 7 * 24 * time.Hour
+)
+
+// effectiveRegistrar is the registrar outcome decideTransfer acts on: an
+// operator's resolution of an unknown transfer stands in for the answer the
+// registrar never gave.
+func effectiveRegistrar(f transferFacts) registrarOutcome {
+ if f.Registrar == rUnknown {
+ switch f.Resolution {
+ case transferResolvedFailed:
+ return rFailed
+ case transferResolvedCompleted:
+ return rCompleted
+ }
+ }
+ return f.Registrar
+}
+
+// The operator resolutions (transferFacts.Resolution).
+const (
+ transferResolvedFailed = "failed"
+ transferResolvedCompleted = "completed"
+)
+
+func decideTransferMoney(f transferFacts) transferDecision {
+ wait := transferDecision{Action: aWait}
+ switch effectiveRegistrar(f) {
+ case rNotSent:
+ switch f.Payment {
+ case pAwaiting:
+ // Checkout is open; a declined card may still be retried in it.
+ if !f.CheckoutExpires.IsZero() && !f.Now.Before(f.CheckoutExpires) {
+ return transferDecision{Action: aFinishFailed, Terminal: PurchaseExpired}
+ }
+ case pAuthorised:
+ return transferDecision{Action: aSubmit}
+ case pCancelled:
+ // Nothing was sent and nothing taken.
+ return transferDecision{Action: aFinishFailed, Terminal: PurchaseExpired}
+ }
+ case rUnknown:
+ // Never settled blind. A transfer the registrar was seen to accept
+ // is captured as an accepted one is; nothing else moves money.
+ if f.Accepted && f.Payment == pAuthorised {
+ return transferDecision{Action: aCapture}
+ }
+ case rPending:
+ if f.Payment == pAuthorised {
+ return transferDecision{Action: aCapture}
+ }
+ case rCompleted:
+ switch f.Payment {
+ case pCaptured:
+ if f.Completed != nil {
+ return transferDecision{Action: aRecordDone, Terminal: PurchaseDone}
+ }
+ case pAuthorised:
+ return transferDecision{Action: aCapture}
+ case pCancelled, pFailed:
+ if f.Completed != nil {
+ return transferDecision{Action: aRecordUnpaid, Terminal: PurchaseUnpaid}
+ }
+ }
+ case rFailed:
+ switch f.Payment {
+ case pAuthorised:
+ return transferDecision{Action: aCancelAuthorisation}
+ case pCancelled, pFailed:
+ return transferDecision{Action: aFinishFailed, Terminal: PurchaseFailed}
+ case pCaptured:
+ switch f.Refund {
+ case fNone:
+ return transferDecision{Action: aCreateRefund, RefundAttempt: max(f.RefundAttempt, 1)}
+ case fFailed:
+ // A new attempt, and the operator told the last one failed.
+ return transferDecision{Action: aCreateRefund, RefundAttempt: f.RefundAttempt + 1, Alert: refundFailedAlert(f.RefundAttempt)}
+ case fSucceeded:
+ return transferDecision{Action: aFinishFailed, Terminal: PurchaseFailed}
+ }
+ }
+ }
+ return wait
+}
+
+// dueTransferAlert is the alert that is due and not yet delivered, or "".
+// The schedule for an unknown outcome: a day after submit, a day before the
+// authorisation lapses, then weekly after the first. A refused capture and
+// each failed refund attempt are alerted once.
+func dueTransferAlert(f transferFacts) string {
+ sent := func(kind string) bool { return !f.Alerts[kind].IsZero() }
+ reg := effectiveRegistrar(f)
+ if reg == rUnknown {
+ if !f.SubmittedAt.IsZero() && !f.Now.Before(f.SubmittedAt.Add(transferUnknownAlertAfter)) && !sent(alertUnknown24h) {
+ return alertUnknown24h
+ }
+ if f.Payment == pAuthorised && !f.CaptureBefore.IsZero() && !f.Now.Before(f.CaptureBefore.Add(-transferLapseAlertBefore)) && !sent(alertLapse) {
+ return alertLapse
+ }
+ if first := f.Alerts[alertUnknown24h]; !first.IsZero() {
+ last := first
+ if weekly := f.Alerts[alertUnknownWeekly]; weekly.After(last) {
+ last = weekly
+ }
+ if !f.Now.Before(last.Add(transferUnknownRepeat)) {
+ return alertUnknownWeekly
+ }
+ }
+ }
+ accepted := reg == rPending || (reg == rUnknown && f.Accepted)
+ if accepted && (f.Payment == pFailed || f.Payment == pCancelled) && !sent(alertCaptureRefused) {
+ return alertCaptureRefused
+ }
+ if reg == rFailed && f.Payment == pCaptured {
+ // Every attempt before the current one failed; so did the current
+ // one when its refund reads failed.
+ last := f.RefundAttempt - 1
+ if f.Refund == fFailed {
+ last = f.RefundAttempt
+ }
+ for n := 1; n <= last; n++ {
+ if kind := refundFailedAlert(n); !sent(kind) {
+ return kind
+ }
+ }
+ }
+ return ""
+}
+
+func refundFailedAlert(attempt int) string { return fmt.Sprintf("%s%d", alertRefundFailed, attempt) }
diff --git a/internal/console/domaintransfer_decide_test.go b/internal/console/domaintransfer_decide_test.go
new file mode 100644
index 000000000..4c55bf596
--- /dev/null
+++ b/internal/console/domaintransfer_decide_test.go
@@ -0,0 +1,870 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "math/rand/v2"
+ "net/http"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/billing/billingtest"
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/carlosframework/platform/internal/registrar/registrartest"
+)
+
+var decideBase = time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)
+
+// quietFacts are facts at a moment no alert is due: an hour after submit,
+// Checkout still open, the authorisation days from lapsing.
+func quietFacts(reg registrarOutcome, pay paymentOutcome, refund refundOutcome) transferFacts {
+ f := transferFacts{Registrar: reg, Payment: pay, Refund: refund,
+ Now: decideBase, CheckoutExpires: decideBase.Add(30 * time.Minute), CaptureBefore: decideBase.Add(5 * 24 * time.Hour)}
+ if reg != rNotSent {
+ f.SubmittedAt = decideBase.Add(-time.Hour)
+ }
+ if reg == rCompleted {
+ f.Completed = &registrar.Registered{Domain: "shop.com", RegistrarID: "r1", Expires: decideBase.AddDate(1, 0, 0)}
+ }
+ if pay == pCaptured || pay == pFailed {
+ f.CaptureAttempted = true
+ }
+ if refund != fNone {
+ f.RefundAttempt = 1
+ }
+ return f
+}
+
+type decideKey struct {
+ reg registrarOutcome
+ pay paymentOutcome
+ refund refundOutcome
+}
+
+func TestDecideTransferTable(t *testing.T) {
+ type row struct {
+ name string
+ facts transferFacts
+ action transferAction
+ terminal PurchaseState
+ attempt int
+ alert string
+ }
+ expired := quietFacts(rNotSent, pAwaiting, fNone)
+ expired.Now = expired.CheckoutExpires
+ resolvedFailed := quietFacts(rUnknown, pAuthorised, fNone)
+ resolvedFailed.Resolution = transferResolvedFailed
+ resolvedCaptured := quietFacts(rUnknown, pCaptured, fNone)
+ resolvedCaptured.Resolution = transferResolvedFailed
+ resolvedDone := quietFacts(rUnknown, pCaptured, fNone)
+ resolvedDone.Resolution = transferResolvedCompleted
+ resolvedDone.Completed = &registrar.Registered{Domain: "shop.com", RegistrarID: "r1"}
+ resolvedUnpaid := resolvedDone
+ resolvedUnpaid.Payment = pCancelled
+ acceptedUnknown := quietFacts(rUnknown, pAuthorised, fNone)
+ acceptedUnknown.Accepted = true
+ emptyReason := quietFacts(rFailed, pCaptured, fNone)
+ emptyReason.RegistrarReason = ""
+ resend := quietFacts(rFailed, pCaptured, fNone)
+ resend.RefundAttempt = 2
+ secondPendingAlerted := quietFacts(rFailed, pCaptured, fPending)
+ secondPendingAlerted.RefundAttempt = 2
+ secondPendingAlerted.Alerts = map[string]time.Time{refundFailedAlert(1): decideBase}
+ secondPending := secondPendingAlerted
+ secondPending.Alerts = nil
+ pendingRefused := quietFacts(rPending, pFailed, fNone)
+ pendingRefusedAlerted := pendingRefused
+ pendingRefusedAlerted.Alerts = map[string]time.Time{alertCaptureRefused: decideBase}
+
+ rows := []row{
+ {"not sent, checkout open: wait (a declined card may be retried)", quietFacts(rNotSent, pAwaiting, fNone), aWait, "", 0, ""},
+ {"not sent, checkout past its expiry: expired, not charged", expired, aFinishFailed, PurchaseExpired, 0, ""},
+ {"not sent, authorised: submit", quietFacts(rNotSent, pAuthorised, fNone), aSubmit, "", 0, ""},
+ {"not sent, cancelled: finished, not charged", quietFacts(rNotSent, pCancelled, fNone), aFinishFailed, PurchaseExpired, 0, ""},
+ {"unknown, authorised: wait, never settled blind", quietFacts(rUnknown, pAuthorised, fNone), aWait, "", 0, ""},
+ {"unknown after acceptance, authorised: capture", acceptedUnknown, aCapture, "", 0, ""},
+ {"unknown resolved failed, authorised: cancel", resolvedFailed, aCancelAuthorisation, "", 0, ""},
+ {"unknown resolved failed, captured: refund", resolvedCaptured, aCreateRefund, "", 1, ""},
+ {"unknown resolved completed, captured: done", resolvedDone, aRecordDone, PurchaseDone, 0, ""},
+ {"unknown resolved completed, cancelled: unpaid", resolvedUnpaid, aRecordUnpaid, PurchaseUnpaid, 0, ""},
+ {"pending, authorised: capture", quietFacts(rPending, pAuthorised, fNone), aCapture, "", 0, ""},
+ {"pending, captured: wait", quietFacts(rPending, pCaptured, fNone), aWait, "", 0, ""},
+ {"pending, capture failed: alerted once", pendingRefused, aAlert, "", 0, alertCaptureRefused},
+ {"pending, capture failed, alerted: wait", pendingRefusedAlerted, aWait, "", 0, ""},
+ {"completed, captured: done", quietFacts(rCompleted, pCaptured, fNone), aRecordDone, PurchaseDone, 0, ""},
+ {"completed, authorised: capture", quietFacts(rCompleted, pAuthorised, fNone), aCapture, "", 0, ""},
+ {"completed, cancelled: unpaid", quietFacts(rCompleted, pCancelled, fNone), aRecordUnpaid, PurchaseUnpaid, 0, ""},
+ {"completed, capture failed (pFailed): unpaid", quietFacts(rCompleted, pFailed, fNone), aRecordUnpaid, PurchaseUnpaid, 0, ""},
+ {"completed, payment unread: wait", quietFacts(rCompleted, pUnknown, fNone), aWait, "", 0, ""},
+ {"failed, authorised: cancel the authorisation", quietFacts(rFailed, pAuthorised, fNone), aCancelAuthorisation, "", 0, ""},
+ {"failed, cancelled: failed, not charged", quietFacts(rFailed, pCancelled, fNone), aFinishFailed, PurchaseFailed, 0, ""},
+ {"failed, capture failed: failed, not charged", quietFacts(rFailed, pFailed, fNone), aFinishFailed, PurchaseFailed, 0, ""},
+ {"failed with an empty reason after capture: refund attempt 1", emptyReason, aCreateRefund, "", 1, ""},
+ {"failed, captured, attempt 2 stored but unanswered: resend attempt 2", resend, aCreateRefund, "", 2, ""},
+ {"failed, captured, refund attempt failed: a new attempt, alerted", quietFacts(rFailed, pCaptured, fFailed), aCreateRefund, "", 2, refundFailedAlert(1)},
+ {"failed, captured, refund pending: wait", quietFacts(rFailed, pCaptured, fPending), aWait, "", 0, ""},
+ {"failed, captured, second attempt pending: the first's failure alerted", secondPending, aAlert, "", 0, refundFailedAlert(1)},
+ {"failed, captured, second attempt pending, alerted: wait", secondPendingAlerted, aWait, "", 0, ""},
+ {"failed, captured, refunded in full: failed (refunded)", quietFacts(rFailed, pCaptured, fSucceeded), aFinishFailed, PurchaseFailed, 0, ""},
+ {"failed, payment unread: wait", quietFacts(rFailed, pUnknown, fNone), aWait, "", 0, ""},
+ }
+ for _, r := range rows {
+ d := decideTransfer(r.facts)
+ if d.Action != r.action || d.Terminal != r.terminal || d.RefundAttempt != r.attempt || d.Alert != r.alert {
+ t.Errorf("%s: got %v terminal=%q attempt=%d alert=%q, want %v terminal=%q attempt=%d alert=%q",
+ r.name, d.Action, d.Terminal, d.RefundAttempt, d.Alert, r.action, r.terminal, r.attempt, r.alert)
+ }
+ }
+
+ // Exhaustive over the enums: every combination the table does not
+ // list waits (quiet facts: no alert due, Checkout open).
+ listed := map[decideKey]transferAction{
+ {rNotSent, pAuthorised, fNone}: aSubmit, {rNotSent, pCancelled, fNone}: aFinishFailed,
+ {rPending, pAuthorised, fNone}: aCapture,
+ {rCompleted, pCaptured, fNone}: aRecordDone, {rCompleted, pAuthorised, fNone}: aCapture,
+ {rCompleted, pCancelled, fNone}: aRecordUnpaid, {rCompleted, pFailed, fNone}: aRecordUnpaid,
+ {rFailed, pAuthorised, fNone}: aCancelAuthorisation, {rFailed, pCancelled, fNone}: aFinishFailed,
+ {rFailed, pFailed, fNone}: aFinishFailed, {rFailed, pCaptured, fNone}: aCreateRefund,
+ {rFailed, pCaptured, fFailed}: aCreateRefund, {rFailed, pCaptured, fSucceeded}: aFinishFailed,
+ }
+ for reg := rNotSent; reg <= rFailed; reg++ {
+ for pay := pUnknown; pay <= pFailed; pay++ {
+ for refund := fNone; refund <= fFailed; refund++ {
+ f := quietFacts(reg, pay, refund)
+ f.Alerts = map[string]time.Time{alertCaptureRefused: decideBase, refundFailedAlert(1): decideBase}
+ want, ok := listed[decideKey{reg, pay, refund}]
+ if !ok {
+ // The refund outcome only matters once captured and failed:
+ // elsewhere the fNone row stands for every refund outcome.
+ want, ok = listed[decideKey{reg, pay, fNone}]
+ if reg == rFailed && pay == pCaptured {
+ want, ok = aWait, true
+ }
+ }
+ if !ok {
+ want = aWait
+ }
+ if d := decideTransfer(f); d.Action != want {
+ t.Errorf("%v/%v/%v: got %v, want %v", reg, pay, refund, d.Action, want)
+ }
+ }
+ }
+ }
+}
+
+// TestDecideTransferAlertsOncePerSchedule walks an unknown transfer through
+// its alert schedule: a day after submit, a day before the authorisation
+// lapses, then weekly after the first, each delivered exactly once; an
+// undelivered alert stays due.
+func TestDecideTransferAlertsOncePerSchedule(t *testing.T) {
+ submitted := decideBase
+ f := transferFacts{Registrar: rUnknown, Payment: pAuthorised, SubmittedAt: submitted,
+ CheckoutExpires: submitted.Add(-time.Hour), CaptureBefore: submitted.Add(6 * 24 * time.Hour), Alerts: map[string]time.Time{}}
+ var got []string
+ failedOnce := false
+ for now := submitted; now.Before(submitted.Add(30 * 24 * time.Hour)); now = now.Add(time.Hour) {
+ f.Now = now
+ d := decideTransfer(f)
+ switch d.Action {
+ case aWait:
+ case aAlert:
+ if !failedOnce {
+ // The first delivery fails: not recorded, so it stays due.
+ failedOnce = true
+ continue
+ }
+ got = append(got, fmt.Sprintf("%s@%s", d.Alert, now.Sub(submitted)))
+ f.Alerts[d.Alert] = now
+ default:
+ t.Fatalf("%s: unknown outcome chose %v", now.Sub(submitted), d.Action)
+ }
+ }
+ want := []string{"24h-unknown@25h0m0s", "lapse@120h0m0s", "weekly-unknown@193h0m0s", "weekly-unknown@361h0m0s", "weekly-unknown@529h0m0s", "weekly-unknown@697h0m0s"}
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("alerts = %v\nwant %v", got, want)
+ }
+
+ // The lapse alert is only for a hold still in place.
+ f = transferFacts{Registrar: rUnknown, Payment: pCaptured, SubmittedAt: submitted, CaptureBefore: submitted.Add(2 * 24 * time.Hour),
+ Alerts: map[string]time.Time{alertUnknown24h: submitted.Add(24 * time.Hour)}, Now: submitted.Add(36 * time.Hour)}
+ if d := decideTransfer(f); d.Action != aWait {
+ t.Fatalf("captured unknown transfer: %v %q, want wait", d.Action, d.Alert)
+ }
+ // A definite outcome has no unknown alerts, however late.
+ f.Registrar, f.Now, f.Alerts = rPending, submitted.Add(40*24*time.Hour), nil
+ if d := decideTransfer(f); d.Action != aWait {
+ t.Fatalf("pending transfer alerted: %v %q", d.Action, d.Alert)
+ }
+}
+
+// TestDecideTransferSimulation replays random transfers through the real
+// engine (advancePurchase over the registrar and billing fakes, a fresh
+// Server on restart) and asserts invariants I1-I10 after every pass. Each
+// run draws: whether and when the customer pays (a decline first,
+// sometimes), the registrar's answer to the request (refused with a
+// reason, accepted, lost on the way, lost after applying), lag before the
+// transfer shows, a final outcome (completed or failed, with or without a
+// reason) after a delay, an answer that later reads "none", authorisations
+// that lapse, refunds that sit pending or fail; and, on every pass, lost
+// and stale reads, lost and crashed sends, console crashes after any step,
+// failed alert deliveries and restarts. Then the faults stop, outcomes
+// become definite, an operator resolves (most of) what the registrar never
+// answered, and every purchase must end within 20 passes (I10).
+//
+// A failure names its seed: set TRANSFER_SIM_SEED to replay it. Each run
+// goes through the store, so 10,000 runs take about 70 s; the default is
+// 1,000 (200 with -short). TRANSFER_SIM_RUNS=10000 runs the full count.
+func TestDecideTransferSimulation(t *testing.T) {
+ runs := 1000
+ if testing.Short() {
+ runs = 200
+ }
+ if v := os.Getenv("TRANSFER_SIM_RUNS"); v != "" {
+ runs, _ = strconv.Atoi(v)
+ }
+ seed := uint64(time.Now().UnixNano())
+ if v := os.Getenv("TRANSFER_SIM_SEED"); v != "" {
+ seed, _ = strconv.ParseUint(v, 10, 64)
+ }
+ t.Cleanup(func() {
+ if t.Failed() {
+ t.Logf("TestDecideTransferSimulation: replay with TRANSFER_SIM_SEED=%d", seed)
+ }
+ })
+ sim := newTransferSim(t, seed)
+ for i := 0; i < runs && !t.Failed(); i++ {
+ sim.run(i)
+ }
+ t.Logf("seed %d: %d runs, %d passes, outcomes %v\npaths %v", seed, runs, sim.passes, sim.outcomes, sim.paths)
+}
+
+type transferSim struct {
+ t *testing.T
+ tf *transferFixture
+ seed uint64
+ rng *rand.Rand
+ reg *simRegistrar
+ bill *billingtest.Fake
+ // violation is a breach the provider wrapper saw at a send.
+ violation string
+ faults bool
+ // pageErr fails alert deliveries while faults are on.
+ pageFail float64
+ pages map[string][]simPage // purchase -> delivered alerts
+ leaks *codeLeakWriter
+
+ passes int
+ outcomes map[PurchaseState]int
+ paths map[string]int // how often each risky path was reached
+}
+
+type simPage struct {
+ reason string
+ at time.Time
+}
+
+// codeLeakWriter discards log output, remembering any line that holds an
+// auth code.
+type codeLeakWriter struct {
+ mu sync.Mutex
+ leaks []string
+}
+
+func (w *codeLeakWriter) Write(p []byte) (int, error) {
+ if bytes.Contains(p, []byte(simAuthPrefix)) {
+ w.mu.Lock()
+ w.leaks = append(w.leaks, string(p))
+ w.mu.Unlock()
+ }
+ return len(p), nil
+}
+
+const simAuthPrefix = "sim-auth-"
+
+func newTransferSim(t *testing.T, seed uint64) *transferSim {
+ tf := newTransferFixture(t)
+ tf.srv.cfg.DomainCatalog.DailyCap = 1 << 30
+ sim := &transferSim{t: t, tf: tf, seed: seed, pages: map[string][]simPage{}, outcomes: map[PurchaseState]int{}, paths: map[string]int{}, leaks: &codeLeakWriter{}}
+ log.SetOutput(sim.leaks)
+ t.Cleanup(func() { log.SetOutput(os.Stderr) })
+ pageDomainPurchase = func(_ context.Context, _, _, body string) error {
+ if sim.faults && sim.rng.Float64() < sim.pageFail {
+ return errors.New("sim: page lost")
+ }
+ id, reason := pageField(body, "Purchase: "), pageField(body, "Reason: ")
+ sim.pages[id] = append(sim.pages[id], simPage{reason: reason, at: sim.tf.now})
+ return nil
+ }
+ transferStepHook = func(step string) error {
+ rate := 0.04
+ if strings.HasPrefix(step, "refund:") {
+ rate = 0.15
+ }
+ if sim.faults && sim.rng.Float64() < rate {
+ sim.paths["crash:"+step]++
+ return errors.New("sim: crash after " + step)
+ }
+ return nil
+ }
+ t.Cleanup(func() { transferStepHook = nil })
+ return sim
+}
+
+func pageField(body, label string) string {
+ _, rest, ok := strings.Cut(body, label)
+ if !ok {
+ return ""
+ }
+ line, _, _ := strings.Cut(rest, "\n")
+ return line
+}
+
+// simRegistrar is the registrar fake with the simulation's faults: lag
+// before an accepted transfer shows, a transfer that later reads "none",
+// failed and stale status reads.
+type simRegistrar struct {
+ *registrartest.Fake
+ sim *transferSim
+ lag int // status reads that still say none after acceptance
+ hidden bool // after acceptance, reads say none for good
+ dropped bool // failed, then dropped to none before or after a read
+ acceptedAt time.Time // when the registrar accepted it, zero if never
+ finalAt time.Time // when it moves to its final outcome
+ final registrar.TransferStatus // that outcome
+ prev *registrar.TransferStatus // the previous state, for stale reads
+ requests int
+}
+
+func (r *simRegistrar) RequestTransfer(ctx context.Context, req registrar.TransferRequest) (registrar.TransferStatus, error) {
+ r.requests++
+ st, err := r.Fake.RequestTransfer(ctx, req)
+ if cur, ok := r.Fake.Transfers[req.Domain]; ok && cur.State == registrar.TransferPending && r.acceptedAt.IsZero() {
+ r.acceptedAt = r.sim.tf.now
+ }
+ return st, err
+}
+
+func (r *simRegistrar) TransferStatus(ctx context.Context, domain string) (registrar.TransferStatus, error) {
+ if r.sim.faults && r.sim.rng.Float64() < 0.1 {
+ return registrar.TransferStatus{}, fmt.Errorf("%w: sim: read lost", registrar.ErrIndeterminate)
+ }
+ st, err := r.Fake.TransferStatus(ctx, domain)
+ if err != nil || st.State == registrar.TransferNone {
+ return st, err
+ }
+ if r.lag > 0 && r.sim.faults {
+ r.lag--
+ return registrar.TransferStatus{State: registrar.TransferNone}, nil
+ }
+ if r.hidden && (st.State == registrar.TransferPending || r.sim.rng.Float64() < 0.5) && r.prev != nil {
+ return registrar.TransferStatus{State: registrar.TransferNone}, nil
+ }
+ if r.sim.faults && r.prev != nil && r.sim.rng.Float64() < 0.1 {
+ return *r.prev, nil
+ }
+ return st, nil
+}
+
+// unanswered: the registrar never shows the console a definite outcome (it
+// never got the request, hides it, or dropped a failure to "none"), so only
+// an operator can settle it.
+func (r *simRegistrar) unanswered() bool { return r.hidden || r.dropped || r.acceptedAt.IsZero() }
+
+// simBilling is the billing fake as the simulation's console sees it:
+// refunds listed in any order (the real provider lists newest first, the
+// fake oldest first: the engine must not depend on either), and every
+// refund create checked against what is outstanding.
+type simBilling struct {
+ *billingtest.Fake
+ sim *transferSim
+}
+
+func (b *simBilling) Refunds(ctx context.Context, pi string) ([]billing.RefundInfo, error) {
+ list, err := b.Fake.Refunds(ctx, pi)
+ b.sim.rng.Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] })
+ return list, err
+}
+
+// Send checks a refund create: attempt n is only ever made once every
+// earlier attempt has failed (I6).
+func (b *simBilling) Send(ctx context.Context, p billing.Prepared) (billing.Result, error) {
+ if p.Kind == billing.PreparedRefund {
+ var body struct {
+ Intent string
+ Attempt int
+ }
+ if err := json.Unmarshal(p.Body, &body); err != nil {
+ b.sim.violation = "refund body: " + err.Error()
+ }
+ held := b.Fake.HeaderlessTimeout
+ b.Fake.HeaderlessTimeout = 0
+ list, _ := b.Fake.Refunds(ctx, body.Intent)
+ b.Fake.HeaderlessTimeout = held
+ for _, r := range list {
+ if r.Attempt < body.Attempt && !(r.Status == billing.RefundFailed || r.Status == billing.RefundCanceled) {
+ b.sim.violation = fmt.Sprintf("I6: refund attempt %d sent while attempt %d is %s", body.Attempt, r.Attempt, r.Status)
+ }
+ }
+ }
+ return b.Fake.Send(ctx, p)
+}
+
+// advanceProvider moves the registrar to its final outcome when due.
+func (r *simRegistrar) advanceProvider(domain string) {
+ if r.acceptedAt.IsZero() || r.finalAt.IsZero() || r.sim.tf.now.Before(r.finalAt) {
+ return
+ }
+ cur, ok := r.Fake.Transfers[domain]
+ if !ok || cur.State != registrar.TransferPending {
+ return
+ }
+ pending := cur
+ r.prev = &pending
+ r.Fake.Advance(domain, r.final)
+ if r.final.State == registrar.TransferFailed {
+ // The fake keeps a failed transfer listed; a real registrar may
+ // drop it to "none" later, which must change nothing (I9).
+ if r.sim.rng.Float64() < 0.5 {
+ delete(r.Fake.Transfers, domain)
+ r.dropped = true
+ }
+ }
+}
+
+func (sim *transferSim) chance(p float64) bool { return sim.rng.Float64() < p }
+
+func (sim *transferSim) tick(d time.Duration) {
+ sim.tf.now = sim.tf.now.Add(d)
+ sim.bill.AdvanceProvider(d)
+}
+
+func (sim *transferSim) fail(i int, format string, args ...any) {
+ sim.t.Helper()
+ sim.t.Fatalf("seed %d run %d: %s", sim.seed, i, fmt.Sprintf(format, args...))
+}
+
+// run is one purchase from insert to its end (or its last live pass).
+func (sim *transferSim) run(i int) {
+ sim.rng = rand.New(rand.NewPCG(sim.seed, uint64(i)))
+ tf := sim.tf
+ ctx := context.Background()
+ domain := fmt.Sprintf("sim%d.com", i)
+ sim.faults = true
+ sim.pageFail = []float64{0, 0.1, 0.5}[sim.rng.IntN(3)]
+
+ // Fresh fakes per run keep the providers' lists short.
+ bill := billingtest.New()
+ bill.SetProviderClock(tf.now)
+ bill.LapseAuthorisations = sim.chance(0.3)
+ bill.CaptureWindow = []time.Duration{0, -1, 26 * time.Hour, 3 * 24 * time.Hour}[sim.rng.IntN(4)]
+ sim.bill = bill
+ sim.violation = ""
+ tf.srv.cfg.Billing.Provider = &simBilling{Fake: bill, sim: sim}
+ reg := &simRegistrar{Fake: registrartest.New(), sim: sim, lag: sim.rng.IntN(4), hidden: sim.chance(0.04)}
+ reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 1 << 30}
+ reasons := []string{"auth_code", "rejected", "timeout", "", "something-new"}
+ switch roll := sim.rng.Float64(); {
+ case roll < 0.15:
+ reg.Transfers[domain] = registrar.TransferStatus{State: registrar.TransferFailed, Reason: reasons[sim.rng.IntN(len(reasons))]}
+ case roll < 0.30:
+ reg.RequestErr, reg.RequestApplies = registrar.ErrIndeterminate, true
+ case roll < 0.36:
+ reg.RequestErr, reg.RequestApplies = registrar.ErrIndeterminate, false // never arrives
+ }
+ reg.finalAt = tf.now.Add(time.Duration(sim.rng.IntN(10*24*60)+30) * time.Minute)
+ if sim.chance(0.6) {
+ reg.final = registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{Domain: domain, RegistrarID: "reg-" + domain, Expires: tf.now.AddDate(1, 0, 0).Truncate(time.Second)}}
+ } else {
+ reg.final = registrar.TransferStatus{State: registrar.TransferFailed, Reason: reasons[sim.rng.IntN(len(reasons))]}
+ }
+ sim.reg = reg
+ tf.srv.cfg.Registrar = reg
+
+ code := fmt.Sprintf("%s%d", simAuthPrefix, i)
+ now := tf.now
+ p := DomainPurchase{ID: newDomainPurchaseID(), Kind: PurchaseKindTransfer, AccountID: tf.acct.ID, Domain: domain, Currency: "usd", Amount: 1200,
+ State: PurchaseAwaitingPayment, CheckoutExpires: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now,
+ purchaseDetails: purchaseDetails{Principal: "buyer@example.test", Contact: purchaseContact(), OwnerHandle: "contact-sim", AuthCode: code,
+ Nameservers: []string{"ns1.example-dns.test", "ns2.example-dns.test"}}}
+ if err := tf.st.CreateDomainPurchase(p); err != nil {
+ sim.fail(i, "insert: %v", err)
+ }
+
+ // The customer: pays (perhaps after a decline) at some point in the
+ // hour, or never.
+ pays := sim.chance(0.85)
+ payAt := now.Add(time.Duration(sim.rng.IntN(55)) * time.Minute)
+ declineFirst := sim.chance(0.2)
+ refundPending := sim.chance(0.6)
+ var last *DomainPurchase
+ stored := func() *DomainPurchase {
+ got, err := tf.st.DomainPurchase(p.ID)
+ if err != nil || got == nil {
+ sim.fail(i, "read: %+v %v", got, err)
+ }
+ return got
+ }
+ customer := func() {
+ if !pays || tf.now.Before(payAt) {
+ return
+ }
+ session := sim.session(p.ID)
+ if session == "" {
+ return
+ }
+ if declineFirst {
+ declineFirst = false
+ _ = bill.DeclinePaymentCheckout(session)
+ payAt = tf.now.Add(5 * time.Minute)
+ return
+ }
+ if _, err := bill.CompletePaymentCheckout(session); err == nil {
+ pays = false
+ }
+ }
+ pass := func() {
+ sim.passes++
+ customer()
+ reg.advanceProvider(domain)
+ if sim.faults {
+ bill.HeaderlessTimeout = sim.pick(0.08, 1)
+ bill.LoseNextResponse = sim.chance(0.05)
+ bill.CrashAfterSend = sim.chance(0.05)
+ bill.CrashBeforeSend = sim.chance(0.03)
+ bill.FailBeforeDelivery = sim.pick(0.03, 1)
+ }
+ if refundPending && sim.chance(0.7) {
+ bill.NextRefundStatus = billing.RefundPending
+ }
+ if sim.faults && sim.chance(0.05) {
+ sim.restart()
+ sim.paths["restart"]++
+ }
+ _ = tf.srv.advancePurchase(ctx, p.ID)
+ bill.HeaderlessTimeout, bill.LoseNextResponse, bill.CrashAfterSend, bill.CrashBeforeSend, bill.FailBeforeDelivery = 0, false, false, false, 0
+ bill.NextRefundStatus = ""
+ sim.settleRefunds(p.ID)
+ cur := stored()
+ if sim.violation != "" {
+ sim.fail(i, "%s", sim.violation)
+ }
+ sim.check(i, last, cur, code)
+ last = cur
+ }
+ steps := []time.Duration{time.Minute, 10 * time.Minute, 30 * time.Minute, 2 * time.Hour, 12 * time.Hour, 24 * time.Hour, 3 * 24 * time.Hour}
+ chaos := 12 + sim.rng.IntN(20)
+ liveNow := func() bool { return last == nil || purchaseLive(last.State) }
+ for n := 0; n < chaos && liveNow(); n++ {
+ pass()
+ if tf.now.Before(p.CheckoutExpires) && (pays || sim.chance(0.5)) {
+ // Inside the Checkout hour time moves in minutes, so the
+ // customer gets to pay before it expires.
+ sim.tick(time.Duration(1+sim.rng.IntN(12)) * time.Minute)
+ continue
+ }
+ sim.tick(steps[sim.rng.IntN(len(steps))])
+ }
+
+ // Stable: no more faults; outcomes become definite.
+ sim.faults = false
+ if !reg.acceptedAt.IsZero() && tf.now.Before(reg.finalAt) {
+ reg.finalAt = tf.now
+ }
+ refundPending = false
+ resolved := false
+ operatorLooks := sim.chance(0.7)
+ for n := 0; n < 20 && liveNow(); n++ {
+ cur := last
+ if !resolved && cur.Facts.Registrar == rUnknown && cur.Facts.Resolution == "" && reg.unanswered() && n >= 2 && operatorLooks {
+ // The registrar never answered (or answers "none"): the operator
+ // looks and records the outcome.
+ outcome := transferResolvedFailed
+ if _, ok := reg.Fake.Domains[domain]; ok {
+ outcome = transferResolvedCompleted
+ }
+ if _, status, msg := tf.srv.resolveTransfer(ctx, p.ID, outcome, "sim-operator"); status != http.StatusOK {
+ sim.fail(i, "resolve %s: %d %s", outcome, status, msg)
+ }
+ resolved = true
+ sim.paths["resolved:"+outcome]++
+ }
+ pass()
+ sim.tick(24 * time.Hour)
+ }
+ end := stored()
+ sim.outcomes[end.State]++
+ if end.Facts.Accepted && end.Facts.Registrar == rUnknown {
+ sim.paths["unknown after acceptance"]++
+ }
+ if end.Facts.RefundAttempt > 1 {
+ sim.paths["refund attempts > 1"]++
+ }
+ if end.Facts.RefundAttempt > 0 {
+ sim.paths["refunded"]++
+ }
+ if end.Facts.CaptureAttempted && end.State == PurchaseUnpaid {
+ sim.paths["unpaid after a capture attempt"]++
+ }
+ if end.Facts.Payment == pCancelled && end.Facts.Registrar != rNotSent {
+ sim.paths["hold ended after submit"]++
+ }
+ if len(sim.pages[p.ID]) > 0 {
+ sim.paths["alerted"]++
+ }
+ if purchaseLive(end.State) {
+ // Only an unknown the operator has not resolved may still be live.
+ if end.Facts.Registrar != rUnknown || end.Facts.Resolution != "" || !reg.unanswered() {
+ sim.fail(i, "I10: still live after 20 stable passes: %+v facts %+v", end, end.Facts)
+ }
+ sim.checkAlertSchedule(i, end)
+ }
+ sim.checkAlertsOnce(i, end)
+ // Each run stands alone: its rows go, so the store stays small.
+ for _, q := range []string{`DELETE FROM domain_purchases WHERE id=?`, `DELETE FROM domain_registrations WHERE domain=?`} {
+ arg := p.ID
+ if strings.Contains(q, "registrations") {
+ arg = domain
+ }
+ if _, err := tf.st.db.Exec(q, arg); err != nil {
+ sim.fail(i, "cleanup: %v", err)
+ }
+ }
+ delete(sim.pages, p.ID)
+}
+
+func (sim *transferSim) pick(p float64, n int) int {
+ if sim.chance(p) {
+ return n
+ }
+ return 0
+}
+
+func (sim *transferSim) restart() {
+ tf := sim.tf
+ srv, err := NewServer(tf.srv.cfg, tf.st)
+ if err != nil {
+ sim.t.Fatal(err)
+ }
+ srv.billing.ready.Store(true)
+ srv.consoleMail = tf.srv.consoleMail
+ srv.sendFederated = nil
+ srv.transferClock = func() time.Time { return tf.now }
+ tf.srv = srv
+}
+
+// session is the purchase's Checkout at the provider, found as a customer
+// would (by reference), whatever the console recorded.
+func (sim *transferSim) session(id string) string {
+ list, err := sim.bill.CustomerCheckouts(context.Background(), "cus_1", time.Unix(0, 0))
+ if err != nil {
+ return ""
+ }
+ for _, c := range list {
+ if c.Reference == id {
+ return c.ID
+ }
+ }
+ return ""
+}
+
+// settleRefunds moves pending refunds on: mostly succeeded, sometimes
+// failed; while faults are on, some stay pending.
+func (sim *transferSim) settleRefunds(id string) {
+ info, ok := sim.payment(id)
+ if !ok || info.PaymentIntent == "" {
+ return
+ }
+ list, _ := sim.bill.Refunds(context.Background(), info.PaymentIntent)
+ for _, r := range list {
+ if r.Status != billing.RefundPending {
+ continue
+ }
+ switch {
+ case sim.faults && sim.chance(0.4):
+ case sim.chance(0.35) && sim.faults:
+ _ = sim.bill.SettleRefund(r.ID, billing.RefundFailed)
+ default:
+ _ = sim.bill.SettleRefund(r.ID, billing.RefundSucceeded)
+ }
+ }
+}
+
+func (sim *transferSim) payment(id string) (billing.PaymentInfo, bool) {
+ session := sim.session(id)
+ if session == "" {
+ return billing.PaymentInfo{}, false
+ }
+ info, err := sim.bill.PaymentCheckout(context.Background(), session)
+ return info, err == nil
+}
+
+// check asserts I1-I9 on the record after a pass.
+func (sim *transferSim) check(i int, before, p *DomainPurchase, code string) {
+ ctx := context.Background()
+ info, _ := sim.payment(p.ID)
+ captured := info.IntentStatus == "succeeded"
+ var refunds []billing.RefundInfo
+ if info.PaymentIntent != "" {
+ refunds, _ = sim.bill.Refunds(ctx, info.PaymentIntent)
+ }
+ fullRefund := false
+ outstanding := 0
+ perAttempt := map[int]int{}
+ for _, r := range refunds {
+ perAttempt[r.Attempt]++
+ if r.Status == billing.RefundSucceeded && r.Amount == info.AmountTotal && r.Currency == info.Currency {
+ fullRefund = true
+ }
+ if r.Status == billing.RefundPending || r.Status == billing.RefundRequiresAction || r.Status == billing.RefundSucceeded {
+ outstanding++
+ }
+ }
+ live := purchaseLive(p.State)
+ reg := p.Facts.Registrar
+ if !live {
+ // I1: an end only on a definite registrar outcome, an operator's
+ // resolution, or before submit with nothing taken.
+ if !(reg == rCompleted || reg == rFailed || p.Facts.Resolution != "" || (reg == rNotSent && !captured)) {
+ sim.fail(i, "I1: ended %s with registrar %v: %+v", p.State, p.Facts.Registrar, p.Facts)
+ }
+ if info.IntentStatus == "requires_capture" {
+ sim.fail(i, "ended %s with the authorisation still held", p.State)
+ }
+ }
+ // Never settled blind: an outcome never seen accepted, unresolved,
+ // takes no money.
+ if reg == rUnknown && !p.Facts.Accepted && p.Facts.Resolution == "" && captured {
+ sim.fail(i, "captured while the outcome was unknown and never accepted")
+ }
+ switch p.State {
+ case PurchaseDone: // I2
+ if !captured {
+ sim.fail(i, "I2: done but not captured (%s)", info.IntentStatus)
+ }
+ if r, _ := sim.tf.st.DomainRegistrationFor(ctx, p.AccountID, p.Domain); r == nil || r.ZoneID != "" || !r.AutoRenew {
+ sim.fail(i, "done without its zoneless registration: %+v", r)
+ }
+ case PurchaseUnpaid: // I3
+ if _, ok := sim.reg.Fake.Domains[p.Domain]; !ok || captured {
+ sim.fail(i, "I3: unpaid but completed=%v captured=%v", ok, captured)
+ }
+ if r, _ := sim.tf.st.DomainRegistrationFor(ctx, p.AccountID, p.Domain); r == nil || r.AutoRenew {
+ sim.fail(i, "unpaid without its registration, renewal off: %+v", r)
+ }
+ case PurchaseFailed, PurchaseExpired: // I4
+ if captured && !fullRefund {
+ sim.fail(i, "I4: %s with money taken and no full refund: %+v", p.State, refunds)
+ }
+ }
+ // I5: the request is sent at most once.
+ if sim.reg.requests > 1 {
+ sim.fail(i, "I5: %d transfer requests", sim.reg.requests)
+ }
+ // I6: at most one refund outstanding; each attempt made at most once,
+ // so a failed attempt is never sent again; the attempt only moves on.
+ if outstanding > 1 {
+ sim.fail(i, "I6: %d refunds outstanding: %+v", outstanding, refunds)
+ }
+ for attempt, n := range perAttempt {
+ if n > 1 || attempt < 1 {
+ sim.fail(i, "I6: attempt %d made %d times: %+v", attempt, n, refunds)
+ }
+ }
+ if before != nil && p.Facts.RefundAttempt < before.Facts.RefundAttempt {
+ sim.fail(i, "I6: refund attempt went back %d -> %d", before.Facts.RefundAttempt, p.Facts.RefundAttempt)
+ }
+ if p.Facts.RefundID != "" {
+ for _, r := range refunds {
+ if r.ID == p.Facts.RefundID && r.Attempt != p.Facts.RefundAttempt {
+ sim.fail(i, "I6: refund %s of attempt %d recorded for attempt %d", r.ID, r.Attempt, p.Facts.RefundAttempt)
+ }
+ }
+ }
+ changed := before == nil || before.Revision != p.Revision
+ // I7: live means it holds the domain and blocks deletion.
+ if live && changed {
+ doms, err := sim.tf.st.DomainObligations(ctx, p.AccountID)
+ if err != nil || !slices.Contains(doms, p.Domain) {
+ sim.fail(i, "I7: live purchase not an obligation: %v %v", doms, err)
+ }
+ }
+ // I8: no auth code once submitted or ended, anywhere in the record.
+ if (p.Facts.Registrar != rNotSent || !live) && changed {
+ var raw string
+ if err := sim.tf.st.db.QueryRow(`SELECT details FROM domain_purchases WHERE id=?`, p.ID).Scan(&raw); err != nil || p.AuthCode != "" || strings.Contains(raw, code) {
+ sim.fail(i, "I8: auth code kept in %s: %v", p.State, err)
+ }
+ }
+ if len(sim.leaks.leaks) > 0 {
+ sim.fail(i, "auth code logged: %q", sim.leaks.leaks[0])
+ }
+ // I9: definite outcomes are sticky.
+ if before != nil && (before.Facts.Registrar == rCompleted || before.Facts.Registrar == rFailed) && p.Facts.Registrar != before.Facts.Registrar {
+ sim.fail(i, "I9: %v replaced by %v", before.Facts.Registrar, p.Facts.Registrar)
+ }
+}
+
+// checkAlertsOnce: no alert kind but the weekly one is delivered twice for
+// a purchase, and weekly ones are a week apart.
+func (sim *transferSim) checkAlertsOnce(i int, p *DomainPurchase) {
+ seen := map[string]int{}
+ var weekly []time.Time
+ for _, pg := range sim.pages[p.ID] {
+ seen[pg.reason]++
+ if pg.reason == transferAlertReason(alertUnknownWeekly) {
+ weekly = append(weekly, pg.at)
+ }
+ }
+ for reason, n := range seen {
+ if n > 1 && reason != transferAlertReason(alertUnknownWeekly) {
+ sim.fail(i, "I10: alert %q delivered %d times", reason, n)
+ }
+ }
+ for k := 1; k < len(weekly); k++ {
+ if weekly[k].Sub(weekly[k-1]) < transferUnknownRepeat {
+ sim.fail(i, "I10: weekly alerts %s apart", weekly[k].Sub(weekly[k-1]))
+ }
+ }
+}
+
+// checkAlertSchedule: a transfer still unknown at the end has had each due
+// alert: the day-after one, and the weekly one no more than a pass late.
+func (sim *transferSim) checkAlertSchedule(i int, p *DomainPurchase) {
+ now := sim.tf.now
+ if p.Facts.SubmittedAt.IsZero() || now.Before(p.Facts.SubmittedAt.Add(transferUnknownAlertAfter+24*time.Hour)) {
+ return
+ }
+ var first, latest time.Time
+ for _, pg := range sim.pages[p.ID] {
+ switch pg.reason {
+ case transferAlertReason(alertUnknown24h):
+ first = pg.at
+ latest = maxTime(latest, pg.at)
+ case transferAlertReason(alertUnknownWeekly):
+ latest = maxTime(latest, pg.at)
+ }
+ }
+ if first.IsZero() {
+ sim.fail(i, "I10: no day-after alert for an unknown transfer submitted %s ago", now.Sub(p.Facts.SubmittedAt))
+ }
+ if now.Sub(latest) > transferUnknownRepeat+2*24*time.Hour {
+ sim.fail(i, "I10: weekly alert overdue: last %s ago", now.Sub(latest))
+ }
+}
+
+func maxTime(a, b time.Time) time.Time {
+ if b.After(a) {
+ return b
+ }
+ return a
+}
diff --git a/internal/console/domaintransfer_facts.go b/internal/console/domaintransfer_facts.go
index 433a770d9..649348a19 100644
--- a/internal/console/domaintransfer_facts.go
+++ b/internal/console/domaintransfer_facts.go
@@ -77,8 +77,13 @@ type transferFacts struct {
Registrar registrarOutcome `json:",omitempty"`
RegistrarReason string `json:",omitempty"`
Completed *registrar.Registered `json:",omitempty"`
- Payment paymentOutcome `json:",omitempty"`
- Refund refundOutcome `json:",omitempty"`
+ // Accepted is set once a status read has shown the transfer pending or
+ // completed. It survives a later "none" or unreadable answer (which
+ // reads as rUnknown), so a transfer the registrar accepted is still
+ // captured while its outcome is unknown.
+ Accepted bool `json:",omitempty"`
+ Payment paymentOutcome `json:",omitempty"`
+ Refund refundOutcome `json:",omitempty"`
// RefundAttempt numbers refund attempts from 1; 0 is untagged.
RefundAttempt int `json:",omitempty"`
RefundID string `json:",omitempty"`
diff --git a/internal/console/domaintransfer_resolve.go b/internal/console/domaintransfer_resolve.go
new file mode 100644
index 000000000..a510a7c52
--- /dev/null
+++ b/internal/console/domaintransfer_resolve.go
@@ -0,0 +1,130 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// The operator's door for a transfer whose outcome the registrar never made
+// definite (spec §12.4, builder check T6): POST
+// /api/cli/system/domains/purchases/{id}/resolve {"outcome","note"}. A
+// person on the store operator list only (apiSystemOperator, no ops-account
+// owner fallback), closed to every service credential, not registered where
+// buying is off, and audited. "completed" needs the registrar to show the
+// domain in our account; its registration is what the purchase records.
+
+// transferResolveCopy is the door's operator-facing answers (drafts).
+var transferResolveCopy = map[string]string{
+ "outcome": `outcome must be "failed" or "completed"`,
+ "notUnknown": "only a live transfer whose outcome is unknown can be resolved",
+ "notOurs": "the registrar does not show this domain in our account, so it cannot be resolved as completed",
+ "registrar": "could not read the domain at the registrar; try again",
+ "busy": "could not record the resolution; try again",
+}
+
+// errTransferNotUnknown refuses a resolution of anything but a live transfer
+// whose recorded registrar outcome is unknown and unresolved.
+var errTransferNotUnknown = errors.New("console: transfer is not unknown")
+
+const maxResolveNote = 500
+
+func (s *Server) handleAPITransferResolve(w http.ResponseWriter, r *http.Request) {
+ addr, ok := s.apiSystemOperator(w, r)
+ if !ok {
+ return
+ }
+ if !s.domainPurchaseReady() {
+ http.NotFound(w, r)
+ return
+ }
+ var in struct {
+ Outcome string `json:"outcome"`
+ Note string `json:"note"`
+ }
+ if !readJSONStrictLimit(w, r, &in, 8<<10) {
+ return
+ }
+ if in.Outcome != transferResolvedFailed && in.Outcome != transferResolvedCompleted {
+ jsonError(w, http.StatusUnprocessableEntity, transferResolveCopy["outcome"])
+ return
+ }
+ if len(in.Note) > maxResolveNote {
+ in.Note = in.Note[:maxResolveNote]
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ p, status, msg := s.resolveTransfer(ctx, r.PathValue("id"), in.Outcome, addr)
+ if status != http.StatusOK {
+ if status == http.StatusNotFound {
+ http.NotFound(w, r)
+ return
+ }
+ jsonError(w, status, msg)
+ return
+ }
+ s.auditSystem(addr, "domain.transfer.resolve", fmt.Sprintf("purchase %s domain %s outcome %s note %q", p.ID, p.Domain, in.Outcome, in.Note))
+ s.nudgePurchase(p.ID)
+ writeJSON(w, http.StatusOK, map[string]string{"id": p.ID, "domain": p.Domain, "state": string(p.State), "resolution": in.Outcome})
+}
+
+// resolveTransfer records outcome as the operator's resolution of an
+// unknown transfer. The answer is an HTTP status and, when not 200, its
+// message.
+func (s *Server) resolveTransfer(ctx context.Context, id, outcome, by string) (*DomainPurchase, int, string) {
+ p, err := s.store.DomainPurchase(id)
+ if err != nil {
+ return nil, http.StatusServiceUnavailable, transferResolveCopy["busy"]
+ }
+ if p == nil || purchaseKindOf(p) != PurchaseKindTransfer {
+ return nil, http.StatusNotFound, ""
+ }
+ if !transferResolvable(p) {
+ return nil, http.StatusConflict, transferResolveCopy["notUnknown"]
+ }
+ var completed *registrar.Registered
+ if outcome == transferResolvedCompleted {
+ r, found, err := s.cfg.Registrar.Lookup(ctx, p.Domain)
+ if err != nil {
+ log.Printf("console: transfer %s: resolve lookup: %v", p.ID, err)
+ return nil, http.StatusBadGateway, transferResolveCopy["registrar"]
+ }
+ if r.Domain == "" {
+ r.Domain = p.Domain
+ }
+ if !found || r.Domain != p.Domain || r.RegistrarID == "" {
+ return nil, http.StatusConflict, transferResolveCopy["notOurs"]
+ }
+ completed = &r
+ }
+ err = s.purchaseMutation(ctx, p, func(ctx context.Context) error {
+ if !transferResolvable(p) {
+ return errTransferNotUnknown
+ }
+ return s.movePurchase(ctx, p, p.State, func(q *DomainPurchase) {
+ q.Facts.Resolution, q.ResolvedBy = outcome, by
+ if completed != nil {
+ c := *completed
+ q.Facts.Completed = &c
+ }
+ })
+ })
+ switch {
+ case errors.Is(err, errTransferNotUnknown), errors.Is(err, ErrPurchaseStateMoved):
+ return nil, http.StatusConflict, transferResolveCopy["notUnknown"]
+ case err != nil:
+ log.Printf("console: transfer %s: resolve: %v", p.ID, err)
+ return nil, http.StatusServiceUnavailable, transferResolveCopy["busy"]
+ }
+ log.Printf("console: transfer %s: resolved %s by %s", p.ID, outcome, by)
+ return p, http.StatusOK, ""
+}
+
+func transferResolvable(p *DomainPurchase) bool {
+ return purchaseLive(p.State) && p.Facts.Registrar == rUnknown && p.Facts.Resolution == ""
+}
diff --git a/internal/console/domaintransfer_start.go b/internal/console/domaintransfer_start.go
new file mode 100644
index 000000000..6287581da
--- /dev/null
+++ b/internal/console/domaintransfer_start.go
@@ -0,0 +1,180 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/domainreg"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// transferQuote is what a transfer would cost and the nameservers it would
+// keep, read from public DNS at check (registration only, R13: a transfer
+// never changes them).
+type transferQuote struct {
+ Quote domainreg.Quote
+ Nameservers []string
+}
+
+// transferPrice is a TLD's transfer price in currency: its transfer price
+// when set for the currency, else its renewal price (spec §12.4).
+func transferPrice(tld domainreg.TLD, currency string) int64 {
+ if price, ok := tld.Transfer[currency]; ok {
+ return price
+ }
+ return tld.Renew[currency]
+}
+
+// quoteTransfer checks that the account may transfer name in now and
+// prices it. Every refusal comes before any payment.
+func (s *Server) quoteTransfer(ctx context.Context, acct *Account, name string) (transferQuote, *doorRefusal) {
+ return s.admitDomainTransfer(ctx, acct, name)
+}
+
+// admitDomainTransfer is admitDomainDoor plus a transfer's own checks, in
+// order: the TLD must be in the catalog, marked transferable and priced in
+// the account's currency; the shared check budget; the domain must not be
+// registered here already (by any account) nor claimed by another account,
+// nor have a live purchase; the registrar's transfer check and the catalog's
+// transfer quote; no DS record at the parent (fail closed on an error); and
+// nameservers readable from public DNS.
+func (s *Server) admitDomainTransfer(ctx context.Context, acct *Account, name string, country ...string) (transferQuote, *doorRefusal) {
+ a, ref := s.admitDomainDoor(ctx, acct, name, PurchaseKindTransfer, country...)
+ if ref != nil {
+ return transferQuote{}, ref
+ }
+ if a.own != nil {
+ return transferQuote{Quote: domainreg.Quote{Domain: a.own.Domain, Currency: a.own.Currency, Price: a.own.Amount}, Nameservers: a.own.Nameservers}, nil
+ }
+ name = a.name
+ if !a.offered || !a.tld.Transferable {
+ return transferQuote{}, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainTransferCopy["notOffered"]}
+ }
+ if transferPrice(a.tld, a.currency) <= 0 {
+ return transferQuote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ if !s.domainChecks.allow(acct.ID) {
+ return transferQuote{}, &doorRefusal{Status: http.StatusTooManyRequests, Msg: domainBuyCopy["rate"]}
+ }
+ registered, err := s.domainRegisteredHere(ctx, name)
+ if err != nil {
+ return transferQuote{}, purchaseUnavailable(PurchaseKindTransfer)
+ }
+ if registered {
+ log.Printf("console: domain transfer: account=%s domain=%s reason=already registered here", acct.Sqid, name)
+ return transferQuote{}, claimRefusal(name, domains.ErrHostUnavailable)
+ }
+ if ref := s.domainHostsRefusal(ctx, acct, name, PurchaseKindTransfer); ref != nil {
+ return transferQuote{}, ref
+ }
+ if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil {
+ return transferQuote{}, ref
+ }
+ check, err := s.cfg.Registrar.CheckTransfer(ctx, name)
+ if err != nil {
+ if errors.Is(err, registrar.ErrSetup) {
+ s.purchaseRefusalAlert(ctx, acct, name, "registrar-setup", err.Error())
+ }
+ log.Printf("console: domain transfer check %s: %v", name, err)
+ return transferQuote{}, purchaseUnavailable(PurchaseKindTransfer)
+ }
+ q, err := s.cfg.DomainCatalog.QuoteTransfer(name, a.currency, check)
+ if err != nil {
+ return transferQuote{}, s.transferQuoteRefusal(ctx, acct, name, a.suffix, check, err)
+ }
+ signed, err := s.lookupDomainDS(ctx, name)
+ if err != nil {
+ log.Printf("console: domain transfer %s: DS lookup: %v", name, err)
+ return transferQuote{}, &doorRefusal{Status: http.StatusServiceUnavailable, Msg: domainTransferCopy["dnsUnread"]}
+ }
+ if signed {
+ return transferQuote{}, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainTransferCopy["dnssec"]}
+ }
+ ns, err := s.lookupDomainNS(ctx, name)
+ if err != nil || len(ns) == 0 {
+ log.Printf("console: domain transfer %s: nameservers: %d read, error %v", name, len(ns), err)
+ return transferQuote{}, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainTransferCopy["nameservers"]}
+ }
+ return transferQuote{Quote: q, Nameservers: ns}, nil
+}
+
+// transferQuoteRefusal is the plain refusal for a QuoteTransfer error. Why
+// a domain cannot move now comes from the check's reason, never from the
+// error's text.
+func (s *Server) transferQuoteRefusal(ctx context.Context, acct *Account, name, suffix string, check registrar.TransferCheck, err error) *doorRefusal {
+ switch {
+ case errors.Is(err, domainreg.ErrNotTransferable):
+ return transferNotNowRefusal(check.Reason)
+ case errors.Is(err, domainreg.ErrPremium):
+ return &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["premium"]}
+ case errors.Is(err, domainreg.ErrTLDNotOffered):
+ return &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainTransferCopy["notOffered"]}
+ case errors.Is(err, domainreg.ErrCostAboveCeiling):
+ s.purchaseRefusalAlert(ctx, acct, name, "transfer-cost:"+suffix, "registrar transfer cost above ceiling")
+ }
+ log.Printf("console: domain transfer quote %s: %v", name, err)
+ return purchaseUnavailable(PurchaseKindTransfer)
+}
+
+// maxAuthCode bounds the transfer code a start accepts.
+const maxAuthCode = 256
+
+// validAuthCode: present, bounded, and printable without spaces.
+func validAuthCode(code string) bool {
+ if code == "" || len(code) > maxAuthCode {
+ return false
+ }
+ for _, r := range code {
+ if r <= ' ' || r == 0x7f {
+ return false
+ }
+ }
+ return true
+}
+
+// startDomainTransfer starts a transfer in: the checks of quoteTransfer, the
+// auth code and contact, then the shared start under the billing hold. A
+// non-nil third result supplies the replacement quote for confirmation. An
+// owner's live transfer of the name resumes at its stored price (its auth
+// code is not replaced); a live purchase of the name is refused.
+//
+// authCode is a secret: it goes only into the purchase record, which clears
+// it when the transfer is submitted or ends before that.
+func (s *Server) startDomainTransfer(ctx context.Context, acct *Account, name, authCode string, contact purchaseContactSelection, principal string, confirmed domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) {
+ defer s.planLock(acct)()
+ c, saved, contactOK, err := s.purchaseContactFor(ctx, acct, contact)
+ if err != nil {
+ return nil, "", nil, purchaseUnavailable(PurchaseKindTransfer)
+ }
+ tq, ref := s.admitDomainTransfer(ctx, acct, name, c.Country)
+ if ref != nil {
+ return nil, "", nil, ref
+ }
+ q := tq.Quote
+ own, ref := s.ownLivePurchaseOfKind(ctx, acct.ID, q.Domain, PurchaseKindTransfer)
+ if ref != nil {
+ return nil, "", nil, ref
+ }
+ if own != nil {
+ if confirmed.Currency != q.Currency || confirmed.Price != q.Price {
+ return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict)
+ }
+ p, link, ref := s.resumeDomainPurchase(ctx, own)
+ return p, link, nil, ref
+ }
+ code := strings.TrimSpace(authCode)
+ if !validAuthCode(code) {
+ return nil, "", nil, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainTransferCopy["authCode"]}
+ }
+ if !contactOK || c.Validate() != nil {
+ return nil, "", nil, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["contactError"]}
+ }
+ tld := q.TLD
+ return s.startPurchaseCheckout(ctx, acct, purchaseStart{Kind: PurchaseKindTransfer, Principal: principal, Confirmed: confirmed,
+ Contact: c, Saved: saved, Price: func(currency string) int64 { return transferPrice(s.cfg.DomainCatalog.TLDs[tld], currency) },
+ Details: purchaseDetails{AuthCode: code, Nameservers: tq.Nameservers}}, q)
+}
diff --git a/internal/console/domaintransfer_test.go b/internal/console/domaintransfer_test.go
new file mode 100644
index 000000000..b46c21e8d
--- /dev/null
+++ b/internal/console/domaintransfer_test.go
@@ -0,0 +1,919 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "os"
+ "reflect"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/domainreg"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+const testAuthCode = "Xy7-secret-CODE-9"
+
+// transferFixture is newPurchaseFixture with transfers on: .com marked
+// transferable, shop.com transferable at the registrar, public DNS faked,
+// a controlled transfer clock and a recording alert sink.
+type transferFixture struct {
+ *purchaseFixture
+ now time.Time
+ ns []*net.NS
+ nsErr error
+ ds bool
+ dsErr error
+
+ mu sync.Mutex
+ pages []string
+ pageErr error
+}
+
+func newTransferFixture(t *testing.T) *transferFixture {
+ t.Helper()
+ f := newPurchaseFixture(t)
+ tf := &transferFixture{purchaseFixture: f, now: f.fake.ConsoleNow(),
+ ns: []*net.NS{{Host: "NS2.Example-DNS.test."}, {Host: "ns1.example-dns.test"}}}
+ f.fake.SetProviderClock(tf.now)
+ cat := f.srv.cfg.DomainCatalog
+ com := cat.TLDs["com"]
+ com.Renew, com.Transferable = map[string]int64{"usd": 1300, "eur": 1350, "gbp": 1150}, true
+ com.Transfer = map[string]int64{"usd": 1200, "eur": 1250}
+ cat.TLDs["com"] = com
+ cat.TLDs["net"] = domainreg.TLD{Register: map[string]int64{"usd": 1500}, Renew: map[string]int64{"usd": 1300}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}
+ f.reg.TransferChecks["shop.com"] = registrar.TransferCheck{Transferable: true, Cost: registrar.Money{Currency: "usd", Minor: 800}}
+ f.srv.cfg.LookupNS = func(context.Context, string) ([]*net.NS, error) { return tf.ns, tf.nsErr }
+ f.srv.cfg.LookupDS = func(context.Context, string) (bool, error) { return tf.ds, tf.dsErr }
+ f.srv.transferClock = func() time.Time { return tf.now }
+ pageDomainPurchase = func(_ context.Context, _, _, body string) error {
+ tf.mu.Lock()
+ defer tf.mu.Unlock()
+ if tf.pageErr != nil {
+ return tf.pageErr
+ }
+ tf.pages = append(tf.pages, body)
+ return nil
+ }
+ return tf
+}
+
+// tick moves the transfer clock and the provider's together.
+func (tf *transferFixture) tick(d time.Duration) {
+ tf.now = tf.now.Add(d)
+ tf.fake.AdvanceProvider(d)
+}
+
+// restart is a fresh Server over the same store and configuration.
+func (tf *transferFixture) restart(t *testing.T) {
+ t.Helper()
+ srv, err := NewServer(tf.srv.cfg, tf.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv.billing.ready.Store(true)
+ srv.consoleMail = tf.srv.consoleMail
+ srv.sendFederated = nil
+ srv.transferClock = func() time.Time { return tf.now }
+ tf.srv = srv
+}
+
+func (tf *transferFixture) alerts(kind string) int {
+ tf.mu.Lock()
+ defer tf.mu.Unlock()
+ n := 0
+ for _, b := range tf.pages {
+ if strings.Contains(b, "Reason: "+transferAlertReason(kind)+"\n") {
+ n++
+ }
+ }
+ return n
+}
+
+// transferQuoteFor is the quote the account would be shown for the test
+// contact's country.
+func transferQuoteFor(s *Server, acct *Account) domainreg.Quote {
+ currency, _ := s.billing.cfg.Book.ChooseCurrency("", purchaseContact().Country)
+ if b, _ := s.store.BillingAccount(acct.ID); b != nil && b.Currency != "" {
+ currency = b.Currency
+ }
+ return domainreg.Quote{Currency: currency, Price: transferPrice(s.cfg.DomainCatalog.TLDs["com"], currency)}
+}
+
+func (tf *transferFixture) startTransfer(t *testing.T, acct *Account, name string) (*DomainPurchase, *doorRefusal) {
+ t.Helper()
+ c := purchaseContact()
+ p, link, _, ref := tf.srv.startDomainTransfer(context.Background(), acct, name, testAuthCode, purchaseContactSelection{New: &c}, "buyer@example.test", transferQuoteFor(tf.srv, acct))
+ if ref == nil && (p == nil || (link == "" && p.State == PurchaseAwaitingPayment)) {
+ t.Fatalf("start: %+v %q", p, link)
+ }
+ return p, ref
+}
+
+func (tf *transferFixture) start(t *testing.T) *DomainPurchase {
+ t.Helper()
+ p, ref := tf.startTransfer(t, tf.acct, "shop.com")
+ if ref != nil {
+ t.Fatalf("start refused: %+v", ref)
+ }
+ return p
+}
+
+// pass runs the purchase pass's step for id; a provider error is expected
+// in some tests and only logged.
+func (tf *transferFixture) pass(t *testing.T, id string) *DomainPurchase {
+ t.Helper()
+ if err := tf.srv.advancePurchase(context.Background(), id); err != nil {
+ t.Logf("pass %s: %v", id, err)
+ }
+ return tf.read(t, id)
+}
+
+func (tf *transferFixture) authorise(t *testing.T, p *DomainPurchase) {
+ t.Helper()
+ if _, err := tf.fake.CompletePaymentCheckout(tf.read(t, p.ID).CheckoutSession); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (tf *transferFixture) intentStatus(t *testing.T, p *DomainPurchase) string {
+ t.Helper()
+ info, err := tf.fake.PaymentCheckout(context.Background(), tf.read(t, p.ID).CheckoutSession)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return info.IntentStatus
+}
+
+// submitted drives a fresh transfer to its submit.
+func (tf *transferFixture) submitted(t *testing.T) *DomainPurchase {
+ t.Helper()
+ p := tf.start(t)
+ tf.authorise(t, p)
+ p = tf.pass(t, p.ID)
+ if p.State != PurchaseTransferSubmitting || purchaseCalls(tf.reg.Calls, "request-transfer:") != 1 {
+ t.Fatalf("not submitted: %+v %v", p, tf.reg.Calls)
+ }
+ return p
+}
+
+func TestTransferHappyPathRecordsRegistrationWithoutZone(t *testing.T) {
+ tf := newTransferFixture(t)
+ ctx := context.Background()
+ for _, host := range []string{"shop.com", "www.shop.com"} {
+ if _, _, err := domains.AttachClaim(ctx, tf.rel, domains.Claim{Schema: 1, Host: host, Account: tf.acct.Sqid, App: "kass"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := map[string]*domains.Claim{}
+ for _, host := range []string{"shop.com", "www.shop.com"} {
+ before[host], _ = domains.GetClaim(ctx, tf.rel, host)
+ }
+ p := tf.start(t)
+ if p.Kind != PurchaseKindTransfer || p.Amount != 1200 || p.AuthCode != testAuthCode || !slices.Equal(p.Nameservers, []string{"ns1.example-dns.test", "ns2.example-dns.test"}) {
+ t.Fatalf("started: %+v", p)
+ }
+ // An edit to the saved contact after start changes nothing the transfer sends or records.
+ edited := purchaseContact()
+ edited.City = "Cork"
+ if err := tf.st.EditSavedContact(ctx, tf.acct.ID, p.ContactID, edited); err != nil {
+ t.Fatal(err)
+ }
+ tf.authorise(t, p)
+ p = tf.pass(t, p.ID)
+ sent := tf.reg.LastTransfer
+ if p.State != PurchaseTransferSubmitting || sent.AuthCode != testAuthCode || sent.OwnerHandle != p.OwnerHandle || sent.Key != p.ID ||
+ !slices.Equal(sent.Nameservers, []string{"ns1.example-dns.test", "ns2.example-dns.test"}) {
+ t.Fatalf("submit: %+v sent %v", p, sent)
+ }
+ p = tf.pass(t, p.ID) // reads pending: capture
+ if p.Facts.Registrar != rPending || !p.Facts.Accepted || tf.sent(billing.PreparedCapture) != 1 {
+ t.Fatalf("after acceptance: %+v %v", p.Facts, tf.fake.Sent)
+ }
+ expires := tf.now.AddDate(2, 0, 0).Truncate(time.Second)
+ tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{Domain: "shop.com", RegistrarID: "reg-shop", Expires: expires}})
+ tf.tick(transferStatusEvery)
+ for i := 0; i < 3 && p.State != PurchaseDone; i++ {
+ p = tf.pass(t, p.ID)
+ }
+ if p.State != PurchaseDone || p.AuthCode != "" || p.RegistrarID != "reg-shop" {
+ t.Fatalf("not done: %+v", p)
+ }
+ r, err := tf.st.DomainRegistrationFor(ctx, tf.acct.ID, "shop.com")
+ if err != nil || r == nil || r.ZoneID != "" || !r.Expires.Equal(expires) || r.Registrant != purchaseContact() || !r.AutoRenew {
+ t.Fatalf("registration: %+v %v", r, err)
+ }
+ if tf.sent(billing.PreparedCapture) != 1 || tf.intentStatus(t, p) != "succeeded" || len(tf.zone.Zones) != 0 ||
+ purchaseCalls(tf.reg.Calls, "register:") != 0 || purchaseCalls(tf.reg.Calls, "request-transfer:") != 1 {
+ t.Fatalf("money or resources: capture=%d zones=%v calls=%v", tf.sent(billing.PreparedCapture), tf.zone.Zones, tf.reg.Calls)
+ }
+ for host, c := range before {
+ after, err := domains.GetClaim(ctx, tf.rel, host)
+ if err != nil || !reflect.DeepEqual(after, c) {
+ t.Fatalf("claim %s touched: %+v -> %+v (%v)", host, c, after, err)
+ }
+ }
+ mail := tf.srv.consoleMail.(*fakeConsoleMail)
+ mail.mu.Lock()
+ defer mail.mu.Unlock()
+ if len(mail.sent) == 0 || !strings.Contains(strings.Join(mail.sent, "\n"), transferOwnerCopy.DoneBody) {
+ t.Fatalf("owner not told: %v", mail.sent)
+ }
+}
+
+// sponsoredTransferAccount is a second account entitled to custom domains
+// without a subscription.
+func sponsoredTransferAccount(t *testing.T, tf *transferFixture, id int64) *Account {
+ t.Helper()
+ acct := planAccount(t, tf.consoleFixture, id)
+ sponsored := sponsorUnlimited()
+ if _, err := tf.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return acct
+}
+
+func TestTransferStartRefusals(t *testing.T) {
+ type tcase struct {
+ name string
+ domain string
+ setup func(t *testing.T, tf *transferFixture)
+ acct func(t *testing.T, tf *transferFixture) *Account
+ status int // 0: allowed
+ msg string
+ }
+ neutral := claimRefusal("shop.com", domains.ErrHostUnavailable)
+ cases := []tcase{
+ {name: "not registrable", domain: "localhost", status: 422, msg: domainBuyCopy["nameError"]},
+ {name: "TLD not marked transferable", domain: "shop.net", status: 422, msg: domainTransferCopy["notOffered"]},
+ {name: "TLD not in the catalog", domain: "shop.org", status: 422, msg: domainTransferCopy["notOffered"]},
+ {name: "premium", setup: func(t *testing.T, tf *transferFixture) {
+ tf.reg.TransferChecks["shop.com"] = registrar.TransferCheck{Transferable: true, Premium: true, Cost: registrar.Money{Currency: "usd", Minor: 800}}
+ }, status: 422, msg: domainBuyCopy["premium"]},
+ {name: "already registered here", setup: func(t *testing.T, tf *transferFixture) {
+ other := planAccount(t, tf.consoleFixture, 802)
+ if err := tf.st.AddDomainRegistration(DomainRegistration{Domain: "shop.com", AccountID: other.ID, RegistrarID: "r", ZoneID: "z"}); err != nil {
+ t.Fatal(err)
+ }
+ }, status: neutral.Status, msg: neutral.Msg},
+ {name: "another account's apex claim", setup: func(t *testing.T, tf *transferFixture) { holdBuyName(t, tf.purchaseFixture, "shop.com") },
+ status: neutral.Status, msg: neutral.Msg},
+ {name: "another account's www claim", setup: func(t *testing.T, tf *transferFixture) { holdBuyName(t, tf.purchaseFixture, "www.shop.com") },
+ status: neutral.Status, msg: neutral.Msg},
+ {name: "own apps' claims allowed", setup: func(t *testing.T, tf *transferFixture) {
+ for _, host := range []string{"shop.com", "www.shop.com"} {
+ if _, _, err := domains.AttachClaim(context.Background(), tf.rel, domains.Claim{Schema: 1, Host: host, Account: tf.acct.Sqid, App: "kass"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }},
+ {name: "DS present", setup: func(t *testing.T, tf *transferFixture) { tf.ds = true }, status: 422, msg: domainTransferCopy["dnssec"]},
+ {name: "DS lookup error", setup: func(t *testing.T, tf *transferFixture) { tf.dsErr = errors.New("servfail") }, status: 503, msg: domainTransferCopy["dnsUnread"]},
+ {name: "NS unreadable", setup: func(t *testing.T, tf *transferFixture) { tf.nsErr = errors.New("timeout") }, status: 422, msg: domainTransferCopy["nameservers"]},
+ {name: "empty NS", setup: func(t *testing.T, tf *transferFixture) { tf.ns = nil }, status: 422, msg: domainTransferCopy["nameservers"]},
+ {name: "check says locked", setup: func(t *testing.T, tf *transferFixture) {
+ tf.reg.TransferChecks["shop.com"] = registrar.TransferCheck{Reason: "locked"}
+ }, status: 422, msg: domainTransferNotNow["locked"]},
+ {name: "check says no with an unknown reason", setup: func(t *testing.T, tf *transferFixture) {
+ tf.reg.TransferChecks["shop.com"] = registrar.TransferCheck{Reason: "something-new"}
+ }, status: 422, msg: domainTransferNotNow[""]},
+ {name: "daily cap", setup: func(t *testing.T, tf *transferFixture) {
+ tf.srv.cfg.DomainCatalog.DailyCap = 1
+ if err := tf.st.CreateDomainPurchase(DomainPurchase{AccountID: tf.acct.ID, Domain: "earlier.com", State: PurchaseDone}); err != nil {
+ t.Fatal(err)
+ }
+ }, status: 429, msg: domainPurchaseCopy.DailyCap},
+ {name: "registrar balance short", setup: func(t *testing.T, tf *transferFixture) {
+ tf.reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100}
+ },
+ status: 503, msg: domainTransferCopy["unavailable"]},
+ {name: "sponsored account without a subscription allowed", acct: func(t *testing.T, tf *transferFixture) *Account {
+ return sponsoredTransferAccount(t, tf, 503)
+ }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ tf := newTransferFixture(t)
+ if c.setup != nil {
+ c.setup(t, tf)
+ }
+ acct := tf.acct
+ if c.acct != nil {
+ acct = c.acct(t, tf)
+ }
+ domain := c.domain
+ if domain == "" {
+ domain = "shop.com"
+ }
+ p, ref := tf.startTransfer(t, acct, domain)
+ if c.status == 0 {
+ if ref != nil || p == nil || p.Kind != PurchaseKindTransfer {
+ t.Fatalf("refused: %+v %+v", ref, p)
+ }
+ return
+ }
+ if ref == nil || ref.Status != c.status || ref.Msg != c.msg {
+ t.Fatalf("refusal = %+v, want %d %q", ref, c.status, c.msg)
+ }
+ if n, _ := tf.st.PurchasesToday(acct.ID, time.Now()); n > 0 && c.name != "daily cap" {
+ t.Fatalf("a refused start wrote a purchase")
+ }
+ if tf.sent(billing.PreparedPaymentCheckout) != 0 {
+ t.Fatal("a refused start opened a Checkout")
+ }
+ })
+ }
+ // An auth code is required.
+ tf := newTransferFixture(t)
+ c := purchaseContact()
+ _, _, _, ref := tf.srv.startDomainTransfer(context.Background(), tf.acct, "shop.com", " ", purchaseContactSelection{New: &c}, "buyer@example.test", transferQuoteFor(tf.srv, tf.acct))
+ if ref == nil || ref.Msg != domainTransferCopy["authCode"] {
+ t.Fatalf("empty auth code: %+v", ref)
+ }
+}
+
+func TestTransferUnknownStaysLiveBlocksDeletionAndSecondStart(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ tf.authorise(t, p)
+ tf.reg.RequestErr = registrar.ErrIndeterminate // lost on the way: the registrar never shows it
+ p = tf.pass(t, p.ID)
+ for i := 0; i < 60; i++ {
+ tf.tick(6 * time.Hour)
+ p = tf.pass(t, p.ID)
+ if !purchaseLive(p.State) || p.Facts.Registrar != rUnknown {
+ t.Fatalf("pass %d: unknown transfer settled: %+v", i, p)
+ }
+ }
+ if tf.sent(billing.PreparedCapture) != 0 || tf.sent(billing.PreparedCancelPayment) != 0 || purchaseCalls(tf.reg.Calls, "request-transfer:") != 1 {
+ t.Fatalf("money moved or resent: %v %v", tf.fake.Sent, tf.reg.Calls)
+ }
+ if tf.alerts(alertUnknown24h) != 1 || tf.alerts(alertLapse) != 1 || tf.alerts(alertUnknownWeekly) < 1 {
+ t.Fatalf("alerts: %v", tf.pages)
+ }
+ doms, err := tf.st.DomainObligations(context.Background(), tf.acct.ID)
+ if err != nil || !slices.Contains(doms, "shop.com") {
+ t.Fatalf("deletion not blocked: %v %v", doms, err)
+ }
+ // The same account's transfer resumes the same purchase; its buy, and
+ // another account's transfer, are refused neutrally.
+ again, ref := tf.startTransfer(t, tf.acct, "shop.com")
+ if ref == nil && (again == nil || again.ID != p.ID) {
+ t.Fatalf("second transfer start: %+v %+v", again, ref)
+ }
+ if _, _, buyRef := startQuotedPurchase(tf.srv, context.Background(), tf.acct, "", "shop.com", purchaseContact(), "buyer@example.test"); buyRef == nil || buyRef.Status != http.StatusConflict {
+ t.Fatalf("buy over a live transfer: %+v", buyRef)
+ }
+ other := sponsoredTransferAccount(t, tf, 803)
+ if _, ref := tf.startTransfer(t, other, "shop.com"); ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("another account's transfer: %+v", ref)
+ }
+ if purchaseCalls(tf.reg.Calls, "request-transfer:") != 1 {
+ t.Fatal("a second start sent a request")
+ }
+}
+
+func TestTransferOperatorResolveOnlyForUnknownAndAudited(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ tf.authorise(t, p)
+ tf.reg.RequestErr = registrar.ErrIndeterminate
+ p = tf.submittedOrPass(t, p)
+ tf.srv.cfg.StoreOperators = []string{"operator@example.com"}
+ listed := cliToken(t, tf.consoleFixture, "operator@example.com", "resolve-listed")
+ opsOwner := cliToken(t, tf.consoleFixture, "opsowner@example.com", "resolve-ops")
+ if err := tf.st.AddMember(OpsAccountID, "opsowner@example.com", RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ owner := buyToken(t, tf.purchaseFixture)
+ svc := serviceToken(t, tf.st, tf.acct.ID, "resolve-admin", "kass", svcrole.Admin)
+ path := "/api/cli/system/domains/purchases/" + p.ID + "/resolve"
+ body := `{"outcome":"failed","note":"registrar says no such transfer"}`
+ for name, token := range map[string]string{"ops-account owner off the list": opsOwner, "account owner": owner, "service principal": svc} {
+ status, b := buyRequest(t, tf.purchaseFixture, "POST", path, token, body)
+ if status == http.StatusOK {
+ t.Fatalf("%s resolved: %s", name, b)
+ }
+ if got := tf.read(t, p.ID); got.Facts.Resolution != "" {
+ t.Fatalf("%s recorded a resolution", name)
+ }
+ }
+ if status, b := buyRequest(t, tf.purchaseFixture, "POST", path, listed, `{"outcome":"maybe"}`); status != 422 {
+ t.Fatalf("bad outcome: %d %s", status, b)
+ }
+ // "completed" needs the registrar to show the domain in our account.
+ if status, b := buyRequest(t, tf.purchaseFixture, "POST", path, listed, `{"outcome":"completed"}`); status != http.StatusConflict {
+ t.Fatalf("completed while not ours: %d %s", status, b)
+ }
+ if status, b := buyRequest(t, tf.purchaseFixture, "POST", path, listed, body); status != http.StatusOK {
+ t.Fatalf("listed operator: %d %s", status, b)
+ }
+ got := tf.read(t, p.ID)
+ if got.Facts.Resolution != transferResolvedFailed || got.ResolvedBy != "operator@example.com" {
+ t.Fatalf("resolution: %+v", got)
+ }
+ events, err := tf.st.Events(OpsAccountID, "platform", 10)
+ if err != nil || len(events) == 0 || events[0].Action != "domain.transfer.resolve" || events[0].Address != "operator@example.com" || !strings.Contains(events[0].Detail, p.ID) {
+ t.Fatalf("audit: %+v %v", events, err)
+ }
+ // Resolved once; the authorisation is cancelled and the purchase fails, nothing taken.
+ if status, _ := buyRequest(t, tf.purchaseFixture, "POST", path, listed, body); status != http.StatusConflict {
+ t.Fatalf("resolved twice: %d", status)
+ }
+ for i := 0; i < 3 && purchaseLive(got.State); i++ {
+ got = tf.pass(t, p.ID)
+ }
+ if got.State != PurchaseFailed || tf.intentStatus(t, p) != "canceled" {
+ t.Fatalf("after resolution: %+v %s", got, tf.intentStatus(t, p))
+ }
+
+ // A pending transfer cannot be resolved.
+ tf2 := newTransferFixture(t)
+ tf2.srv.cfg.StoreOperators = []string{"operator@example.com"}
+ p2 := tf2.submitted(t)
+ tf2.pass(t, p2.ID)
+ listed2 := cliToken(t, tf2.consoleFixture, "operator@example.com", "resolve-listed")
+ if status, b := buyRequest(t, tf2.purchaseFixture, "POST", "/api/cli/system/domains/purchases/"+p2.ID+"/resolve", listed2, body); status != http.StatusConflict {
+ t.Fatalf("pending resolved: %d %s", status, b)
+ }
+
+ // Completed: the registrar's registration is recorded.
+ tf3 := newTransferFixture(t)
+ tf3.srv.cfg.StoreOperators = []string{"operator@example.com"}
+ p3 := tf3.start(t)
+ tf3.authorise(t, p3)
+ tf3.reg.RequestErr = registrar.ErrIndeterminate
+ p3 = tf3.submittedOrPass(t, p3)
+ tf3.reg.Domains["shop.com"] = registrar.Registered{Domain: "shop.com", RegistrarID: "reg-op", Expires: tf3.now.AddDate(1, 0, 0).Truncate(time.Second)}
+ listed3 := cliToken(t, tf3.consoleFixture, "operator@example.com", "resolve-listed")
+ if status, b := buyRequest(t, tf3.purchaseFixture, "POST", "/api/cli/system/domains/purchases/"+p3.ID+"/resolve", listed3, `{"outcome":"completed"}`); status != http.StatusOK {
+ t.Fatalf("completed: %d %s", status, b)
+ }
+ for i := 0; i < 4 && purchaseLive(p3.State); i++ {
+ p3 = tf3.pass(t, p3.ID)
+ }
+ // It was never accepted, so nothing was captured before: captured now, then done.
+ if p3.State != PurchaseDone || tf3.intentStatus(t, p3) != "succeeded" {
+ t.Fatalf("resolved completed: %+v", p3)
+ }
+}
+
+// lockedBuffer is a log sink safe for concurrent writers.
+type lockedBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (l *lockedBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *lockedBuffer) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.String()
+}
+
+// submittedOrPass runs the submit pass for an authorised transfer.
+func (tf *transferFixture) submittedOrPass(t *testing.T, p *DomainPurchase) *DomainPurchase {
+ t.Helper()
+ p = tf.pass(t, p.ID)
+ if p.State != PurchaseTransferSubmitting {
+ t.Fatalf("not submitted: %+v", p)
+ }
+ return p
+}
+
+func TestTransferSubmitRefusalIsStickyAgainstLaterNone(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ tf.authorise(t, p)
+ tf.reg.Transfers["shop.com"] = registrar.TransferStatus{State: registrar.TransferFailed, Reason: "auth_code"}
+ p = tf.pass(t, p.ID)
+ if p.Facts.Registrar != rFailed || p.Facts.RegistrarReason != "auth_code" {
+ t.Fatalf("refusal not recorded: %+v", p.Facts)
+ }
+ // The registrar now reads "none"; a restart and many passes later the
+ // refusal stands and the authorisation is cancelled, never captured.
+ tf.restart(t)
+ for i := 0; i < 5 && purchaseLive(p.State); i++ {
+ tf.tick(time.Hour)
+ p = tf.pass(t, p.ID)
+ if p.Facts.Registrar != rFailed {
+ t.Fatalf("refusal replaced: %+v", p.Facts)
+ }
+ }
+ if p.State != PurchaseFailed || p.Reason != "auth_code" || tf.intentStatus(t, p) != "canceled" || tf.sent(billing.PreparedCapture) != 0 {
+ t.Fatalf("end: %+v %s", p, tf.intentStatus(t, p))
+ }
+ if purchaseCalls(tf.reg.Calls, "transfer-status:") != 0 {
+ t.Fatalf("a definite refusal was read again: %v", tf.reg.Calls)
+ }
+}
+
+// failAfterCapture drives a transfer to accepted and captured, then fails it
+// at the registrar.
+func (tf *transferFixture) failAfterCapture(t *testing.T, reason string) *DomainPurchase {
+ t.Helper()
+ p := tf.submitted(t)
+ p = tf.pass(t, p.ID) // pending: capture
+ p = tf.pass(t, p.ID) // captured observed
+ if tf.intentStatus(t, p) != "succeeded" {
+ t.Fatalf("not captured: %+v", p)
+ }
+ tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferFailed, Reason: reason})
+ tf.tick(transferStatusEvery)
+ return p
+}
+
+func (tf *transferFixture) refunds(t *testing.T, p *DomainPurchase) []billing.RefundInfo {
+ t.Helper()
+ list, err := tf.fake.Refunds(context.Background(), tf.read(t, p.ID).PaymentIntent)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return list
+}
+
+func TestTransferReplacementRefundSurvivesCrashPastKeyRetention(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.failAfterCapture(t, "")
+ tf.fake.NextRefundStatus = billing.RefundPending
+ p = tf.pass(t, p.ID) // reads failed: refund attempt 1
+ r0 := tf.refunds(t, p)
+ if len(r0) != 1 || r0[0].Attempt != 1 || p.Facts.RefundAttempt != 1 {
+ t.Fatalf("attempt 1: %+v %+v", r0, p.Facts)
+ }
+ if err := tf.fake.SettleRefund(r0[0].ID, billing.RefundFailed); err != nil {
+ t.Fatal(err)
+ }
+ // Attempt 2 succeeds at the provider, but its answer is lost.
+ tf.fake.LoseNextResponse = true
+ p = tf.pass(t, p.ID)
+ if p.Facts.RefundAttempt != 2 || p.Facts.RefundID != "" {
+ t.Fatalf("attempt 2 recorded: %+v", p.Facts)
+ }
+ // Past the key's retention, and on a fresh server: attempt 2 is
+ // adopted from the list (attempt 1, failed, still listed, is ignored).
+ tf.tick(48 * time.Hour)
+ tf.fake.PruneKeysOlderThan(24 * time.Hour)
+ tf.restart(t)
+ for i := 0; i < 4 && purchaseLive(p.State); i++ {
+ p = tf.pass(t, p.ID)
+ }
+ list := tf.refunds(t, p)
+ if p.State != PurchaseFailed || len(list) != 2 || tf.sent(billing.PreparedRefund) != 2 {
+ t.Fatalf("end: %+v refunds=%+v sends=%d", p, list, tf.sent(billing.PreparedRefund))
+ }
+ if p.Facts.RefundID != list[1].ID || list[1].Status != billing.RefundSucceeded {
+ t.Fatalf("adopted: %+v %+v", p.Facts, list)
+ }
+ if tf.alerts(refundFailedAlert(1)) != 1 {
+ t.Fatalf("failed attempt not alerted once: %v", tf.pages)
+ }
+}
+
+func TestTransferRefundIgnoresFailedEarlierAttemptInList(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.failAfterCapture(t, "rejected")
+ tf.fake.NextRefundStatus = billing.RefundPending
+ p = tf.pass(t, p.ID)
+ first := tf.refunds(t, p)[0]
+ if err := tf.fake.SettleRefund(first.ID, billing.RefundFailed); err != nil {
+ t.Fatal(err)
+ }
+ // Attempt 2's create crashes after it reached the provider; it is
+ // pending there. The list holds attempt 1 (failed) and attempt 2.
+ tf.fake.NextRefundStatus = billing.RefundPending
+ tf.fake.CrashAfterSend = true
+ p = tf.pass(t, p.ID)
+ if p.Facts.RefundAttempt != 2 || p.Facts.RefundID != "" {
+ t.Fatalf("attempt 2: %+v", p.Facts)
+ }
+ p = tf.pass(t, p.ID)
+ list := tf.refunds(t, p)
+ if len(list) != 2 || p.Facts.RefundID != list[1].ID || p.Facts.Refund != fPending || p.Facts.RefundAttempt != 2 {
+ t.Fatalf("listed failed attempt 1 chosen: %+v %+v", p.Facts, list)
+ }
+ if err := tf.fake.SettleRefund(list[1].ID, billing.RefundSucceeded); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 3 && purchaseLive(p.State); i++ {
+ p = tf.pass(t, p.ID)
+ }
+ if p.State != PurchaseFailed || tf.sent(billing.PreparedRefund) != 2 || len(tf.refunds(t, p)) != 2 {
+ t.Fatalf("end: %+v %d", p, tf.sent(billing.PreparedRefund))
+ }
+}
+
+func TestTransferDeclinedCardThenRetriedInSameCheckout(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ // A declined card: the session stays open; its PaymentIntent needs a
+ // new payment method.
+ if err := tf.fake.DeclinePaymentCheckout(p.CheckoutSession); err != nil {
+ t.Fatal(err)
+ }
+ p = tf.pass(t, p.ID)
+ if p.State != PurchaseAwaitingPayment || p.Facts.Payment != pAwaiting || p.PaymentIntent != "" {
+ t.Fatalf("decline settled: %+v", p)
+ }
+ tf.restart(t)
+ tf.tick(10 * time.Minute)
+ p = tf.pass(t, p.ID)
+ if p.State != PurchaseAwaitingPayment {
+ t.Fatalf("after restart: %+v", p)
+ }
+ tf.authorise(t, p)
+ p = tf.pass(t, p.ID)
+ if p.State != PurchaseTransferSubmitting || purchaseCalls(tf.reg.Calls, "request-transfer:") != 1 {
+ t.Fatalf("retried card did not submit: %+v", p)
+ }
+}
+
+func TestTransferCaptureBeforeDrivesLapseAlert(t *testing.T) {
+ for _, window := range []time.Duration{72 * time.Hour, -1} {
+ t.Run(fmt.Sprint(window), func(t *testing.T) {
+ tf := newTransferFixture(t)
+ tf.fake.CaptureWindow = window
+ p := tf.start(t)
+ created := tf.read(t, p.ID).CreatedAt
+ tf.authorise(t, p)
+ authorisedAt := tf.now
+ // Seen late: two days pass before the first pass reads it.
+ tf.tick(48 * time.Hour)
+ tf.reg.RequestErr = registrar.ErrIndeterminate
+ p = tf.pass(t, p.ID)
+ deadline := authorisedAt.Add(window)
+ if window < 0 {
+ deadline = created.Add(transferCaptureFallback)
+ }
+ if !p.Facts.CaptureBefore.Equal(deadline) {
+ t.Fatalf("capture before = %s, want %s", p.Facts.CaptureBefore, deadline)
+ }
+ var alertedAt time.Time
+ for i := 0; i < 400 && alertedAt.IsZero(); i++ {
+ tf.tick(30 * time.Minute)
+ p = tf.pass(t, p.ID)
+ if at := p.Facts.Alerts[alertLapse]; !at.IsZero() {
+ alertedAt = at
+ }
+ }
+ if alertedAt.Before(deadline.Add(-transferLapseAlertBefore)) || alertedAt.After(deadline.Add(-transferLapseAlertBefore+30*time.Minute)) {
+ t.Fatalf("lapse alert at %s, want a day before %s", alertedAt, deadline)
+ }
+ if tf.alerts(alertLapse) != 1 {
+ t.Fatalf("lapse alerts: %v", tf.pages)
+ }
+ })
+ }
+}
+
+func TestTransferAuthCodeClearedAtSubmitAndNeverLogged(t *testing.T) {
+ logs := &lockedBuffer{}
+ log.SetOutput(logs)
+ t.Cleanup(func() { log.SetOutput(os.Stderr) })
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ started := *p
+ tf.authorise(t, p)
+ var atSubmit *DomainPurchase
+ transferStepHook = func(step string) error {
+ if step == "submit:recorded" {
+ atSubmit, _ = tf.st.DomainPurchase(p.ID)
+ }
+ return nil
+ }
+ t.Cleanup(func() { transferStepHook = nil })
+ tf.reg.RequestErr = fmt.Errorf("%w: lost", registrar.ErrIndeterminate)
+ p = tf.pass(t, p.ID)
+ if atSubmit == nil || atSubmit.AuthCode != "" || atSubmit.State != PurchaseTransferSubmitting || tf.reg.LastTransfer.AuthCode != testAuthCode {
+ t.Fatalf("auth code at the submit move: %+v (sent %q)", atSubmit, tf.reg.LastTransfer.AuthCode)
+ }
+ var raw string
+ if err := tf.st.db.QueryRow(`SELECT details FROM domain_purchases WHERE id=?`, p.ID).Scan(&raw); err != nil || strings.Contains(raw, testAuthCode) {
+ t.Fatalf("stored details hold the code: %v", err)
+ }
+ for i := 0; i < 10; i++ {
+ tf.tick(6 * time.Hour)
+ tf.pass(t, p.ID)
+ }
+ if started.AuthCode != testAuthCode {
+ t.Fatal("the start did not keep the code: the format check proves nothing")
+ }
+ for _, s := range []string{fmt.Sprintf("%v %+v %#v %s %v", started, started, started, started.purchaseDetails, &started), fmt.Sprint(tf.reg.LastTransfer), logs.String(), strings.Join(tf.pages, "\n")} {
+ if strings.Contains(s, testAuthCode) {
+ t.Fatalf("auth code leaked: %q", s)
+ }
+ }
+ if !strings.Contains(logs.String(), p.ID) {
+ t.Fatal("captured no log output: the check proves nothing")
+ }
+}
+
+func TestTransferAuthCodeClearedOnEveryPreSubmitTerminal(t *testing.T) {
+ type path struct {
+ name string
+ end func(t *testing.T, tf *transferFixture, p *DomainPurchase)
+ }
+ for _, c := range []path{
+ {"checkout expired", func(t *testing.T, tf *transferFixture, p *DomainPurchase) { tf.tick(2 * time.Hour) }},
+ {"authorisation lapsed before it was seen", func(t *testing.T, tf *transferFixture, p *DomainPurchase) {
+ tf.fake.LapseAuthorisations, tf.fake.CaptureWindow = true, time.Hour
+ tf.authorise(t, p)
+ tf.tick(2 * time.Hour)
+ }},
+ {"payment setup refused", func(t *testing.T, tf *transferFixture, p *DomainPurchase) {
+ // As if the start stopped before its Checkout; the provider then
+ // refuses to create one.
+ if err := tf.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(q *DomainPurchase) { q.CheckoutSession, q.CheckoutPrepared = "", nil }); err != nil {
+ t.Fatal(err)
+ }
+ tf.fake.BeforeSend = func(billing.Prepared) error { return billing.ErrRefused }
+ }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.start(t)
+ c.end(t, tf, p)
+ p = tf.read(t, p.ID)
+ for i := 0; i < 4 && purchaseLive(p.State); i++ {
+ p = tf.pass(t, p.ID)
+ }
+ if purchaseLive(p.State) || p.AuthCode != "" || purchaseCalls(tf.reg.Calls, "request-transfer:") != 0 || tf.sent(billing.PreparedCapture) != 0 {
+ t.Fatalf("end: %+v", p)
+ }
+ })
+ }
+}
+
+func TestTransferCompletionReplayAfterCrashBetweenInsertAndMove(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.submitted(t)
+ p = tf.pass(t, p.ID) // capture
+ tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{Domain: "shop.com", RegistrarID: "reg-shop", Expires: tf.now.AddDate(1, 0, 0).Truncate(time.Second)}})
+ tf.tick(transferStatusEvery)
+ crashed := false
+ transferStepHook = func(step string) error {
+ if step == "complete:recorded" && !crashed {
+ crashed = true
+ return errors.New("crash")
+ }
+ return nil
+ }
+ t.Cleanup(func() { transferStepHook = nil })
+ for i := 0; i < 3 && !crashed; i++ {
+ p = tf.pass(t, p.ID)
+ }
+ if !crashed || !purchaseLive(p.State) {
+ t.Fatalf("no crash between insert and move: %+v", p)
+ }
+ tf.restart(t)
+ p = tf.pass(t, p.ID)
+ var n int
+ if err := tf.st.db.QueryRow(`SELECT COUNT(*) FROM domain_registrations WHERE domain='shop.com'`).Scan(&n); err != nil || n != 1 || p.State != PurchaseDone {
+ t.Fatalf("replay: %+v registrations=%d %v", p, n, err)
+ }
+}
+
+func TestBuyAndTransferResumeOnlyTheirOwnKind(t *testing.T) {
+ // A live buy: a transfer start refuses neutrally; the buy resumes.
+ tf := newTransferFixture(t)
+ buy := tf.purchaseFixture.start(t)
+ if _, ref := tf.startTransfer(t, tf.acct, "shop.com"); ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("transfer over a live buy: %+v", ref)
+ }
+ if q, ref := tf.srv.quoteTransfer(context.Background(), tf.acct, "shop.com"); ref == nil || q.Quote.Price != 0 {
+ t.Fatalf("transfer quote over a live buy: %+v %+v", q, ref)
+ }
+ if again, _, ref := startQuotedPurchase(tf.srv, context.Background(), tf.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test"); ref != nil || again.ID != buy.ID {
+ t.Fatalf("buy resume: %+v %+v", again, ref)
+ }
+ // A live transfer: a buy (start, check, step quote) refuses neutrally;
+ // the transfer resumes.
+ tf2 := newTransferFixture(t)
+ tr := tf2.start(t)
+ if _, _, ref := startQuotedPurchase(tf2.srv, context.Background(), tf2.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test"); ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("buy over a live transfer: %+v", ref)
+ }
+ if _, ref := tf2.srv.checkDomainBuy(context.Background(), tf2.acct, "shop.com", ""); ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("buy check over a live transfer: %+v", ref)
+ }
+ if _, ref := tf2.srv.buyStepQuote(context.Background(), tf2.acct, "shop.com", ""); ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("buy step quote over a live transfer: %+v", ref)
+ }
+ if again, ref := tf2.startTransfer(t, tf2.acct, "shop.com"); ref != nil || again.ID != tr.ID {
+ t.Fatalf("transfer resume: %+v %+v", again, ref)
+ }
+ // A transfer row never reaches a buy step, even in a state the kinds
+ // share, nor through the billing webhook's nudge.
+ tf2.authorise(t, tr)
+ if err := tf2.srv.domainPurchasePass(context.Background()); err != nil {
+ t.Log(err)
+ }
+ if len(tf2.zone.Zones) != 0 || purchaseCalls(tf2.reg.Calls, "register:") != 0 {
+ t.Fatalf("a transfer reached a buy step: zones %v calls %v", tf2.zone.Zones, tf2.reg.Calls)
+ }
+ if err := tf2.st.AdvanceDomainPurchase(tr.ID, PurchaseTransferSubmitting, PurchaseAuthorised, nil); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 3; i++ {
+ tf2.pass(t, tr.ID)
+ }
+ if len(tf2.zone.Zones) != 0 || purchaseCalls(tf2.reg.Calls, "register:") != 0 || purchaseCalls(tf2.reg.Calls, "request-transfer:") != 1 {
+ t.Fatalf("a transfer in a shared state reached a buy step: zones %v calls %v", tf2.zone.Zones, tf2.reg.Calls)
+ }
+}
+
+func TestTransferStatusCadence(t *testing.T) {
+ tf := newTransferFixture(t)
+ p := tf.submitted(t)
+ submitted := p.Facts.SubmittedAt
+ reads := func() int { return purchaseCalls(tf.reg.Calls, "transfer-status:") }
+ p = tf.pass(t, p.ID) // the first read follows the submit
+ if reads() != 1 || !p.NextStatusAt.Equal(tf.now.Add(transferStatusEvery)) {
+ t.Fatalf("first read: %d next %s", reads(), p.NextStatusAt)
+ }
+ tf.tick(29 * time.Minute)
+ tf.pass(t, p.ID)
+ if reads() != 1 {
+ t.Fatal("read before NextStatusAt")
+ }
+ tf.tick(time.Minute)
+ p = tf.pass(t, p.ID)
+ if reads() != 2 {
+ t.Fatal("no read at NextStatusAt")
+ }
+ for tf.now.Before(submitted.Add(transferStatusFastFor)) {
+ tf.tick(30 * time.Minute)
+ p = tf.pass(t, p.ID)
+ }
+ fast := reads()
+ if fast < 7*48-2 || fast > 7*48+2 {
+ t.Fatalf("reads in the first week = %d, want about %d", fast, 7*48)
+ }
+ if !p.NextStatusAt.Equal(tf.now.Add(transferStatusSlowEvery)) {
+ t.Fatalf("after a week: next %s, want %s", p.NextStatusAt, tf.now.Add(transferStatusSlowEvery))
+ }
+ for i := 0; i < 48; i++ {
+ tf.tick(time.Hour)
+ tf.pass(t, p.ID)
+ }
+ if got := reads() - fast; got != 2 {
+ t.Fatalf("reads over two later days = %d, want 2", got)
+ }
+}
+
+func TestAlertOperatorReportsDeliveryFailure(t *testing.T) {
+ tf := newTransferFixture(t)
+ if err := tf.srv.alertOperator(context.Background(), "subject", "body"); err != nil {
+ t.Fatal(err)
+ }
+ tf.pageErr = errors.New("sns down")
+ if err := tf.srv.alertOperator(context.Background(), "subject", "body"); err == nil || !strings.Contains(err.Error(), "sns down") {
+ t.Fatalf("undelivered alert: %v", err)
+ }
+ // An undelivered transfer alert is not recorded and is sent again.
+ p := tf.start(t)
+ tf.authorise(t, p)
+ tf.reg.RequestErr = registrar.ErrIndeterminate
+ p = tf.pass(t, p.ID)
+ tf.tick(25 * time.Hour)
+ p = tf.pass(t, p.ID)
+ if !p.Facts.Alerts[alertUnknown24h].IsZero() {
+ t.Fatalf("an undelivered alert was recorded: %+v", p.Facts.Alerts)
+ }
+ tf.pageErr = nil
+ p = tf.pass(t, p.ID)
+ if p.Facts.Alerts[alertUnknown24h].IsZero() || tf.alerts(alertUnknown24h) != 1 {
+ t.Fatalf("alert not delivered once: %+v %v", p.Facts.Alerts, tf.pages)
+ }
+}
+
+// A transferred domain has no zone, so the point door does not offer it:
+// nothing is written to a zone with no ID.
+func TestPointRefusesTransferredDomain(t *testing.T) {
+ tf := newTransferFixture(t)
+ if err := tf.st.AddDomainRegistration(DomainRegistration{Domain: "shop.com", AccountID: tf.acct.ID, RegistrarID: "reg-shop", ZoneID: ""}); err != nil {
+ t.Fatal(err)
+ }
+ if _, ref := tf.srv.pointBoughtDomain(context.Background(), tf.acct, "kass", "shop.com", "buyer@example.test"); ref == nil || ref.Status != http.StatusNotFound {
+ t.Fatalf("point of a transferred domain: %+v", ref)
+ }
+ if len(tf.zone.Zones) != 0 {
+ t.Fatalf("zones touched: %v", tf.zone.Zones)
+ }
+}
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index dc80d526f..6d0fe2374 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -50,9 +50,11 @@ 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", "purchaseManagedSet", "capturedPurchase", "finishPurchaseUnpointed"},
- "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass", "billingSnapshotPass"},
- "PublishPlansMarker": {"publishPlansMarkerOnce"},
+ "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice", "purchaseManagedSet", "capturedPurchase", "finishPurchaseUnpointed",
+ "advanceTransferStep", "gatherTransfer", "gatherTransferRegistrar", "gatherTransferPayment", "gatherTransferRefund", "adoptTransferCheckout",
+ "actTransfer", "alertTransfer", "submitTransfer", "refundTransfer", "completeTransfer", "ownerNotice", "recordPurchaseRegistration"},
+ "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass", "billingSnapshotPass"},
+ "PublishPlansMarker": {"publishPlansMarkerOnce"},
"StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns",
"orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd",
"finishPendingInteractiveEnds", "interactiveSweep", "clearDeadMarker", "sweepEndRow", "scanOrphanGrants", "sweepOrphanGrants"},
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 27b800b18..adee0e46a 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -1199,6 +1199,11 @@ var routeDecls = []routeDecl{
{Pattern: "GET /api/cli/system/media", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemMediaGet},
{Pattern: "POST /api/cli/system/antivirus", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemAntivirusSet},
{Pattern: "POST /api/cli/system/antivirus/rotate-webhook-key", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemWebhookRotate},
+ // Resolving a transfer in whose outcome the registrar never made
+ // definite (domaintransfer_resolve.go): apiSystemOperator, a person on
+ // CARLOS_STORE_OPERATORS only. Transfers ride the buy door's switch, so
+ // it is not registered on a host-claim console.
+ {Pattern: "POST /api/cli/system/domains/purchases/{id}/resolve", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPITransferResolve},
// Platform GeoIP (geoip spec §4.2): apiSystemRoller, like the update
// doors, never CARLOS_STORE_OPERATORS.
{Pattern: "PUT /api/cli/system/geoip", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemGeoipPut},
diff --git a/internal/console/server.go b/internal/console/server.go
index 06aecfa98..899efe66b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -790,6 +790,17 @@ type Config struct {
// check (#215: domains.ChallengeName). nil means net.DefaultResolver;
// tests set it so no attach ever reaches a real resolver.
LookupTXT func(ctx context.Context, name string) ([]string, error)
+ // LookupNS reads a domain's nameservers from public DNS for a transfer
+ // in (domaintransfer_start.go). nil means net.DefaultResolver.LookupNS.
+ LookupNS func(ctx context.Context, name string) ([]*net.NS, error)
+ // LookupDS reports whether a domain has a DS record at its parent (a
+ // DNSSEC-signed domain cannot be transferred in yet). nil means
+ // lookupDS against DNSServer (dnsds.go).
+ LookupDS func(ctx context.Context, name string) (bool, error)
+ // DNSServer is the resolver lookupDS asks, host:port; "" means the
+ // first nameserver in /etc/resolv.conf. Tests point it at a local
+ // responder.
+ DNSServer string
// StoreProvisioner is the backend the object-storage doors provision
// through (issue #55), built at boot from CARLOS_STORE_BACKEND. nil is an
// ordinary deployment shape, not a broken one: members may still DECLARE
@@ -1071,6 +1082,7 @@ type Server struct {
pdfLimiter *pdfLimiter
recordPDF func(context.Context, pdfRenderRow)
purchaseWake chan struct{}
+ transferClock func() time.Time // the transfer engine's clock; nil: time.Now
// mediaRuntime is the media job table, the door's limiter and their
// test seams (mediawire.go).
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 24e33eafc..4b494840d 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -125,6 +125,8 @@ var closedDoors = []string{
"GET /api/cli/system/media",
"POST /api/cli/system/antivirus",
"POST /api/cli/system/antivirus/rotate-webhook-key",
+ // Resolving an unknown transfer in is an operator's (a person's) act.
+ "POST /api/cli/system/domains/purchases/{id}/resolve",
// Platform GeoIP (geoip spec §4.2): deployment-wide, operator-only, a
// person's decision. Publishing replaces what every edge serves.
"PUT /api/cli/system/geoip",
@@ -473,6 +475,7 @@ var domainBuyDoors = []string{
"POST /api/cli/accounts/{account}/domains/check",
"POST /api/cli/accounts/{account}/domains/purchases",
"POST /api/cli/apps/{account}/{app}/domains/point",
+ "POST /api/cli/system/domains/purchases/{id}/resolve",
}
// TestEveryCLIDoorNamesItsRoles is the default-deny guarantee for the
@@ -1797,8 +1800,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 113 {
- t.Errorf("walked %d closed doors, want all %d (and 113 today: three domain purchase doors, the account's domains list, four saved-contact doors, the domain point door, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, the media status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, three platform grant doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, and the claimed source door)",
+ if seen != len(closedDoors) || seen != 114 {
+ t.Errorf("walked %d closed doors, want all %d (and 114 today: three domain purchase doors, the account's domains list, four saved-contact doors, the domain point door, the transfer resolve door, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, the media status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, three platform grant doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, and the claimed source door)",
seen, len(closedDoors))
}
}