transfers: back off refused refunds; status reads name their record
A refund create the provider refuses outright is recorded on its attempt (fFailed, reason refused); the next attempt waits 1 h, 6 h, then 24 h, and the operator is alerted at the first refusal and daily while it lasts. A status read now belongs to this transfer: registrar.TransferStatus carries Ref and Created, TransferStatus reads (ctx, domain, ref), the engine keeps the request's ref in Facts and, with no ref, accepts only a record created at or after the submit. An earlier failed transfer of the same domain never settles a retry. Openprovider reads every record of the name and picks by id or newest creation date; the fake keeps earlier records.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+626
−80
internal/console/domaintransfer.go+60 −5internal/console/domaintransfer_decide.go+33 −0internal/console/domaintransfer_decide_test.go+105 −14internal/console/domaintransfer_facts.go+16 −5internal/console/domaintransfer_test.go+118 −0internal/registrar/openprovider/client.go+91 −24internal/registrar/openprovider/client_test.go+87 −11internal/registrar/openprovider/testdata/README.md+2 −0internal/registrar/registrar.go+14 −3internal/registrar/registrar_test.go+33 −8internal/registrar/registrartest/fake.go+67 −10
diff --git a/internal/console/domaintransfer.go b/internal/console/domaintransfer.go| index fcfc67bf8..93ade1b07 100644 |
| --- a/internal/console/domaintransfer.go |
| +++ b/internal/console/domaintransfer.go |
| @@ -138,7 +138,7 @@ func (s *Server) gatherTransferRegistrar(ctx context.Context, p *DomainPurchase, |
| if f.Resolution != "" || now.Before(p.NextStatusAt) { |
| return |
| } |
| - st, err := s.cfg.Registrar.TransferStatus(ctx, p.Domain) |
| + st, err := s.cfg.Registrar.TransferStatus(ctx, p.Domain, f.TransferRef) |
| o.nextStatusAt = nextTransferStatusAt(now, f.SubmittedAt) |
| if err != nil { |
| log.Printf("console: transfer %s: status: %v", p.ID, err) |
| @@ -146,6 +146,17 @@ func (s *Server) gatherTransferRegistrar(ctx context.Context, p *DomainPurchase, |
| f.Registrar = rUnknown |
| return |
| } |
| + if !transferRecordIsOurs(f, st) { |
| + // Another transfer's record of this domain (an earlier one that |
| + // failed, say): it says nothing about this purchase. |
| + log.Printf("console: transfer %s: status read another transfer's record", p.ID) |
| + f.Registrar = rUnknown |
| + return |
| + } |
| + if f.TransferRef == "" && st.State != registrar.TransferNone && st.Ref != "" { |
| + // Ours by its creation time: from now on read it by name. |
| + f.TransferRef = st.Ref |
| + } |
| switch st.State { |
| case registrar.TransferPending: |
| f.Registrar, f.Accepted = rPending, true |
| @@ -172,6 +183,24 @@ func (s *Server) gatherTransferRegistrar(ctx context.Context, p *DomainPurchase, |
| } |
| } |
| +// transferRecordIsOurs says whether a status read is about this purchase's |
| +// transfer. With a ref, only the record of that name is (the adapter answers |
| +// none when it is not there). Without one (the request's answer was lost), |
| +// only a record the registrar created at or after the submit is: an earlier |
| +// record of the same domain, such as a failed transfer before this retry, |
| +// is older. A record with no creation time cannot be told apart, so it is |
| +// not ours. "None" is never anyone's. |
| +func transferRecordIsOurs(f *transferFacts, st registrar.TransferStatus) bool { |
| + if st.State == registrar.TransferNone { |
| + return true |
| + } |
| + if f.TransferRef != "" { |
| + return st.Ref == f.TransferRef |
| + } |
| + // The registrar's times are to the second; the submit's is finer. |
| + return !st.Created.IsZero() && !st.Created.Before(f.SubmittedAt.Truncate(time.Second)) |
| +} |
| + |
| // 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 |
| @@ -315,11 +344,18 @@ func (s *Server) gatherTransferRefund(ctx context.Context, p *DomainPurchase, o |
| } |
| } |
| if !found { |
| + // None made for this attempt: refused outright (recorded when |
| + // its create was refused), else not sent or not answered yet. |
| f.Refund = fNone |
| + if f.RefundReason == refundRefused { |
| + f.Refund = fFailed |
| + } |
| return |
| } |
| - f.RefundID = r.ID |
| + f.RefundID, f.RefundReason = r.ID, "" |
| } |
| + // A refund made for the attempt ends a run of refused creates. |
| + f.RefundRefusals = 0 |
| switch r.Status { |
| case billing.RefundSucceeded: |
| f.Refund = fPending |
| @@ -497,7 +533,12 @@ func (s *Server) submitTransfer(ctx context.Context, p *DomainPurchase, o *trans |
| return stepErr |
| } |
| if err == nil { |
| - return nil |
| + if st.Ref == "" { |
| + return nil |
| + } |
| + // The record's identity, not its outcome: reads name it from now on. |
| + o.facts.TransferRef = st.Ref |
| + return s.recordTransfer(ctx, p, o, PurchaseTransferSubmitting, nil) |
| } |
| if !errors.Is(err, registrar.ErrRefused) { |
| return err |
| @@ -520,7 +561,7 @@ func (s *Server) refundTransfer(ctx context.Context, acct *Account, p *DomainPur |
| if err != nil { |
| return err |
| } |
| - o.facts.RefundAttempt, o.facts.RefundID, o.facts.Refund = n, "", fNone |
| + o.facts.RefundAttempt, o.facts.RefundID, o.facts.Refund, o.facts.RefundReason = n, "", fNone, "" |
| if err := s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), func(q *DomainPurchase) { q.RefundPrepared = &prepared }); err != nil { |
| return err |
| } |
| @@ -541,13 +582,27 @@ func (s *Server) refundTransfer(ctx context.Context, acct *Account, p *DomainPur |
| if stepErr := transferStep("refund:sent"); stepErr != nil { |
| return stepErr |
| } |
| + if errors.Is(err, billing.ErrRefused) { |
| + // Refused outright: nothing was made, and resending the same request |
| + // gets the same answer. Recorded on this attempt; the next one waits |
| + // out the backoff (decideTransfer) and the operator is alerted |
| + // through the refused alerts, which stand for this attempt's |
| + // failure alert too. |
| + o.facts.Refund, o.facts.RefundReason, o.facts.RefundFailedAt = fFailed, refundRefused, o.facts.Now |
| + o.facts.RefundRefusals++ |
| + if o.facts.Alerts == nil { |
| + o.facts.Alerts = map[string]time.Time{} |
| + } |
| + o.facts.Alerts[refundFailedAlert(n)] = o.facts.Now |
| + return errors.Join(err, s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil)) |
| + } |
| if err != nil { |
| return err |
| } |
| if res.Refund == nil || res.Refund.ID == "" { |
| return nil |
| } |
| - o.facts.RefundID = res.Refund.ID |
| + o.facts.RefundID, o.facts.RefundRefusals = res.Refund.ID, 0 |
| return s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil) |
| } |
diff --git a/internal/console/domaintransfer_decide.go b/internal/console/domaintransfer_decide.go| index 622dd487c..167957b1d 100644 |
| --- a/internal/console/domaintransfer_decide.go |
| +++ b/internal/console/domaintransfer_decide.go |
| @@ -76,8 +76,12 @@ const ( |
| 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 |
| + alertRefundRefused = "refund-refused" // the provider refuses the refund create: at once, then daily |
| ) |
| +// refundRefused is RefundReason for a create the provider refused outright. |
| +const refundRefused = "refused" |
| + |
| const ( |
| transferUnknownAlertAfter = 24 * time.Hour |
| transferLapseAlertBefore = 24 * time.Hour |
| @@ -155,6 +159,14 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| case fNone: |
| return transferDecision{Action: aCreateRefund, RefundAttempt: max(f.RefundAttempt, 1)} |
| case fFailed: |
| + if f.RefundReason == refundRefused { |
| + // Refused outright: the next attempt waits out the backoff; |
| + // the refused alerts tell the operator meanwhile. |
| + if f.Now.Before(f.RefundFailedAt.Add(refundRefusedBackoff(f.RefundRefusals))) { |
| + return wait |
| + } |
| + return transferDecision{Action: aCreateRefund, RefundAttempt: f.RefundAttempt + 1} |
| + } |
| // 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: |
| @@ -193,6 +205,13 @@ func dueTransferAlert(f transferFacts) string { |
| if accepted && (f.Payment == pFailed || f.Payment == pCancelled) && !sent(alertCaptureRefused) { |
| return alertCaptureRefused |
| } |
| + if reg == rFailed && f.Payment == pCaptured && f.Refund == fFailed && f.RefundReason == refundRefused { |
| + // At the first refusal of a run of them, then daily while it lasts. |
| + last := f.Alerts[alertRefundRefused] |
| + if last.IsZero() || (f.RefundRefusals == 1 && last.Before(f.RefundFailedAt)) || !f.Now.Before(last.Add(refundRefusedAlertEvery)) { |
| + return alertRefundRefused |
| + } |
| + } |
| if reg == rFailed && f.Payment == pCaptured { |
| // Every attempt before the current one failed; so did the current |
| // one when its refund reads failed. |
| @@ -209,4 +228,18 @@ func dueTransferAlert(f transferFacts) string { |
| return "" |
| } |
| +// refundRefusedBackoff is the wait after the nth refund create refused in a |
| +// row: 1 h, then 6 h, then 24 h. |
| +func refundRefusedBackoff(refusals int) time.Duration { |
| + switch { |
| + case refusals <= 1: |
| + return time.Hour |
| + case refusals == 2: |
| + return 6 * time.Hour |
| + } |
| + return 24 * time.Hour |
| +} |
| + |
| +const refundRefusedAlertEvery = 24 * time.Hour |
| + |
| 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| index 4c55bf596..76a8c1b94 100644 |
| --- a/internal/console/domaintransfer_decide_test.go |
| +++ b/internal/console/domaintransfer_decide_test.go |
| @@ -86,7 +86,26 @@ func TestDecideTransferTable(t *testing.T) { |
| pendingRefusedAlerted := pendingRefused |
| pendingRefusedAlerted.Alerts = map[string]time.Time{alertCaptureRefused: decideBase} |
| + refused := func(refusals int, since, alerted time.Duration) transferFacts { |
| + f := quietFacts(rFailed, pCaptured, fFailed) |
| + f.RefundAttempt, f.RefundReason, f.RefundRefusals, f.RefundFailedAt = refusals, refundRefused, refusals, decideBase.Add(-since) |
| + f.Alerts = map[string]time.Time{refundFailedAlert(1): decideBase, refundFailedAlert(2): decideBase, refundFailedAlert(3): decideBase} |
| + if alerted >= 0 { |
| + f.Alerts[alertRefundRefused] = decideBase.Add(-alerted) |
| + } |
| + return f |
| + } |
| rows := []row{ |
| + {"refund refused once, 59 min ago: wait", refused(1, 59*time.Minute, 0), aWait, "", 0, ""}, |
| + {"refund refused once, an hour ago: the next attempt, no failed alert", refused(1, time.Hour, 0), aCreateRefund, "", 2, ""}, |
| + {"refund refused twice, 5 h ago: wait", refused(2, 5*time.Hour, 0), aWait, "", 0, ""}, |
| + {"refund refused twice, 6 h ago: the next attempt", refused(2, 6*time.Hour, 0), aCreateRefund, "", 3, ""}, |
| + {"refund refused three times, 23 h ago: wait", refused(3, 23*time.Hour, 23*time.Hour-time.Minute), aWait, "", 0, ""}, |
| + {"refund refused three times, 24 h ago: the next attempt", refused(3, 24*time.Hour, 0), aCreateRefund, "", 4, ""}, |
| + {"refund refused, not yet alerted: alert", refused(1, 0, -1), aAlert, "", 0, alertRefundRefused}, |
| + {"refund refused, alerted 23 h ago: wait", refused(3, 2*time.Hour, 23*time.Hour), aWait, "", 0, ""}, |
| + {"refund refused, alerted a day ago: alert again", refused(3, 2*time.Hour, 24*time.Hour), aAlert, "", 0, alertRefundRefused}, |
| + {"first refusal of a new run, alerted before it: alert", refused(1, 0, time.Hour), aAlert, "", 0, alertRefundRefused}, |
| {"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, ""}, |
| @@ -249,12 +268,13 @@ func TestDecideTransferSimulation(t *testing.T) { |
| } |
| type transferSim struct { |
| - t *testing.T |
| - tf *transferFixture |
| - seed uint64 |
| - rng *rand.Rand |
| - reg *simRegistrar |
| - bill *billingtest.Fake |
| + t *testing.T |
| + tf *transferFixture |
| + seed uint64 |
| + rng *rand.Rand |
| + reg *simRegistrar |
| + bill *billingtest.Fake |
| + billing *simBilling |
| // violation is a breach the provider wrapper saw at a send. |
| violation string |
| faults bool |
| @@ -343,22 +363,26 @@ type simRegistrar struct { |
| final registrar.TransferStatus // that outcome |
| prev *registrar.TransferStatus // the previous state, for stale reads |
| requests int |
| + refused bool // the request itself was refused |
| } |
| func (r *simRegistrar) RequestTransfer(ctx context.Context, req registrar.TransferRequest) (registrar.TransferStatus, error) { |
| r.requests++ |
| st, err := r.Fake.RequestTransfer(ctx, req) |
| + if errors.Is(err, registrar.ErrRefused) { |
| + r.refused = true |
| + } |
| 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) { |
| +func (r *simRegistrar) TransferStatus(ctx context.Context, domain, ref 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) |
| + st, err := r.Fake.TransferStatus(ctx, domain, ref) |
| if err != nil || st.State == registrar.TransferNone { |
| return st, err |
| } |
| @@ -387,6 +411,13 @@ func (r *simRegistrar) unanswered() bool { return r.hidden || r.dropped || r.acc |
| type simBilling struct { |
| *billingtest.Fake |
| sim *transferSim |
| + // The last refund create: its attempt, whether it was refused, and how |
| + // many in a row were, for the backoff check. |
| + lastAttempt int |
| + lastRefused bool |
| + refusedAt time.Time |
| + refusals int |
| + runsStarted []time.Time // when each run of refused creates began |
| } |
| func (b *simBilling) Refunds(ctx context.Context, pi string) ([]billing.RefundInfo, error) { |
| @@ -415,6 +446,36 @@ func (b *simBilling) Send(ctx context.Context, p billing.Prepared) (billing.Resu |
| b.sim.violation = fmt.Sprintf("I6: refund attempt %d sent while attempt %d is %s", body.Attempt, r.Attempt, r.Status) |
| } |
| } |
| + now := b.sim.tf.now |
| + if b.lastRefused && body.Attempt == b.lastAttempt+1 && now.Before(b.refusedAt.Add(refundRefusedBackoff(b.refusals))) { |
| + b.sim.violation = fmt.Sprintf("refund attempt %d sent %s after %d refusals, inside the backoff", body.Attempt, now.Sub(b.refusedAt), b.refusals) |
| + } |
| + var res billing.Result |
| + var err error |
| + if b.sim.faults && b.sim.chance(0.15) { |
| + // Refused outright: nothing made. |
| + err = fmt.Errorf("%w: sim: refund refused", billing.ErrRefused) |
| + b.sim.paths["refund refused"]++ |
| + } else { |
| + res, err = b.Fake.Send(ctx, p) |
| + } |
| + sameAttempt := body.Attempt == b.lastAttempt |
| + b.lastAttempt = body.Attempt |
| + if errors.Is(err, billing.ErrRefused) { |
| + if !b.lastRefused { |
| + b.refusals = 0 |
| + b.runsStarted = append(b.runsStarted, now) |
| + } |
| + if !(b.lastRefused && sameAttempt) { |
| + // One refusal per attempt: the same attempt refused again |
| + // (resent after a crash hid the first answer) is one. |
| + b.refusals++ |
| + } |
| + b.lastRefused, b.refusedAt = true, now |
| + } else { |
| + b.lastRefused, b.refusals = false, 0 |
| + } |
| + return res, err |
| } |
| return b.Fake.Send(ctx, p) |
| } |
| @@ -469,9 +530,18 @@ func (sim *transferSim) run(i int) { |
| 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} |
| + sim.billing = &simBilling{Fake: bill, sim: sim} |
| + tf.srv.cfg.Billing.Provider = sim.billing |
| 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} |
| + reg.Now = func() time.Time { return tf.now } |
| + if sim.chance(0.25) { |
| + // An earlier transfer of this domain failed (a wrong code, say) and |
| + // left its record: it must never settle this one. |
| + reg.Earlier = map[string][]registrar.TransferStatus{domain: {{State: registrar.TransferFailed, Reason: "auth_code", |
| + Ref: fmt.Sprintf("old-%d", i), Created: tf.now.Add(-time.Duration(1+sim.rng.IntN(72)) * time.Hour)}}} |
| + sim.paths["earlier failed record"]++ |
| + } |
| reasons := []string{"auth_code", "rejected", "timeout", "", "something-new"} |
| switch roll := sim.rng.Float64(); { |
| case roll < 0.15: |
| @@ -808,28 +878,49 @@ func (sim *transferSim) check(i int, before, p *DomainPurchase, code string) { |
| if len(sim.leaks.leaks) > 0 { |
| sim.fail(i, "auth code logged: %q", sim.leaks.leaks[0]) |
| } |
| + // Only its own record settles it: failed means the request was refused |
| + // or its own transfer failed. |
| + if reg == rFailed && p.Facts.Resolution == "" && !sim.reg.refused && !(sim.reg.final.State == registrar.TransferFailed && !sim.reg.acceptedAt.IsZero()) { |
| + sim.fail(i, "settled failed on a record that is not its own: %+v", p.Facts) |
| + } |
| // 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. |
| +// checkAlertsOnce: no alert kind but the weekly and the refused ones is |
| +// delivered twice for a purchase; weekly ones are a week apart; refused |
| +// ones a day apart, unless a new run of refusals began between them. |
| func (sim *transferSim) checkAlertsOnce(i int, p *DomainPurchase) { |
| seen := map[string]int{} |
| - var weekly []time.Time |
| + var weekly, refused []time.Time |
| for _, pg := range sim.pages[p.ID] { |
| seen[pg.reason]++ |
| - if pg.reason == transferAlertReason(alertUnknownWeekly) { |
| + switch pg.reason { |
| + case transferAlertReason(alertUnknownWeekly): |
| weekly = append(weekly, pg.at) |
| + case transferAlertReason(alertRefundRefused): |
| + refused = append(refused, pg.at) |
| } |
| } |
| for reason, n := range seen { |
| - if n > 1 && reason != transferAlertReason(alertUnknownWeekly) { |
| + if n > 1 && reason != transferAlertReason(alertUnknownWeekly) && reason != transferAlertReason(alertRefundRefused) { |
| sim.fail(i, "I10: alert %q delivered %d times", reason, n) |
| } |
| } |
| + for k := 1; k < len(refused); k++ { |
| + if refused[k].Sub(refused[k-1]) >= refundRefusedAlertEvery { |
| + continue |
| + } |
| + newRun := false |
| + for _, at := range sim.billing.runsStarted { |
| + newRun = newRun || (at.After(refused[k-1]) && !at.After(refused[k])) |
| + } |
| + if !newRun { |
| + sim.fail(i, "refused alerts %s apart with no new run of refusals", refused[k].Sub(refused[k-1])) |
| + } |
| + } |
| 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])) |
diff --git a/internal/console/domaintransfer_facts.go b/internal/console/domaintransfer_facts.go| index 649348a19..9b117a559 100644 |
| --- a/internal/console/domaintransfer_facts.go |
| +++ b/internal/console/domaintransfer_facts.go |
| @@ -81,12 +81,23 @@ type transferFacts struct { |
| // 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"` |
| + Accepted bool `json:",omitempty"` |
| + // TransferRef is the registrar's identity for this purchase's transfer |
| + // record (from the request's answer, or the first read accepted as |
| + // ours). Reads name it, so an earlier record of the same domain, such |
| + // as a failed transfer before this one, never settles this purchase. |
| + TransferRef string `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"` |
| + RefundAttempt int `json:",omitempty"` |
| + RefundID string `json:",omitempty"` |
| + // RefundReason is refundRefused when the provider refused the current |
| + // attempt's create outright (nothing made); RefundFailedAt is when, and |
| + // RefundRefusals how many creates in a row were refused (the backoff). |
| + RefundReason string `json:",omitempty"` |
| + RefundFailedAt time.Time `json:",omitzero"` |
| + RefundRefusals int `json:",omitempty"` |
| Resolution string `json:",omitempty"` // operator: "", "failed", "completed" |
| CaptureAttempted bool `json:",omitempty"` |
| CheckoutExpires time.Time `json:",omitzero"` |
diff --git a/internal/console/domaintransfer_test.go b/internal/console/domaintransfer_test.go| index b46c21e8d..88c995737 100644 |
| --- a/internal/console/domaintransfer_test.go |
| +++ b/internal/console/domaintransfer_test.go |
| @@ -57,6 +57,7 @@ func newTransferFixture(t *testing.T) *transferFixture { |
| 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 } |
| + f.reg.Now = func() time.Time { return tf.now } |
| pageDomainPurchase = func(_ context.Context, _, _, body string) error { |
| tf.mu.Lock() |
| defer tf.mu.Unlock() |
| @@ -917,3 +918,120 @@ func TestPointRefusesTransferredDomain(t *testing.T) { |
| t.Fatalf("zones touched: %v", tf.zone.Zones) |
| } |
| } |
| + |
| +// TestTransferIgnoresEarlierFailedRecordOfSameDomain: the domain's first |
| +// transfer failed (wrong code) and left its record; the retry must never be |
| +// settled by it. With the request's answer lost (no ref), the old record is |
| +// older than the submit and reads as unknown; once the retry's own record |
| +// shows, it is followed by its ref. With the answer kept, reads name the |
| +// new record from the start. |
| +func TestTransferIgnoresEarlierFailedRecordOfSameDomain(t *testing.T) { |
| + for _, lost := range []bool{true, false} { |
| + t.Run(fmt.Sprint("answer lost=", lost), func(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + tf.reg.Earlier = map[string][]registrar.TransferStatus{"shop.com": {{State: registrar.TransferFailed, Reason: "auth_code", Ref: "old-1", Created: tf.now.Add(-2 * time.Hour)}}} |
| + p := tf.start(t) |
| + tf.authorise(t, p) |
| + if lost { |
| + tf.reg.RequestErr = registrar.ErrIndeterminate // lost on the way: the new record shows later |
| + } |
| + p = tf.pass(t, p.ID) |
| + if p.State != PurchaseTransferSubmitting || p.Facts.TransferRef != map[bool]string{true: "", false: "transfer-1"}[lost] { |
| + t.Fatalf("after submit: %+v", p.Facts) |
| + } |
| + for i := 0; i < 6; i++ { |
| + tf.tick(transferStatusEvery) |
| + p = tf.pass(t, p.ID) |
| + if p.Facts.Registrar == rFailed || !purchaseLive(p.State) { |
| + t.Fatalf("pass %d: settled by the earlier record: %+v", i, p.Facts) |
| + } |
| + } |
| + if lost { |
| + if p.Facts.Registrar != rUnknown { |
| + t.Fatalf("no record of its own yet: %+v", p.Facts) |
| + } |
| + tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferPending}) |
| + } |
| + tf.tick(transferStatusEvery) |
| + p = tf.pass(t, p.ID) |
| + if p.Facts.Registrar != rPending || p.Facts.TransferRef == "" || p.Facts.TransferRef == "old-1" { |
| + t.Fatalf("its own record: %+v", p.Facts) |
| + } |
| + 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)}}) |
| + for i := 0; i < 4 && purchaseLive(p.State); i++ { |
| + tf.tick(transferStatusEvery) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if p.State != PurchaseDone || tf.intentStatus(t, p) != "succeeded" { |
| + t.Fatalf("end: %+v", p) |
| + } |
| + }) |
| + } |
| + // A record of another transfer under the ref's name is never ours. |
| + tf := newTransferFixture(t) |
| + p := tf.submitted(t) |
| + tf.reg.Transfers["shop.com"] = registrar.TransferStatus{State: registrar.TransferFailed, Ref: "someone-else", Created: tf.now.Add(time.Minute)} |
| + for i := 0; i < 3; i++ { |
| + tf.tick(transferStatusEvery) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if p.Facts.Registrar != rUnknown { |
| + t.Fatalf("a record not named by the ref settled it: %+v", p.Facts) |
| + } |
| +} |
| + |
| +// TestTransferRefundRefusedBacksOffAndAlerts: the provider refuses the |
| +// refund create outright. The refusal is recorded on the attempt; the next |
| +// attempt waits 1 h, then 6 h, then 24 h between attempts; the operator is |
| +// alerted at the first refusal and daily while it lasts; once the provider |
| +// takes it, the refund completes and the purchase fails, refunded. |
| +func TestTransferRefundRefusedBacksOffAndAlerts(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + p := tf.failAfterCapture(t, "rejected") |
| + refusing := true |
| + tf.fake.BeforeSend = func(pr billing.Prepared) error { |
| + if refusing && pr.Kind == billing.PreparedRefund { |
| + return fmt.Errorf("%w: charge disputed", billing.ErrRefused) |
| + } |
| + return nil |
| + } |
| + start := tf.now |
| + p = tf.pass(t, p.ID) |
| + if p.Facts.RefundAttempt != 1 || p.Facts.Refund != fFailed || p.Facts.RefundReason != refundRefused || p.Facts.RefundRefusals != 1 { |
| + t.Fatalf("refusal not recorded: %+v", p.Facts) |
| + } |
| + sendTimes := []time.Duration{0} |
| + sends := tf.sent(billing.PreparedRefund) |
| + for tf.now.Before(start.Add(50 * time.Hour)) { |
| + tf.tick(10 * time.Minute) |
| + p = tf.pass(t, p.ID) |
| + if n := tf.sent(billing.PreparedRefund); n != sends { |
| + sends = n |
| + sendTimes = append(sendTimes, tf.now.Sub(start)) |
| + } |
| + } |
| + want := []time.Duration{0, time.Hour, 7 * time.Hour, 31 * time.Hour} |
| + if fmt.Sprint(sendTimes) != fmt.Sprint(want) { |
| + t.Fatalf("refund sends at %v, want %v", sendTimes, want) |
| + } |
| + if got := tf.alerts(alertRefundRefused); got != 3 { |
| + t.Fatalf("refused alerts = %d over 50 h, want 3 (at once, then daily): %v", got, tf.pages) |
| + } |
| + for n := 1; n <= 4; n++ { |
| + if tf.alerts(refundFailedAlert(n)) != 0 { |
| + t.Fatalf("a refused attempt also alerted as a failed refund: %v", tf.pages) |
| + } |
| + } |
| + if p.State != PurchaseTransferRefunding || len(tf.refunds(t, p)) != 0 { |
| + t.Fatalf("while refused: %+v", p) |
| + } |
| + refusing = false |
| + for i := 0; i < 40 && purchaseLive(p.State); i++ { |
| + tf.tick(time.Hour) |
| + p = tf.pass(t, p.ID) |
| + } |
| + list := tf.refunds(t, p) |
| + if p.State != PurchaseFailed || len(list) != 1 || list[0].Status != billing.RefundSucceeded || p.Facts.RefundRefusals != 0 { |
| + t.Fatalf("end: %+v %+v", p, list) |
| + } |
| +} |
diff --git a/internal/registrar/openprovider/client.go b/internal/registrar/openprovider/client.go| index 66fe15c4b..b77557a91 100644 |
| --- a/internal/registrar/openprovider/client.go |
| +++ b/internal/registrar/openprovider/client.go |
| @@ -230,6 +230,7 @@ type domainRecord struct { |
| Domain domainName `json:"domain"` |
| Status string `json:"status"` |
| Expires string `json:"expiration_date"` |
| + Created string `json:"creation_date"` |
| Nameservers []nameserver `json:"name_servers"` |
| Deleted bool `json:"is_deleted"` |
| } |
| @@ -280,27 +281,61 @@ func (c *Client) Lookup(ctx context.Context, domain string) (registrar.Registere |
| // listDomain finds the domain in our account, in any status. found is false |
| // when the account has no such domain or only a deleted one. |
| func (c *Client) listDomain(ctx context.Context, domain string) (domainRecord, bool, error) { |
| + records, total, err := c.listDomainRecords(ctx, domain) |
| + if err != nil { |
| + return domainRecord{}, false, err |
| + } |
| + if len(records) == 0 && total == 0 { |
| + return domainRecord{}, false, nil |
| + } |
| + if len(records) != 1 { |
| + return domainRecord{}, false, errors.New("openprovider: unexpected domain results") |
| + } |
| + if records[0].Deleted { |
| + return domainRecord{}, false, nil |
| + } |
| + return records[0], true, nil |
| +} |
| + |
| +// listDomainRecords is the records one answer holds for domain, deleted |
| +// ones included, and the total the answer claims. A record for another |
| +// name is an error. |
| +func (c *Client) listDomainRecords(ctx context.Context, domain string) ([]domainRecord, int, error) { |
| var response struct { |
| Results *[]domainRecord `json:"results"` |
| Total int `json:"total"` |
| } |
| if err := c.call(ctx, http.MethodGet, "/domains?full_name="+url.QueryEscape(domain), nil, &response); err != nil { |
| - return domainRecord{}, false, err |
| + return nil, 0, err |
| } |
| if response.Results == nil { |
| - return domainRecord{}, false, errors.New("openprovider: missing domain results") |
| + return nil, 0, errors.New("openprovider: missing domain results") |
| } |
| records := *response.Results |
| - if len(records) == 0 && response.Total == 0 { |
| - return domainRecord{}, false, nil |
| + for _, r := range records { |
| + if r.Domain.Name+"."+r.Domain.Extension != domain { |
| + return nil, 0, errors.New("openprovider: unexpected domain results") |
| + } |
| } |
| - if len(records) != 1 || records[0].Domain.Name+"."+records[0].Domain.Extension != domain { |
| - return domainRecord{}, false, errors.New("openprovider: unexpected domain results") |
| + return records, response.Total, nil |
| +} |
| + |
| +// created is the record's creation_date, read as UTC (the reference gives |
| +// no zone); zero when absent or unreadable. |
| +func (r domainRecord) created() time.Time { |
| + for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} { |
| + if parsed, err := time.Parse(layout, r.Created); err == nil { |
| + return parsed.UTC() |
| + } |
| } |
| - if records[0].Deleted { |
| - return domainRecord{}, false, nil |
| + return time.Time{} |
| +} |
| + |
| +func (r domainRecord) ref() string { |
| + if r.ID <= 0 { |
| + return "" |
| } |
| - return records[0], true, nil |
| + return strconv.FormatInt(r.ID, 10) |
| } |
| func (r domainRecord) registered() (registrar.Registered, error) { |
| @@ -707,27 +742,36 @@ func (c *Client) RequestTransfer(ctx context.Context, in registrar.TransferReque |
| } |
| return refused, err |
| } |
| + // The answer's id is the new transfer record's: later reads name it. |
| + ref := domainRecord{ID: response.ID}.ref() |
| switch response.Status { |
| case "REQ": |
| - return registrar.TransferStatus{State: registrar.TransferPending}, nil |
| + return registrar.TransferStatus{State: registrar.TransferPending, Ref: ref}, nil |
| case "ACT": |
| // A realtime transfer. Without its ID and expiry it is accepted but |
| // not yet readable as a registration: the status read completes it. |
| record := domainRecord{ID: response.ID, Domain: d, Status: response.Status, Expires: response.Expires, Nameservers: request.Nameservers} |
| if registered, err := record.registered(); err == nil { |
| - return registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registered}, nil |
| + return registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registered, Ref: ref}, nil |
| } |
| - return registrar.TransferStatus{State: registrar.TransferPending}, nil |
| + return registrar.TransferStatus{State: registrar.TransferPending, Ref: ref}, nil |
| } |
| return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: unrecognised transfer status", registrar.ErrIndeterminate) |
| } |
| -// TransferStatus reads the domain in our account. Documented statuses: ACT |
| -// (active), REQ (requested, awaiting approval), FAI (failed transfer), DEL; |
| -// the API's domain statistics add PEN (pending) and REJ (rejected). Any |
| -// answer it cannot read is indeterminate, never a refusal or "none". |
| -func (c *Client) TransferStatus(ctx context.Context, domain string) (registrar.TransferStatus, error) { |
| - record, found, err := c.listDomain(ctx, domain) |
| +// TransferStatus reads one of the domain's records in our account: the one |
| +// whose id is ref, or with no ref the newest by creation date (an earlier |
| +// failed transfer of the same domain keeps its own record). Documented |
| +// statuses: ACT (active), REQ (requested, awaiting approval), FAI (failed |
| +// transfer), DEL; the API's domain statistics add PEN (pending) and REJ |
| +// (rejected). Any answer it cannot read is indeterminate, never a refusal |
| +// or "none". |
| +func (c *Client) TransferStatus(ctx context.Context, domain, ref string) (registrar.TransferStatus, error) { |
| + records, total, err := c.listDomainRecords(ctx, domain) |
| + if err == nil && len(records) != total { |
| + // A partial list may leave out the record asked for, or the newest. |
| + err = errors.New("openprovider: domain results incomplete") |
| + } |
| if err != nil { |
| var answer *providerError |
| if errors.As(err, &answer) && answer.readable && (answer.code == 320 || answer.code == 500) { |
| @@ -738,22 +782,45 @@ func (c *Client) TransferStatus(ctx context.Context, domain string) (registrar.T |
| // %s, not %w: no refusal kind of the read reaches the caller. |
| return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: transfer status unreadable: %s", registrar.ErrIndeterminate, trusted(err).Error()) |
| } |
| - if !found { |
| + var record *domainRecord |
| + for i := range records { |
| + r := &records[i] |
| + switch { |
| + case ref != "": |
| + if r.ref() == ref { |
| + record = r |
| + } |
| + case record == nil: |
| + record = r |
| + default: |
| + newest, this := record.created(), r.created() |
| + if newest.IsZero() || this.IsZero() { |
| + return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: several records and no creation date", registrar.ErrIndeterminate) |
| + } |
| + if this.After(newest) { |
| + record = r |
| + } |
| + } |
| + } |
| + if record == nil || record.Deleted { |
| return registrar.TransferStatus{State: registrar.TransferNone}, nil |
| } |
| + st := registrar.TransferStatus{Ref: record.ref(), Created: record.created()} |
| switch record.Status { |
| case "REQ", "PEN": |
| - return registrar.TransferStatus{State: registrar.TransferPending}, nil |
| + st.State = registrar.TransferPending |
| case "FAI": |
| - return registrar.TransferStatus{State: registrar.TransferFailed}, nil |
| + st.State = registrar.TransferFailed |
| case "REJ": |
| - return registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}, nil |
| + st.State, st.Reason = registrar.TransferFailed, "rejected" |
| case "ACT": |
| registered, err := record.registered() |
| if err != nil { |
| return registrar.TransferStatus{}, err |
| } |
| - return registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registered}, nil |
| + st.State, st.Registered = registrar.TransferCompleted, registered |
| + default: |
| + return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: unrecognised domain status", registrar.ErrIndeterminate) |
| } |
| - return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: unrecognised domain status", registrar.ErrIndeterminate) |
| + return st, nil |
| } |
diff --git a/internal/registrar/openprovider/client_test.go b/internal/registrar/openprovider/client_test.go| index 9870c4cc1..a878bd1d0 100644 |
| --- a/internal/registrar/openprovider/client_test.go |
| +++ b/internal/registrar/openprovider/client_test.go |
| @@ -12,6 +12,7 @@ import ( |
| "net/url" |
| "os" |
| "reflect" |
| + "strconv" |
| "strings" |
| "sync/atomic" |
| "testing" |
| @@ -625,6 +626,7 @@ func TestRequestTransferReplyStates(t *testing.T) { |
| wantErr error |
| }{ |
| {"requested", `{"status":"REQ"}`, registrar.TransferPending, nil}, |
| + {"requested-with-id", `{"id":123456789,"status":"REQ"}`, registrar.TransferPending, nil}, |
| {"realtime", `{"id":123456789,"status":"ACT","expiration_date":"2020-03-31 23:59:59"}`, registrar.TransferCompleted, nil}, |
| {"realtime-without-id", `{"status":"ACT","expiration_date":"2020-03-31 23:59:59"}`, registrar.TransferPending, nil}, |
| {"failed-reply", `{"status":"FAI"}`, "", registrar.ErrIndeterminate}, |
| @@ -639,6 +641,9 @@ func TestRequestTransferReplyStates(t *testing.T) { |
| if !errors.Is(err, tc.wantErr) || (tc.wantErr == nil && err != nil) || got.State != tc.want { |
| t.Fatalf("RequestTransfer=%+v, %v", got, err) |
| } |
| + if strings.Contains(tc.data, `"id"`) != (got.Ref == "123456789") { |
| + t.Fatalf("Ref=%q from %s", got.Ref, tc.data) |
| + } |
| if tc.want == registrar.TransferCompleted { |
| r := got.Registered |
| if r.Domain != "shop.example" || r.RegistrarID != "123456789" || !r.Expires.Equal(expires) || !reflect.DeepEqual(r.Nameservers, transferRequest().Nameservers) { |
| @@ -785,16 +790,19 @@ func TestRequestTransferRefusalReasons(t *testing.T) { |
| func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| expires := time.Date(2014, 7, 4, 17, 14, 44, 0, time.UTC) |
| + created := time.Date(2013, 7, 4, 17, 14, 44, 0, time.UTC) // the record's creation_date |
| + ref := "123456789" |
| for _, tc := range []struct { |
| name, old, new string |
| want registrar.TransferStatus |
| wantErr bool |
| }{ |
| - {"requested", "", "", registrar.TransferStatus{State: registrar.TransferPending}, false}, |
| - {"pending", `"status": "REQ"`, `"status": "PEN"`, registrar.TransferStatus{State: registrar.TransferPending}, false}, |
| - {"active", `"status": "REQ"`, `"status": "ACT"`, registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{Domain: "shop.example", RegistrarID: "123456789", Expires: expires, Nameservers: []string{"ns1.dns.example", "ns2.dns.example"}}}, false}, |
| - {"failed", `"status": "REQ"`, `"status": "FAI"`, registrar.TransferStatus{State: registrar.TransferFailed}, false}, |
| - {"rejected", `"status": "REQ"`, `"status": "REJ"`, registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}, false}, |
| + {"requested", "", "", registrar.TransferStatus{State: registrar.TransferPending, Ref: ref, Created: created}, false}, |
| + {"pending", `"status": "REQ"`, `"status": "PEN"`, registrar.TransferStatus{State: registrar.TransferPending, Ref: ref, Created: created}, false}, |
| + {"active", `"status": "REQ"`, `"status": "ACT"`, registrar.TransferStatus{State: registrar.TransferCompleted, Ref: ref, Created: created, Registered: registrar.Registered{Domain: "shop.example", RegistrarID: "123456789", Expires: expires, Nameservers: []string{"ns1.dns.example", "ns2.dns.example"}}}, false}, |
| + {"failed", `"status": "REQ"`, `"status": "FAI"`, registrar.TransferStatus{State: registrar.TransferFailed, Ref: ref, Created: created}, false}, |
| + {"rejected", `"status": "REQ"`, `"status": "REJ"`, registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected", Ref: ref, Created: created}, false}, |
| + {"no-creation-date", `"creation_date": "2013-07-04 17:14:44"`, `"creation_date": ""`, registrar.TransferStatus{State: registrar.TransferPending, Ref: ref}, false}, |
| {"deleted", `"is_deleted": false`, `"is_deleted": true`, registrar.TransferStatus{State: registrar.TransferNone}, false}, |
| {"unknown-status", `"status": "REQ"`, `"status": "PRE"`, registrar.TransferStatus{}, true}, |
| {"active-without-expiry", `"status": "REQ"`, `"status": "ACT", "expiration_date": ""`, registrar.TransferStatus{}, true}, |
| @@ -811,7 +819,7 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| } |
| fmt.Fprint(w, raw) |
| }, time.Second) |
| - got, err := c.TransferStatus(context.Background(), "shop.example") |
| + got, err := c.TransferStatus(context.Background(), "shop.example", "") |
| if (err != nil) != tc.wantErr || !reflect.DeepEqual(got, tc.want) { |
| t.Fatalf("TransferStatus=%+v, %v; want %+v", got, err, tc.want) |
| } |
| @@ -821,7 +829,7 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| c := newClient(t, func(w http.ResponseWriter, r *http.Request) { |
| fmt.Fprint(w, `{"code":0,"data":{"results":[],"total":0}}`) |
| }, time.Second) |
| - if got, err := c.TransferStatus(context.Background(), "shop.example"); err != nil || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferNone}) { |
| + if got, err := c.TransferStatus(context.Background(), "shop.example", ""); err != nil || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferNone}) { |
| t.Fatalf("TransferStatus=%+v, %v", got, err) |
| } |
| }) |
| @@ -832,7 +840,7 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| w.WriteHeader(status) |
| fmt.Fprint(w, response) |
| }, time.Second) |
| - got, err := c.TransferStatus(context.Background(), "shop.example") |
| + got, err := c.TransferStatus(context.Background(), "shop.example", "") |
| if err == nil || got.State != "" || !errors.Is(err, registrar.ErrIndeterminate) || errors.Is(err, registrar.ErrRefused) { |
| t.Fatalf("%d: an unreadable answer became %+v, %v", status, got, err) |
| } |
| @@ -847,7 +855,7 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| w.WriteHeader(400) |
| fmt.Fprintf(w, `{"code":%d,"desc":"not here"}`, code) |
| }, time.Second) |
| - if got, err := c.TransferStatus(context.Background(), "shop.example"); err != nil || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferNone}) { |
| + if got, err := c.TransferStatus(context.Background(), "shop.example", ""); err != nil || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferNone}) { |
| t.Fatalf("TransferStatus=%+v, %v", got, err) |
| } |
| }) |
| @@ -871,7 +879,7 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| w.WriteHeader(tc.status) |
| fmt.Fprint(w, tc.response) |
| }, time.Second) |
| - got, err := c.TransferStatus(context.Background(), "shop.example") |
| + got, err := c.TransferStatus(context.Background(), "shop.example", "") |
| if !errors.Is(err, registrar.ErrIndeterminate) || errors.Is(err, registrar.ErrRefused) || got.State != "" { |
| t.Fatalf("TransferStatus=%+v, %v", got, err) |
| } |
| @@ -879,6 +887,74 @@ func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) { |
| } |
| } |
| +// transferRecords is a list answer holding one record per (id, status, |
| +// creation date), each the transfer_status fixture's record with those |
| +// three changed: an earlier failed transfer of the domain and a retry. |
| +func transferRecords(t *testing.T, records ...[3]string) string { |
| + t.Helper() |
| + var doc map[string]any |
| + if err := json.Unmarshal(fixture(t, "transfer_status"), &doc); err != nil { |
| + t.Fatal(err) |
| + } |
| + data := doc["data"].(map[string]any) |
| + base := data["results"].([]any)[0].(map[string]any) |
| + var results []any |
| + for _, r := range records { |
| + rec := map[string]any{} |
| + for k, v := range base { |
| + rec[k] = v |
| + } |
| + id, _ := strconv.ParseInt(r[0], 10, 64) |
| + rec["id"], rec["status"], rec["creation_date"] = id, r[1], r[2] |
| + results = append(results, rec) |
| + } |
| + data["results"], data["total"] = results, len(results) |
| + b, err := json.Marshal(doc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| +// TestTransferStatusPicksItsOwnRecord: a domain whose first transfer failed |
| +// has two records once it is retried. A ref reads exactly its record (one |
| +// not there is none); with no ref the newest by creation date answers, with |
| +// its Ref and Created so the caller can tell whose it is. |
| +func TestTransferStatusPicksItsOwnRecord(t *testing.T) { |
| + answer := transferRecords(t, [3]string{"111", "FAI", "2026-11-20 09:00:00"}, [3]string{"222", "REQ", "2026-11-21 10:30:00"}) |
| + c := newClient(t, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, answer) }, time.Second) |
| + ctx := context.Background() |
| + for _, tc := range []struct { |
| + ref string |
| + want registrar.TransferStatus |
| + }{ |
| + {"", registrar.TransferStatus{State: registrar.TransferPending, Ref: "222", Created: time.Date(2026, 11, 21, 10, 30, 0, 0, time.UTC)}}, |
| + {"222", registrar.TransferStatus{State: registrar.TransferPending, Ref: "222", Created: time.Date(2026, 11, 21, 10, 30, 0, 0, time.UTC)}}, |
| + {"111", registrar.TransferStatus{State: registrar.TransferFailed, Ref: "111", Created: time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC)}}, |
| + {"333", registrar.TransferStatus{State: registrar.TransferNone}}, |
| + } { |
| + got, err := c.TransferStatus(ctx, "shop.example", tc.ref) |
| + if err != nil || !reflect.DeepEqual(got, tc.want) { |
| + t.Fatalf("ref %q: TransferStatus=%+v, %v; want %+v", tc.ref, got, err, tc.want) |
| + } |
| + } |
| + // Order in the answer does not matter. |
| + answer = transferRecords(t, [3]string{"222", "REQ", "2026-11-21 10:30:00"}, [3]string{"111", "FAI", "2026-11-20 09:00:00"}) |
| + if got, err := c.TransferStatus(ctx, "shop.example", ""); err != nil || got.Ref != "222" { |
| + t.Fatalf("newest first: %+v, %v", got, err) |
| + } |
| + // A list that says there are more records than it holds is unreadable. |
| + answer = strings.Replace(transferRecords(t, [3]string{"222", "REQ", "2026-11-21 10:30:00"}), `"total":1`, `"total":2`, 1) |
| + if got, err := c.TransferStatus(ctx, "shop.example", "222"); !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatalf("partial list: %+v, %v", got, err) |
| + } |
| + // With no ref and no creation dates, nothing says which is newest. |
| + answer = transferRecords(t, [3]string{"111", "FAI", ""}, [3]string{"222", "REQ", ""}) |
| + if got, err := c.TransferStatus(ctx, "shop.example", ""); !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatalf("undated records: %+v, %v", got, err) |
| + } |
| +} |
| + |
| func TestCheckTransferParsesCostAndLock(t *testing.T) { |
| cost := registrar.Money{Currency: "eur", Minor: 899} |
| for _, tc := range []struct { |
| @@ -1015,7 +1091,7 @@ func TestAuthCodeNeverInErrorText(t *testing.T) { |
| w.WriteHeader(status) |
| reply(t, w, "transfer_status_echo") |
| }, time.Second) |
| - got, err := c.TransferStatus(context.Background(), "shop.example") |
| + got, err := c.TransferStatus(context.Background(), "shop.example", "") |
| if err == nil || !errors.Is(err, registrar.ErrIndeterminate) { |
| t.Fatalf("TransferStatus=%+v, %v", got, err) |
| } |
diff --git a/internal/registrar/openprovider/testdata/README.md b/internal/registrar/openprovider/testdata/README.md| index fd08e403c..2ccfc618f 100644 |
| --- a/internal/registrar/openprovider/testdata/README.md |
| +++ b/internal/registrar/openprovider/testdata/README.md |
| @@ -25,4 +25,6 @@ Transfer request fields and the `ACT`/`REQ`/`FAI` statuses come from the `/v1` q |
| Code 311 comes from [https://openprovider.help/books/api-integrations/page/api-error-codes](https://openprovider.help/books/api-integrations/page/api-error-codes). Its description here is shortened. The same catalogue supplies privacy refusal codes 19006/19007 and unknown-error code 199 used in tests. |
| +`TestTransferStatusPicksItsOwnRecord` builds a synthetic list from `transfer_status.json`: the one record repeated with its `id`, `status` and `creation_date` changed, standing for an earlier failed transfer of the domain and its retry. The record's `id` and `creation_date` are the reference's `domainListDomainsResponse` fields; the transfer answer's `id` is the field `register.json` (`domainCreateDomainResponse`) carries, which the quickstart's transfer example leaves out. `creation_date` is read as UTC: the reference gives no zone. |
| + |
| Other test responses are synthetic variants for missing fields, pending or deleted registrations, errors, and empty results. Tests also change the premium flag and return a different customer handle to distinguish creation from update. These variants are not captured API responses. No live customer data or credentials are included. |
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go| index bf576ccfb..1f5fdb24f 100644 |
| --- a/internal/registrar/registrar.go |
| +++ b/internal/registrar/registrar.go |
| @@ -67,9 +67,14 @@ type Registrar interface { |
| // ErrIndeterminate means it may have been sent; the reply never decides |
| // the outcome, the next TransferStatus does. |
| RequestTransfer(ctx context.Context, r TransferRequest) (TransferStatus, error) |
| - // TransferStatus reads the transfer's state. A domain not in our account |
| - // is TransferNone; an answer the adapter cannot read is an error. |
| - TransferStatus(ctx context.Context, domain string) (TransferStatus, error) |
| + // TransferStatus reads one transfer record of domain: the one named ref |
| + // (TransferStatus.Ref from RequestTransfer's answer, or an earlier read) |
| + // when ref is set, else the domain's newest record. A record that is |
| + // not there, or a domain not in our account, is TransferNone; an answer |
| + // the adapter cannot read is an error. A domain may have several |
| + // records (an earlier failed transfer, then a retry): the caller decides |
| + // which is its own by Ref and Created. |
| + TransferStatus(ctx context.Context, domain, ref string) (TransferStatus, error) |
| } |
| type TransferCheck struct { |
| @@ -129,6 +134,12 @@ type TransferStatus struct { |
| // "expired", "not_registered", "unsupported"): the same fact, found late. |
| Reason string |
| Registered Registered // set when State == TransferCompleted (expiry from the registrar) |
| + // Ref is the registrar's own identity for this transfer record ("" when |
| + // the answer carries none), and Created when the registrar created the |
| + // record (zero when it does not say). A retry after an earlier failed |
| + // transfer of the same domain makes a new record: these tell them apart. |
| + Ref string |
| + Created time.Time |
| } |
| var ErrUnavailable = errors.New("registrar: domain not available") |
diff --git a/internal/registrar/registrar_test.go b/internal/registrar/registrar_test.go| index a79576286..c142abe68 100644 |
| --- a/internal/registrar/registrar_test.go |
| +++ b/internal/registrar/registrar_test.go |
| @@ -288,6 +288,8 @@ func TestTransferRequestStringRedactsAuthCode(t *testing.T) { |
| func TestFakeTransferLifecycle(t *testing.T) { |
| ctx := context.Background() |
| f := registrartest.New() |
| + clock := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) |
| + f.Now = func() time.Time { return clock } |
| var provider registrar.Registrar = f |
| check := registrar.TransferCheck{Transferable: true, Cost: registrar.Money{Currency: "eur", Minor: 899}} |
| f.TransferChecks["shop.example"] = check |
| @@ -299,7 +301,7 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| if got, err := provider.CheckTransfer(ctx, "unscripted.example"); err != nil || got.Transferable || got.Domain != "unscripted.example" || got.Reason == "" { |
| t.Fatalf("unscripted CheckTransfer = %+v, %v", got, err) |
| } |
| - if s, err := provider.TransferStatus(ctx, "shop.example"); err != nil || s.State != registrar.TransferNone { |
| + if s, err := provider.TransferStatus(ctx, "shop.example", ""); err != nil || s.State != registrar.TransferNone { |
| t.Fatalf("status before request = %+v, %v", s, err) |
| } |
| @@ -308,15 +310,16 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| if _, err := provider.RequestTransfer(ctx, empty); !errors.Is(err, registrar.ErrRefused) { |
| t.Fatalf("empty nameservers = %v, want ErrRefused", err) |
| } |
| - if s, _ := provider.TransferStatus(ctx, "shop.example"); s.State != registrar.TransferNone { |
| + if s, _ := provider.TransferStatus(ctx, "shop.example", ""); s.State != registrar.TransferNone { |
| t.Fatalf("refused request left %+v", s) |
| } |
| req := transferRequest() |
| s, err := provider.RequestTransfer(ctx, req) |
| - if err != nil || s.State != registrar.TransferPending { |
| + if err != nil || s.State != registrar.TransferPending || s.Ref == "" || !s.Created.Equal(clock) { |
| t.Fatalf("RequestTransfer = %+v, %v", s, err) |
| } |
| + ref := s.Ref |
| if f.LastTransfer.AuthCode != transferAuthCode || f.LastTransfer.Key != req.Key { |
| t.Fatalf("fake did not record the request: %v", f.LastTransfer) |
| } |
| @@ -324,7 +327,7 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| if f.LastTransfer.Nameservers[0] != "ns1.dns.example" { |
| t.Fatal("recorded request shares the caller's nameservers") |
| } |
| - if s, err := provider.TransferStatus(ctx, "shop.example"); err != nil || s.State != registrar.TransferPending { |
| + if s, err := provider.TransferStatus(ctx, "shop.example", ""); err != nil || s.State != registrar.TransferPending { |
| t.Fatalf("pending status = %+v, %v", s, err) |
| } |
| expires := time.Date(2027, 12, 2, 0, 0, 0, 0, time.UTC) |
| @@ -332,7 +335,8 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| Domain: "shop.example", RegistrarID: "transfer-1", Expires: expires, Nameservers: []string{"ns1.dns.example", "ns2.dns.example"}, |
| }} |
| f.Advance("shop.example", done) |
| - if s, err := provider.TransferStatus(ctx, "shop.example"); err != nil || !reflect.DeepEqual(s, done) { |
| + done.Ref, done.Created = ref, clock // the same record, moved on |
| + if s, err := provider.TransferStatus(ctx, "shop.example", ref); err != nil || !reflect.DeepEqual(s, done) { |
| t.Fatalf("completed status = %+v, %v; want %+v", s, err, done) |
| } |
| if r, found, err := provider.Lookup(ctx, "shop.example"); err != nil || !found || !r.Expires.Equal(expires) { |
| @@ -346,7 +350,7 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| t.Fatal(err) |
| } |
| f.Advance("other.example", registrar.TransferStatus{State: registrar.TransferFailed, Reason: "auth_code"}) |
| - if s, _ := provider.TransferStatus(ctx, "other.example"); s.State != registrar.TransferFailed || s.Reason != "auth_code" { |
| + if s, _ := provider.TransferStatus(ctx, "other.example", ""); s.State != registrar.TransferFailed || s.Reason != "auth_code" { |
| t.Fatalf("failed status = %+v", s) |
| } |
| @@ -357,9 +361,30 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| if s, err := provider.RequestTransfer(ctx, locked); !errors.Is(err, registrar.ErrRefused) || s.State != registrar.TransferFailed || s.Reason != "locked" { |
| t.Fatalf("scripted refusal = %+v, %v", s, err) |
| } |
| - if s, _ := provider.TransferStatus(ctx, "locked.example"); s.State != registrar.TransferNone { |
| + if s, _ := provider.TransferStatus(ctx, "locked.example", ""); s.State != registrar.TransferNone { |
| t.Fatalf("refusal left %+v", s) |
| } |
| + // A retry after a failed transfer is a new record; the old one stays |
| + // readable by its ref, the newest answers without one, and a ref of |
| + // neither is none. |
| + clock = clock.Add(time.Hour) |
| + retry := transferRequest() |
| + retry.Domain = "other.example" |
| + first, _ := provider.TransferStatus(ctx, "other.example", "") |
| + again, err := provider.RequestTransfer(ctx, retry) |
| + if err != nil || again.Ref == "" || again.Ref == first.Ref || !again.Created.After(first.Created) { |
| + t.Fatalf("retry record = %+v, %v (first %+v)", again, err, first) |
| + } |
| + if s, _ := provider.TransferStatus(ctx, "other.example", ""); s.Ref != again.Ref || s.State != registrar.TransferPending { |
| + t.Fatalf("newest = %+v", s) |
| + } |
| + if s, _ := provider.TransferStatus(ctx, "other.example", first.Ref); s.Ref != first.Ref || s.State != registrar.TransferFailed { |
| + t.Fatalf("earlier by ref = %+v", s) |
| + } |
| + if s, _ := provider.TransferStatus(ctx, "other.example", "no-such-record"); s.State != registrar.TransferNone { |
| + t.Fatalf("unknown ref = %+v", s) |
| + } |
| + |
| if strings.Contains(fmt.Sprintf("%v %+v %#v", f, f, f), "gX38") { |
| t.Fatal("fake prints the recorded auth code") |
| } |
| @@ -380,7 +405,7 @@ func TestFakeTransferLifecycle(t *testing.T) { |
| if applies { |
| want = registrar.TransferPending |
| } |
| - if s, err := f.TransferStatus(ctx, "shop.example"); err != nil || s.State != want { |
| + if s, err := f.TransferStatus(ctx, "shop.example", ""); err != nil || s.State != want { |
| t.Fatalf("status after lost response = %+v, %v; want %s", s, err, want) |
| } |
| wantCalls := []string{"request-transfer:shop.example", "transfer-status:shop.example"} |
diff --git a/internal/registrar/registrartest/fake.go b/internal/registrar/registrartest/fake.go| index 7e29f39a0..760462e94 100644 |
| --- a/internal/registrar/registrartest/fake.go |
| +++ b/internal/registrar/registrartest/fake.go |
| @@ -20,12 +20,20 @@ type Fake struct { |
| // Transfers, scripted: see RequestTransfer and Advance. |
| TransferChecks map[string]registrar.TransferCheck |
| - Transfers map[string]registrar.TransferStatus |
| + // Transfers is each domain's newest transfer record (or, before a |
| + // request, its scripted outcome). Earlier holds records from before it, |
| + // such as an earlier failed transfer of the same domain: a read by ref |
| + // finds them, a read without one answers the newest by Created. |
| + Transfers map[string]registrar.TransferStatus |
| + Earlier map[string][]registrar.TransferStatus |
| + // Now is the registrar's clock for new records' Created; nil: time.Now. |
| + Now func() time.Time |
| RequestErr error // one-shot, for the next RequestTransfer |
| RequestApplies bool // with RequestErr: the request still took effect |
| LastTransfer registrar.TransferRequest // with the auth code, for tests; prints redacted |
| mu sync.Mutex |
| + nextRecord int |
| registered map[string]registrar.Registered |
| contacts map[string]registrar.Contact |
| nextContact int |
| @@ -155,9 +163,15 @@ func (f *Fake) RequestTransfer(ctx context.Context, r registrar.TransferRequest) |
| return refused, fmt.Errorf("%w: incomplete transfer", registrar.ErrRefused) |
| } |
| outcome, scripted := f.Transfers[r.Domain] |
| - if !scripted || outcome.State == "" || outcome.State == registrar.TransferNone { |
| + if !scripted || outcome.State == "" || outcome.State == registrar.TransferNone || outcome.Ref != "" { |
| + // Unscripted, or the newest is a real earlier record: accepted. |
| outcome = registrar.TransferStatus{State: registrar.TransferPending} |
| } |
| + if scripted && outcome.Ref == "" && f.Transfers[r.Domain].Ref == "" { |
| + // A scripted outcome is not a record of its own. |
| + delete(f.Transfers, r.Domain) |
| + } |
| + outcome = f.newRecord(r.Domain, outcome) |
| if f.RequestErr != nil { |
| err := f.RequestErr |
| f.RequestErr = nil |
| @@ -170,37 +184,80 @@ func (f *Fake) RequestTransfer(ctx context.Context, r registrar.TransferRequest) |
| return registrar.TransferStatus{}, err |
| } |
| if outcome.State == registrar.TransferFailed { |
| - delete(f.Transfers, r.Domain) |
| + // Refused: nothing pending, no record kept. |
| return cloneTransfer(outcome), fmt.Errorf("%w: transfer refused", registrar.ErrRefused) |
| } |
| f.setTransfer(r.Domain, outcome) |
| return cloneTransfer(outcome), nil |
| } |
| -// TransferStatus reads Transfers; a domain with no entry is TransferNone. |
| -func (f *Fake) TransferStatus(ctx context.Context, domain string) (registrar.TransferStatus, error) { |
| +// TransferStatus reads the record named ref among Transfers and Earlier, |
| +// or with no ref the newest of them (Transfers, unless an Earlier record |
| +// was created after it); none is TransferNone. |
| +func (f *Fake) TransferStatus(ctx context.Context, domain, ref string) (registrar.TransferStatus, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.Calls = append(f.Calls, "transfer-status:"+domain) |
| - s, ok := f.Transfers[domain] |
| - if !ok { |
| + var records []registrar.TransferStatus |
| + if cur, ok := f.Transfers[domain]; ok { |
| + records = append(records, cur) |
| + } |
| + records = append(records, f.Earlier[domain]...) |
| + var found *registrar.TransferStatus |
| + for i := range records { |
| + r := &records[i] |
| + if ref != "" { |
| + if r.Ref == ref { |
| + found = r |
| + } |
| + } else if found == nil || r.Created.After(found.Created) { |
| + found = r |
| + } |
| + } |
| + if found == nil { |
| return registrar.TransferStatus{State: registrar.TransferNone}, nil |
| } |
| - return cloneTransfer(s), nil |
| + return cloneTransfer(*found), nil |
| } |
| -// Advance moves one transfer to s, as the registrar would. A completed |
| -// transfer puts the domain in the account (Domains, so Lookup finds it). |
| +// Advance moves the domain's newest transfer to s, as the registrar would, |
| +// keeping that record's Ref and Created (a domain with none gets a new |
| +// record). A completed transfer puts the domain in the account (Domains, so |
| +// Lookup finds it). |
| func (f *Fake) Advance(domain string, s registrar.TransferStatus) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| + if cur, ok := f.Transfers[domain]; ok && s.Ref == "" { |
| + s.Ref, s.Created = cur.Ref, cur.Created |
| + } |
| f.setTransfer(domain, s) |
| } |
| +// newRecord is a new transfer record of domain: the previous newest, if it |
| +// was a real record (it has a Ref), moves to Earlier. |
| +func (f *Fake) newRecord(domain string, s registrar.TransferStatus) registrar.TransferStatus { |
| + if cur, ok := f.Transfers[domain]; ok && cur.Ref != "" { |
| + if f.Earlier == nil { |
| + f.Earlier = make(map[string][]registrar.TransferStatus) |
| + } |
| + f.Earlier[domain] = append(f.Earlier[domain], cloneTransfer(cur)) |
| + } |
| + f.nextRecord++ |
| + s.Ref = fmt.Sprintf("transfer-%d", f.nextRecord) |
| + s.Created = time.Now().UTC() |
| + if f.Now != nil { |
| + s.Created = f.Now().UTC() |
| + } |
| + return s |
| +} |
| + |
| func (f *Fake) setTransfer(domain string, s registrar.TransferStatus) { |
| if f.Transfers == nil { |
| f.Transfers = make(map[string]registrar.TransferStatus) |
| } |
| + if s.Ref == "" { |
| + s = f.newRecord(domain, s) |
| + } |
| f.Transfers[domain] = cloneTransfer(s) |
| if s.State == registrar.TransferCompleted { |
| if f.Domains == nil { |