carlos / platform Public

registrar: transfer check, request and status (Openprovider /v1)

The Registrar seam gains CheckTransfer, RequestTransfer and
TransferStatus with provider-neutral types. TransferRequest redacts its
auth code in String, GoString, every fmt verb, slog and JSON.

The fake scripts checks and transfer outcomes, with Advance, a one-shot
RequestErr and RequestApplies for lost responses.

Openprovider: POST /v1/domains/transfer with period 1, auto-renew off,
privacy on, the owner handle in every role and the request's
nameservers; empty nameservers are refused before any HTTP call.
Documented refusal codes are definite with a neutral reason; anything
else after send is indeterminate. The status read maps REQ/PEN, ACT,
FAI/REJ and "not in the account" without reading every non-ACT as
unknown; Lookup is unchanged. The check is best effort: domain check
with WHOIS for EPP lock statuses, and the transfer price. Provider error
text is scrubbed of the auth code, escaped and case-folded forms too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9c9db49c39e86e849c46bd01d3459566199fe3c3 parent 40be4a7
11 files changed, +1,306 −32
  • internal/registrar/openprovider/client.go +277 −28
  • internal/registrar/openprovider/client_test.go +405 −0
  • internal/registrar/openprovider/testdata/README.md +7 −0
  • internal/registrar/openprovider/testdata/transfer_check.json +32 −0
  • internal/registrar/openprovider/testdata/transfer_price.json +42 −0
  • internal/registrar/openprovider/testdata/transfer_refused.json +5 −0
  • internal/registrar/openprovider/testdata/transfer_request.json +11 −0
  • internal/registrar/openprovider/testdata/transfer_status.json +198 −0
  • internal/registrar/registrar.go +74 −0
  • internal/registrar/registrar_test.go +146 −0
  • internal/registrar/registrartest/fake.go +109 −4
diff --git a/internal/registrar/openprovider/client.go b/internal/registrar/openprovider/client.go
index e3d419bc4..34f39532f 100644
--- a/internal/registrar/openprovider/client.go
+++ b/internal/registrar/openprovider/client.go
@@ -6,10 +6,13 @@ import (
"encoding/json"
"errors"
"fmt"
+ "html"
"io"
"math/big"
"net/http"
"net/url"
+ "regexp"
+ "slices"
"strconv"
"strings"
"sync"
@@ -266,28 +269,38 @@ func (c *Client) Register(ctx context.Context, in registrar.Registration) (regis
}
func (c *Client) Lookup(ctx context.Context, domain string) (registrar.Registered, bool, error) {
+ record, found, err := c.listDomain(ctx, domain)
+ if err != nil || !found {
+ return registrar.Registered{}, false, err
+ }
+ result, err := record.registered()
+ return result, err == nil, err
+}
+
+// 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) {
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 registrar.Registered{}, false, err
+ return domainRecord{}, false, err
}
if response.Results == nil {
- return registrar.Registered{}, false, errors.New("openprovider: missing domain results")
+ return domainRecord{}, false, errors.New("openprovider: missing domain results")
}
records := *response.Results
if len(records) == 0 && response.Total == 0 {
- return registrar.Registered{}, false, nil
+ return domainRecord{}, false, nil
}
if len(records) != 1 || records[0].Domain.Name+"."+records[0].Domain.Extension != domain {
- return registrar.Registered{}, false, errors.New("openprovider: unexpected domain results")
+ return domainRecord{}, false, errors.New("openprovider: unexpected domain results")
}
if records[0].Deleted {
- return registrar.Registered{}, false, nil
+ return domainRecord{}, false, nil
}
- result, err := records[0].registered()
- return result, err == nil, err
+ return records[0], true, nil
}
func (r domainRecord) registered() (registrar.Registered, error) {
@@ -393,7 +406,9 @@ func (c *Client) bearer(ctx context.Context, invalid string) (string, error) {
return c.token, nil
}
-func (c *Client) call(ctx context.Context, method, path string, input, output any) error {
+// call sends one request. secrets are redacted from provider messages along
+// with the account credentials.
+func (c *Client) call(ctx context.Context, method, path string, input, output any, secrets ...string) error {
var payload []byte
if input != nil {
var err error
@@ -407,7 +422,7 @@ func (c *Client) call(ctx context.Context, method, path string, input, output an
return err
}
for attempt := 0; attempt < 2; attempt++ {
- data, status, err := c.send(ctx, method, path, payload, token)
+ data, status, err := c.send(ctx, method, path, payload, token, secrets...)
if status == http.StatusUnauthorized && attempt == 0 {
token, err = c.bearer(ctx, token)
if err != nil {
@@ -426,14 +441,65 @@ func (c *Client) call(ctx context.Context, method, path string, input, output an
return errors.New("openprovider: authentication failed")
}
+// sends reports whether a request can create something at the registrar.
+// Once one is sent, an answer that is not a documented refusal is
+// indeterminate.
+func sends(method, path string) bool {
+ return method == http.MethodPost && (path == "/domains" || path == "/domains/transfer")
+}
+
func responseError(method, path, message string) error {
- if method == http.MethodPost && path == "/domains" {
+ if sends(method, path) {
return fmt.Errorf("%w: openprovider: %s", registrar.ErrIndeterminate, message)
}
return fmt.Errorf("openprovider: %s", message)
}
-func (c *Client) send(ctx context.Context, method, path string, payload []byte, token string) (json.RawMessage, int, error) {
+// refusalKind classifies a provider error answer (HTTP 4xx, or a non-zero
+// code in a 2xx answer).
+func refusalKind(method, path string, status, code int) error {
+ if code == 309 || code == 19010 {
+ return errors.Join(registrar.ErrRefused, registrar.ErrSetup)
+ }
+ if method == http.MethodPost && path == "/domains/transfer" {
+ switch {
+ case transferRefusals[code] != "":
+ return registrar.ErrRefused
+ case code == 326 || code == 514:
+ // "Already in your account" and "already being transferred" can
+ // describe our own transfer: the status read decides.
+ return registrar.ErrIndeterminate
+ case status >= 400:
+ return registrar.ErrRefused
+ }
+ return registrar.ErrIndeterminate
+ }
+ kind := registrar.ErrRefused
+ if status < 400 && method == http.MethodPost && path == "/domains" && code != 19006 && code != 19007 {
+ // A provider error inside HTTP 200 is not a definite refusal unless
+ // its code documents that nothing was registered.
+ kind = registrar.ErrIndeterminate
+ }
+ if code == 311 {
+ kind = registrar.ErrUnavailable
+ }
+ return kind
+}
+
+// redact removes a secret from provider text in every case and in the
+// escaped forms a provider might echo it in.
+func redact(message, secret string) string {
+ if secret == "" {
+ return message
+ }
+ quoted, _ := json.Marshal(secret)
+ for _, form := range []string{secret, url.QueryEscape(secret), url.PathEscape(secret), html.EscapeString(secret), string(quoted[1 : len(quoted)-1])} {
+ message = regexp.MustCompile("(?i)"+regexp.QuoteMeta(form)).ReplaceAllLiteralString(message, "[redacted]")
+ }
+ return message
+}
+
+func (c *Client) send(ctx context.Context, method, path string, payload []byte, token string, secrets ...string) (json.RawMessage, int, error) {
req, err := http.NewRequestWithContext(ctx, method, c.endpoint+path, bytes.NewReader(payload))
if err != nil {
return nil, 0, errors.New("openprovider: invalid request")
@@ -460,31 +526,214 @@ func (c *Client) send(ctx context.Context, method, path string, payload []byte,
code = *answer.Code
}
message := answer.Description
- for _, secret := range []string{c.username, c.password, token} {
- if secret != "" {
- message = strings.ReplaceAll(message, secret, "[redacted]")
- }
+ for _, secret := range append([]string{c.username, c.password, token}, secrets...) {
+ message = redact(message, secret)
}
if status >= 500 || status < 200 || (status >= 300 && status < 400) {
return nil, status, &providerError{kind: responseError(method, path, fmt.Sprintf("HTTP %d", status)), status: status, code: code, message: message}
}
if status >= 400 || (decodeErr == nil && answer.Code != nil && code != 0) {
- kind := registrar.ErrRefused
- if status < 400 && method == http.MethodPost && path == "/domains" && code != 19006 && code != 19007 {
- // A provider error inside HTTP 200 is not a definite refusal unless
- // its code documents that nothing was registered.
- kind = registrar.ErrIndeterminate
- }
- if code == 311 {
- kind = registrar.ErrUnavailable
- }
- if code == 309 || code == 19010 {
- kind = errors.Join(registrar.ErrRefused, registrar.ErrSetup)
- }
- return nil, status, &providerError{kind: kind, status: status, code: code, message: message}
+ return nil, status, &providerError{kind: refusalKind(method, path, status, code), status: status, code: code, message: message}
}
if readErr != nil || len(raw) > 1<<20 || decodeErr != nil || answer.Code == nil || len(answer.Data) == 0 || string(answer.Data) == "null" {
return nil, status, responseError(method, path, "invalid response")
}
return answer.Data, status, nil
}
+
+// transferRefusals are the documented codes (API error catalogue) that
+// refuse a transfer request with nothing pending, and their neutral reasons.
+var transferRefusals = map[int]string{
+ 317: "auth_code", 318: "auth_code", 352: "auth_code", 358: "auth_code",
+ 328: "locked", 369: "locked",
+ 19004: "recent",
+ 313: "not_registered",
+ 322: "unsupported", 547: "unsupported",
+ 327: "expired", 542: "expired",
+ 315: "rejected", 316: "rejected", 19006: "rejected", 19007: "rejected",
+}
+
+// CheckTransfer is best effort. /v1 has no transfer check: the domain
+// check says whether the name is registered and returns its WHOIS text, and
+// the price list gives the transfer price. A lock the WHOIS text does not
+// show is found by the registrar after submit.
+func (c *Client) CheckTransfer(ctx context.Context, domain string) (registrar.TransferCheck, error) {
+ result := registrar.TransferCheck{Domain: domain}
+ d, err := splitDomain(domain)
+ if err != nil {
+ return result, err
+ }
+ request := struct {
+ Domains []domainName `json:"domains"`
+ WithWhois bool `json:"with_whois"`
+ }{[]domainName{d}, true}
+ var response struct {
+ Results []struct {
+ Domain string `json:"domain"`
+ Status string `json:"status"`
+ Premium bool `json:"is_premium"`
+ Whois string `json:"whois"`
+ } `json:"results"`
+ }
+ if err := c.call(ctx, http.MethodPost, "/domains/check", request, &response); err != nil {
+ return result, err
+ }
+ if len(response.Results) != 1 || response.Results[0].Domain != domain || response.Results[0].Status == "" {
+ return result, errors.New("openprovider: invalid availability response")
+ }
+ checked := response.Results[0]
+ result.Premium = checked.Premium
+ switch checked.Status {
+ case "free":
+ result.Reason = "not_registered"
+ return result, nil
+ case "reserved":
+ result.Reason = "unsupported"
+ return result, nil
+ }
+ var price struct {
+ Premium bool `json:"is_premium"`
+ Price struct {
+ Reseller struct {
+ Currency string `json:"currency"`
+ Price json.Number `json:"price"`
+ } `json:"reseller"`
+ } `json:"price"`
+ }
+ query := url.Values{"domain.name": {d.Name}, "domain.extension": {d.Extension}, "operation": {"transfer"}}
+ if err := c.call(ctx, http.MethodGet, "/domains/prices?"+query.Encode(), nil, &price); err != nil {
+ var refusal *providerError
+ if errors.As(err, &refusal) && refusal.status < 500 && refusal.code == 322 {
+ result.Reason = "unsupported"
+ return result, nil
+ }
+ return result, err
+ }
+ result.Premium = result.Premium || price.Premium
+ cost, err := money(price.Price.Reseller.Currency, price.Price.Reseller.Price)
+ if err != nil {
+ return result, err
+ }
+ result.Cost = cost
+ result.Reason = whoisTransferBlock(checked.Whois)
+ result.Transferable = result.Reason == ""
+ return result, nil
+}
+
+// whoisTransferBlock reads EPP statuses from WHOIS text, best effort: only
+// lines whose label names a status count, and text it cannot read blocks
+// nothing.
+func whoisTransferBlock(text string) string {
+ expired := false
+ for _, line := range strings.Split(text, "\n") {
+ label, value, ok := strings.Cut(line, ":")
+ if !ok || !strings.Contains(strings.ToLower(label), "status") {
+ continue
+ }
+ for _, word := range strings.Fields(strings.ToLower(value)) {
+ switch strings.Trim(word, ",;") {
+ case "clienttransferprohibited", "servertransferprohibited":
+ return "locked"
+ case "redemptionperiod", "pendingdelete", "pendingrestore":
+ expired = true
+ }
+ }
+ }
+ if expired {
+ return "expired"
+ }
+ return ""
+}
+
+// RequestTransfer sends the transfer once, keeping the domain's own
+// nameservers (registration only), with auto-renew off and WHOIS privacy
+// on. Openprovider has no idempotency key: in.Key is deliberately unused,
+// and after an indeterminate answer the caller settles by TransferStatus.
+func (c *Client) RequestTransfer(ctx context.Context, in registrar.TransferRequest) (registrar.TransferStatus, error) {
+ refused := registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}
+ d, err := splitDomain(in.Domain)
+ if err != nil {
+ return refused, err
+ }
+ blank := func(s string) bool { return strings.TrimSpace(s) == "" }
+ if blank(in.AuthCode) || blank(in.OwnerHandle) || len(in.Nameservers) == 0 || slices.ContainsFunc(in.Nameservers, blank) {
+ return refused, fmt.Errorf("%w: incomplete transfer", registrar.ErrRefused)
+ }
+ request := struct {
+ Domain domainName `json:"domain"`
+ Period int `json:"period"`
+ AuthCode string `json:"auth_code"`
+ Autorenew string `json:"autorenew"`
+ Owner string `json:"owner_handle"`
+ Admin string `json:"admin_handle"`
+ Tech string `json:"tech_handle"`
+ Billing string `json:"billing_handle"`
+ Nameservers []nameserver `json:"name_servers"`
+ Private bool `json:"is_private_whois_enabled"`
+ }{Domain: d, Period: 1, AuthCode: in.AuthCode, Autorenew: "off", Owner: in.OwnerHandle, Admin: in.OwnerHandle, Tech: in.OwnerHandle, Billing: in.OwnerHandle, Private: true}
+ for _, name := range in.Nameservers {
+ request.Nameservers = append(request.Nameservers, nameserver{Name: name})
+ }
+ var response struct {
+ ID int64 `json:"id"`
+ Status string `json:"status"`
+ Expires string `json:"expiration_date"`
+ }
+ if err := c.call(ctx, http.MethodPost, "/domains/transfer", request, &response, in.AuthCode); err != nil {
+ if !errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrIndeterminate) {
+ return registrar.TransferStatus{}, err
+ }
+ var refusal *providerError
+ if errors.As(err, &refusal) && transferRefusals[refusal.code] != "" {
+ refused.Reason = transferRefusals[refusal.code]
+ }
+ return refused, err
+ }
+ switch response.Status {
+ case "REQ":
+ return registrar.TransferStatus{State: registrar.TransferPending}, 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.TransferPending}, 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)
+ if err != nil {
+ var answer *providerError
+ if errors.As(err, &answer) && answer.status < 500 && (answer.code == 320 || answer.code == 500) {
+ // 320 "not in your account", 500 "not registered with Openprovider".
+ return registrar.TransferStatus{State: registrar.TransferNone}, nil
+ }
+ return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: transfer status unreadable: %s", registrar.ErrIndeterminate, err.Error())
+ }
+ if !found {
+ return registrar.TransferStatus{State: registrar.TransferNone}, nil
+ }
+ switch record.Status {
+ case "REQ", "PEN":
+ return registrar.TransferStatus{State: registrar.TransferPending}, nil
+ case "FAI":
+ return registrar.TransferStatus{State: registrar.TransferFailed}, nil
+ case "REJ":
+ return registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}, nil
+ case "ACT":
+ registered, err := record.registered()
+ if err != nil {
+ return registrar.TransferStatus{}, err
+ }
+ return registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registered}, nil
+ }
+ return registrar.TransferStatus{}, fmt.Errorf("%w: openprovider: unrecognised domain status", registrar.ErrIndeterminate)
+}
diff --git a/internal/registrar/openprovider/client_test.go b/internal/registrar/openprovider/client_test.go
index ee84296ed..d1c595749 100644
--- a/internal/registrar/openprovider/client_test.go
+++ b/internal/registrar/openprovider/client_test.go
@@ -5,8 +5,11 @@ import (
"encoding/json"
"errors"
"fmt"
+ "html"
+ "io"
"net/http"
"net/http/httptest"
+ "net/url"
"os"
"reflect"
"strings"
@@ -563,3 +566,405 @@ func TestRegistryErrorMessagesAndSetupCodes(t *testing.T) {
}
}
}
+
+// authCode is the request example's code from the transfer guide; it has
+// characters that change under URL and HTML escaping.
+const authCode = "gX38tslFG2#%F%%1"
+
+func transferRequest() registrar.TransferRequest {
+ return registrar.TransferRequest{Domain: "shop.example", AuthCode: authCode, OwnerHandle: "XX123456-XX", Key: "purchase-id", Nameservers: []string{"ns1.dns.example", "ns2.dns.example"}}
+}
+
+func TestRequestTransferSendsAutorenewOffNameserversHandles(t *testing.T) {
+ req := transferRequest()
+ var calls atomic.Int32
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ b := body(t, r)
+ if r.Method != "POST" || r.URL.Path != "/v1/domains/transfer" || r.URL.RawQuery != "" {
+ t.Errorf("transfer: %s %s", r.Method, r.URL)
+ }
+ if b["auth_code"] != authCode || b["autorenew"] != "off" || b["period"] != float64(1) || b["is_private_whois_enabled"] != true {
+ t.Errorf("auth_code/autorenew/period/privacy: %v %v %v", b["autorenew"], b["period"], b["is_private_whois_enabled"])
+ }
+ if !reflect.DeepEqual(b["domain"], map[string]any{"name": "shop", "extension": "example"}) {
+ t.Errorf("domain=%v", b["domain"])
+ }
+ for _, k := range []string{"owner_handle", "admin_handle", "tech_handle", "billing_handle"} {
+ if b[k] != req.OwnerHandle {
+ t.Errorf("%s=%v", k, b[k])
+ }
+ }
+ want := []any{map[string]any{"name": "ns1.dns.example"}, map[string]any{"name": "ns2.dns.example"}}
+ if !reflect.DeepEqual(b["name_servers"], want) {
+ t.Errorf("nameservers=%v", b["name_servers"])
+ }
+ // Registration only: nothing may swap the domain's nameservers for a
+ // provider group, template or the registry's copy.
+ for _, k := range []string{"ns_group", "ns_template_id", "ns_template_name", "import_nameservers_from_registry", "import_contacts_from_registry", "is_dnssec_enabled", "dnssec_keys"} {
+ if _, ok := b[k]; ok {
+ t.Errorf("sent %s=%v", k, b[k])
+ }
+ }
+ if r.Header.Get("Idempotency-Key") != "" || strings.Contains(fmt.Sprint(b), req.Key) {
+ t.Error("invented provider idempotency")
+ }
+ reply(t, w, "transfer_request")
+ }, time.Second)
+ got, err := c.RequestTransfer(context.Background(), req)
+ if err != nil || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferPending}) || calls.Load() != 1 {
+ t.Fatalf("RequestTransfer=%+v, %v, calls=%d", got, err, calls.Load())
+ }
+}
+
+func TestRequestTransferReplyStates(t *testing.T) {
+ expires := time.Date(2020, 3, 31, 23, 59, 59, 0, time.UTC)
+ for _, tc := range []struct {
+ name, data string
+ want registrar.TransferState
+ wantErr error
+ }{
+ {"requested", `{"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},
+ {"unknown-status", `{"status":"PRE"}`, "", registrar.ErrIndeterminate},
+ {"empty", `{}`, "", registrar.ErrIndeterminate},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"code":0,"data":%s,"desc":""}`, tc.data)
+ }, time.Second)
+ got, err := c.RequestTransfer(context.Background(), transferRequest())
+ if !errors.Is(err, tc.wantErr) || (tc.wantErr == nil && err != nil) || got.State != tc.want {
+ t.Fatalf("RequestTransfer=%+v, %v", got, err)
+ }
+ 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) {
+ t.Fatalf("Registered=%+v", r)
+ }
+ }
+ })
+ }
+}
+
+func TestRequestTransferRefusesEmptyNameservers(t *testing.T) {
+ var calls atomic.Int32
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }))
+ defer s.Close()
+ c, err := openprovider.New(openprovider.Config{BaseURL: s.URL, Username: "test-user", Password: password})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, change := range []func(*registrar.TransferRequest){
+ func(r *registrar.TransferRequest) { r.Nameservers = nil },
+ func(r *registrar.TransferRequest) { r.Nameservers = []string{} },
+ func(r *registrar.TransferRequest) { r.Nameservers = []string{"ns1.dns.example", " "} },
+ func(r *registrar.TransferRequest) { r.AuthCode = "" },
+ func(r *registrar.TransferRequest) { r.OwnerHandle = "" },
+ func(r *registrar.TransferRequest) { r.Domain = "example" },
+ } {
+ req := transferRequest()
+ change(&req)
+ if _, err := c.RequestTransfer(context.Background(), req); !errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrIndeterminate) {
+ t.Errorf("%v: error=%v, want ErrRefused", req, err)
+ }
+ }
+ if calls.Load() != 0 {
+ t.Fatalf("refused request made %d HTTP calls", calls.Load())
+ }
+}
+
+func TestRequestTransferTimeoutIsIndeterminate(t *testing.T) {
+ var calls atomic.Int32
+ release := make(chan struct{})
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ _, _ = io.Copy(io.Discard, r.Body) // so the server notices the client hang up
+ select { // the client gives up first
+ case <-r.Context().Done():
+ case <-release:
+ }
+ }, 50*time.Millisecond)
+ t.Cleanup(func() { close(release) }) // runs before the server closes
+ got, err := c.RequestTransfer(context.Background(), transferRequest())
+ if !errors.Is(err, registrar.ErrIndeterminate) || errors.Is(err, registrar.ErrRefused) || got.State != "" || calls.Load() != 1 {
+ t.Fatalf("status=%+v error=%v calls=%d", got, err, calls.Load())
+ }
+ for _, tc := range []struct {
+ name string
+ status int
+ response string
+ }{
+ {"server", 503, `{"code":358,"desc":"Provided authorization code is incorrect"}`},
+ {"redirect", 307, ``},
+ {"malformed", 200, `{"code":0,"data":`},
+ {"unknown-code-in-200", 200, `{"code":199,"desc":"An unknown error has occurred"}`},
+ {"already-being-transferred", 400, `{"code":514,"desc":"The domain is already being transferred"}`},
+ {"already-in-account", 400, `{"code":326,"desc":"This domain is already in your account"}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var calls atomic.Int32
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if tc.status == 307 {
+ http.Redirect(w, r, "/v1/replayed", tc.status)
+ return
+ }
+ w.WriteHeader(tc.status)
+ fmt.Fprint(w, tc.response)
+ }, time.Second)
+ if _, err := c.RequestTransfer(context.Background(), transferRequest()); !errors.Is(err, registrar.ErrIndeterminate) || errors.Is(err, registrar.ErrRefused) || calls.Load() != 1 {
+ t.Fatalf("error=%v calls=%d", err, calls.Load())
+ }
+ })
+ }
+}
+
+func TestRequestTransferBadAuthCodeIsRefused(t *testing.T) {
+ // Codes from the API error catalogue: 317 empty, 318 incorrect or
+ // missing, 352 validity expired, 358 provided code incorrect.
+ for _, code := range []int{317, 318, 352, 358} {
+ for _, status := range []int{200, 400} {
+ t.Run(fmt.Sprintf("%d/%d", code, status), func(t *testing.T) {
+ var calls atomic.Int32
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(status)
+ raw := fixture(t, "transfer_refused")
+ _, _ = w.Write([]byte(strings.Replace(string(raw), `"code": 358`, fmt.Sprintf(`"code": %d`, code), 1)))
+ }, time.Second)
+ got, err := c.RequestTransfer(context.Background(), transferRequest())
+ if !errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrIndeterminate) || calls.Load() != 1 {
+ t.Fatalf("error=%v calls=%d", err, calls.Load())
+ }
+ if !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferFailed, Reason: "auth_code"}) {
+ t.Fatalf("status=%+v", got)
+ }
+ })
+ }
+ }
+}
+
+func TestRequestTransferRefusalReasons(t *testing.T) {
+ for _, tc := range []struct {
+ code int
+ reason string
+ setup bool
+ }{
+ {328, "locked", false}, {369, "locked", false}, {19004, "recent", false},
+ {313, "not_registered", false}, {322, "unsupported", false}, {547, "unsupported", false},
+ {327, "expired", false}, {542, "expired", false},
+ {19006, "rejected", false}, {19007, "rejected", false},
+ {309, "rejected", true}, {19010, "rejected", true},
+ } {
+ t.Run(fmt.Sprint(tc.code), func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"code":%d,"desc":"refused"}`, tc.code)
+ }, time.Second)
+ got, err := c.RequestTransfer(context.Background(), transferRequest())
+ if !errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrSetup) != tc.setup {
+ t.Fatalf("error=%v", err)
+ }
+ if !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferFailed, Reason: tc.reason}) {
+ t.Fatalf("status=%+v", got)
+ }
+ })
+ }
+ // An undocumented code in a 4xx answer is refused, as for registrations,
+ // with no reason the adapter can name.
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(422)
+ fmt.Fprint(w, `{"code":112,"desc":"address number required"}`)
+ }, time.Second)
+ if got, err := c.RequestTransfer(context.Background(), transferRequest()); !errors.Is(err, registrar.ErrRefused) || !reflect.DeepEqual(got, registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}) {
+ t.Fatalf("status=%+v error=%v", got, err)
+ }
+}
+
+func TestTransferStatusMapsPendingCompletedFailedNone(t *testing.T) {
+ expires := time.Date(2014, 7, 4, 17, 14, 44, 0, time.UTC)
+ 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},
+ {"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},
+ {"wrong-name", `"name": "shop"`, `"name": "other"`, registrar.TransferStatus{}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "GET" || r.URL.Path != "/v1/domains" || r.URL.Query().Get("full_name") != "shop.example" {
+ t.Errorf("status read: %s %s", r.Method, r.URL)
+ }
+ raw := string(fixture(t, "transfer_status"))
+ if tc.old != "" {
+ raw = strings.Replace(raw, tc.old, tc.new, 1)
+ }
+ fmt.Fprint(w, raw)
+ }, time.Second)
+ 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)
+ }
+ })
+ }
+ t.Run("not-in-account", func(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}) {
+ t.Fatalf("TransferStatus=%+v, %v", got, err)
+ }
+ })
+ for _, response := range []string{`{"code":0,"data":{}}`, `{"code":0,"data":`, `{"code":399,"desc":"registry"}`} {
+ t.Run("unreadable/"+response, func(t *testing.T) {
+ for _, status := range []int{200, 500} {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ fmt.Fprint(w, response)
+ }, time.Second)
+ 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)
+ }
+ }
+ })
+ }
+ // Documented "not ours" codes: 320 not in your account, 500 not
+ // registered with the provider.
+ for _, code := range []int{320, 500} {
+ t.Run(fmt.Sprint("code-", code), func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ 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}) {
+ t.Fatalf("TransferStatus=%+v, %v", got, err)
+ }
+ })
+ }
+}
+
+func TestCheckTransferParsesCostAndLock(t *testing.T) {
+ cost := registrar.Money{Currency: "eur", Minor: 899}
+ for _, tc := range []struct {
+ name, old, new string
+ want registrar.TransferCheck
+ priced bool
+ }{
+ {"locked", "", "", registrar.TransferCheck{Domain: "shop.example", Reason: "locked", Cost: cost}, true},
+ {"server-locked", "Domain Status: clientTransferProhibited", "Domain Status: serverTransferProhibited", registrar.TransferCheck{Domain: "shop.example", Reason: "locked", Cost: cost}, true},
+ {"unlocked", "Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited", "Domain Status: ok https://icann.org/epp#ok", registrar.TransferCheck{Domain: "shop.example", Transferable: true, Cost: cost}, true},
+ {"lock-named-outside-status", "Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited", "Domain Status: ok\\nRemarks: see clientTransferProhibited", registrar.TransferCheck{Domain: "shop.example", Transferable: true, Cost: cost}, true},
+ {"redemption", "clientTransferProhibited https://icann.org/epp#clientTransferProhibited", "redemptionPeriod https://icann.org/epp#redemptionPeriod", registrar.TransferCheck{Domain: "shop.example", Reason: "expired", Cost: cost}, true},
+ {"no-whois", `"whois": "Domain Name`, `"whois": "", "unused": "`, registrar.TransferCheck{Domain: "shop.example", Transferable: true, Cost: cost}, true},
+ {"premium", `"is_premium": false`, `"is_premium": true`, registrar.TransferCheck{Domain: "shop.example", Reason: "locked", Cost: cost, Premium: true}, true},
+ {"free", `"status": "active"`, `"status": "free"`, registrar.TransferCheck{Domain: "shop.example", Reason: "not_registered"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var priced atomic.Bool
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method + " " + r.URL.Path {
+ case "POST /v1/domains/check":
+ b := body(t, r)
+ if !reflect.DeepEqual(b["domains"], []any{map[string]any{"name": "shop", "extension": "example"}}) || b["with_whois"] != true {
+ t.Errorf("check body=%v", b)
+ }
+ raw := string(fixture(t, "transfer_check"))
+ if tc.old != "" {
+ raw = strings.Replace(raw, tc.old, tc.new, 1)
+ }
+ fmt.Fprint(w, raw)
+ case "GET /v1/domains/prices":
+ priced.Store(true)
+ q := r.URL.Query()
+ if q.Get("domain.name") != "shop" || q.Get("domain.extension") != "example" || q.Get("operation") != "transfer" {
+ t.Errorf("price query=%v", q)
+ }
+ reply(t, w, "transfer_price")
+ default:
+ t.Errorf("unexpected %s %s", r.Method, r.URL)
+ }
+ }, time.Second)
+ got, err := c.CheckTransfer(context.Background(), "shop.example")
+ if err != nil || got != tc.want || priced.Load() != tc.priced {
+ t.Fatalf("CheckTransfer=%+v, %v (priced %v); want %+v", got, err, priced.Load(), tc.want)
+ }
+ })
+ }
+ t.Run("premium-price", func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/domains/check" {
+ reply(t, w, "transfer_check")
+ return
+ }
+ fmt.Fprint(w, strings.Replace(string(fixture(t, "transfer_price")), `"is_premium": false`, `"is_premium": true`, 1))
+ }, time.Second)
+ if got, err := c.CheckTransfer(context.Background(), "shop.example"); err != nil || !got.Premium {
+ t.Fatalf("CheckTransfer=%+v, %v", got, err)
+ }
+ })
+ t.Run("price-unreadable", func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/domains/check" {
+ reply(t, w, "transfer_check")
+ return
+ }
+ fmt.Fprint(w, `{"code":0,"data":{"price":{}}}`)
+ }, time.Second)
+ if got, err := c.CheckTransfer(context.Background(), "shop.example"); err == nil || got.Transferable {
+ t.Fatalf("CheckTransfer=%+v, %v", got, err)
+ }
+ })
+ t.Run("unsupported-extension", func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/domains/check" {
+ reply(t, w, "transfer_check")
+ return
+ }
+ w.WriteHeader(400)
+ fmt.Fprint(w, `{"code":322,"desc":"Domains with this extension cannot be transferred"}`)
+ }, time.Second)
+ if got, err := c.CheckTransfer(context.Background(), "shop.example"); err != nil || got != (registrar.TransferCheck{Domain: "shop.example", Reason: "unsupported"}) {
+ t.Fatalf("CheckTransfer=%+v, %v", got, err)
+ }
+ })
+}
+
+func TestAuthCodeNeverInErrorText(t *testing.T) {
+ echoes := []string{authCode, strings.ToUpper(authCode), url.QueryEscape(authCode), url.PathEscape(authCode), html.EscapeString(authCode)}
+ for _, status := range []int{200, 400, 500} {
+ t.Run(fmt.Sprint(status), func(t *testing.T) {
+ c := newClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 358,
+ "desc": "Provided authorization code is incorrect: " + strings.Join(echoes, " ") + " " + password + " " + token,
+ "data": map[string]any{"auth_code": authCode},
+ })
+ }, time.Second)
+ got, err := c.RequestTransfer(context.Background(), transferRequest())
+ if err == nil {
+ t.Fatal("echoing refusal accepted")
+ }
+ text := strings.ToLower(fmt.Sprintf("%v %+v %#v %s %v", err, err, err, err.Error(), got))
+ for _, secret := range []string{"gx38tslfg2", password, token} {
+ if strings.Contains(text, secret) {
+ t.Fatalf("secret %q in error text: %s", secret, text)
+ }
+ }
+ if !strings.Contains(err.Error(), "Provided authorization code is incorrect") {
+ t.Fatalf("lost provider message: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/registrar/openprovider/testdata/README.md b/internal/registrar/openprovider/testdata/README.md
index 0ea4ed412..41e1a3258 100644
--- a/internal/registrar/openprovider/testdata/README.md
+++ b/internal/registrar/openprovider/testdata/README.md
@@ -14,6 +14,13 @@ Source: [https://developer.openprovider.com/data/swagger.spec.js](https://develo
| `lookup.json` | `domainListDomainsResponse` | First result's domain → `{name: "shop", extension: "example"}`, status `PRE` → `ACT`; total 999 → 1. |
| `balance.json` | `resellerGetResellerResponse` | None. |
| `taken.json` | `errorError` | Code 0 → 311; description → `Domain already registered or reserved`. |
+| `transfer_check.json` | `domainCheckDomainResponse` (`check-reference.json`) | Domain `example.com` → `shop.example`; `whois` → a synthetic ICANN-format WHOIS text with `Domain Status: clientTransferProhibited`. The reference does not document the `whois` text's format. |
+| `transfer_price.json` | `priceGetPriceResponse` (`GET /v1/domains/prices`) | `data.price.reseller` → EUR 8.99. |
+| `transfer_request.json` | The "Transfer a domain" response example in the `/v1` domain quickstart (the `DomainQuickstart` tag description in the same schema file) | None: status `REQ`, the example's echoed `auth_code`. |
+| `transfer_status.json` | `domainListDomainsResponse` (`lookup.json`) | Status `ACT` → `REQ`; type `NEW` → `TRANSFER`; nameservers → `ns1.dns.example`, `ns2.dns.example`; `auth_code` and `internal_auth_code` → empty. |
+| `transfer_refused.json` | `errorError` | Code 0 → 358; description → `Provided authorization code is incorrect`. |
+
+Transfer request fields and the `ACT`/`REQ`/`FAI` statuses come from the `/v1` quickstart and [https://openprovider.help/books/api-integrations/page/14-domains-api-how-to-transfer-a-domain](https://openprovider.help/books/api-integrations/page/14-domains-api-how-to-transfer-a-domain) (which documents `period`, absent from the `/v1` request schema). The transfer price's `operation=transfer` comes from [https://openprovider.help/books/api-integrations/page/3-domains-api-how-to-retrieve-domain-price](https://openprovider.help/books/api-integrations/page/3-domains-api-how-to-retrieve-domain-price), and the check's `with_whois` from [https://openprovider.help/books/api-integrations/page/2-domains-api-check-domain](https://openprovider.help/books/api-integrations/page/2-domains-api-check-domain). Transfer refusal codes (313, 317, 318, 322, 326, 327, 328, 352, 358, 369, 514, 542, 547, 19004) and the status-read codes 320 and 500 come from the error catalogue below. `PEN` and `REJ` appear only in the schema's `DomainStatisticsByStatus`.
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.
diff --git a/internal/registrar/openprovider/testdata/transfer_check.json b/internal/registrar/openprovider/testdata/transfer_check.json
new file mode 100644
index 000000000..2d826f0bc
--- /dev/null
+++ b/internal/registrar/openprovider/testdata/transfer_check.json
@@ -0,0 +1,32 @@
+{
+ "code": 0,
+ "data": {
+ "results": [
+ {
+ "claim_key": "",
+ "domain": "shop.example",
+ "is_premium": false,
+ "premium": {
+ "currency": "USD",
+ "price": {
+ "create": 0
+ }
+ },
+ "price": {
+ "product": {
+ "currency": "USD",
+ "price": 8.06
+ },
+ "reseller": {
+ "currency": "USD",
+ "price": 8.06
+ }
+ },
+ "reason": "Domain exists",
+ "status": "active",
+ "whois": "Domain Name: SHOP.EXAMPLE\nRegistry Domain ID: 1_DOMAIN_EXAMPLE\nRegistrar WHOIS Server: whois.registrar.example\nUpdated Date: 2025-11-01T00:00:00Z\nCreation Date: 2016-12-02T00:00:00Z\nRegistry Expiry Date: 2026-12-02T00:00:00Z\nRegistrar: Example Registrar\nDomain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited\nName Server: NS1.DNS.EXAMPLE\nName Server: NS2.DNS.EXAMPLE\nDNSSEC: unsigned\n"
+ }
+ ]
+ },
+ "desc": ""
+}
diff --git a/internal/registrar/openprovider/testdata/transfer_price.json b/internal/registrar/openprovider/testdata/transfer_price.json
new file mode 100644
index 000000000..212bfd955
--- /dev/null
+++ b/internal/registrar/openprovider/testdata/transfer_price.json
@@ -0,0 +1,42 @@
+{
+ "code": 0,
+ "data": {
+ "is_premium": false,
+ "is_promotion": false,
+ "membership_price": {
+ "product": {
+ "currency": "USD",
+ "price": 8.06
+ },
+ "reseller": {
+ "currency": "USD",
+ "price": 8.06
+ }
+ },
+ "price": {
+ "product": {
+ "currency": "USD",
+ "price": 8.06
+ },
+ "reseller": {
+ "currency": "EUR",
+ "price": 8.99
+ }
+ },
+ "promotion_data": {
+ "end_date": "1589932800",
+ "start_date": "1582156800"
+ },
+ "tier_price": {
+ "product": {
+ "currency": "USD",
+ "price": 8.06
+ },
+ "reseller": {
+ "currency": "USD",
+ "price": 8.06
+ }
+ }
+ },
+ "desc": ""
+}
diff --git a/internal/registrar/openprovider/testdata/transfer_refused.json b/internal/registrar/openprovider/testdata/transfer_refused.json
new file mode 100644
index 000000000..588468979
--- /dev/null
+++ b/internal/registrar/openprovider/testdata/transfer_refused.json
@@ -0,0 +1,5 @@
+{
+ "code": 358,
+ "data": "",
+ "desc": "Provided authorization code is incorrect"
+}
diff --git a/internal/registrar/openprovider/testdata/transfer_request.json b/internal/registrar/openprovider/testdata/transfer_request.json
new file mode 100644
index 000000000..648033a53
--- /dev/null
+++ b/internal/registrar/openprovider/testdata/transfer_request.json
@@ -0,0 +1,11 @@
+{
+ "code": 0,
+ "data":
+ {
+ "auth_code": "Z79sTaH",
+ "expiration_date": "2020-03-31 23:59:59",
+ "renewal_date": "2020-03-29 23:59:59",
+ "status": "REQ"
+ },
+ "desc": ""
+}
diff --git a/internal/registrar/openprovider/testdata/transfer_status.json b/internal/registrar/openprovider/testdata/transfer_status.json
new file mode 100644
index 000000000..78359c5c6
--- /dev/null
+++ b/internal/registrar/openprovider/testdata/transfer_status.json
@@ -0,0 +1,198 @@
+{
+ "code": 0,
+ "data": {
+ "results": [
+ {
+ "abuse_details": {
+ "abuse_id": 0,
+ "is_domain_held": false,
+ "message": ""
+ },
+ "active_date": "2019-01-27 0:55:17",
+ "additional_data": {
+ "abogado_acceptance": "",
+ "admin_sing_pass_id": "",
+ "ae_acceptance": "1",
+ "allocation_token": "",
+ "auth_code": "",
+ "bank_acceptance": "",
+ "company_registration_number": "XX123456789X01",
+ "consent_for_publishing": "",
+ "coop_acceptance": "1",
+ "customer_uin": "374892173498127349",
+ "customer_uin_doc_type": {
+ "description": "Singapore Personal Access ID",
+ "doc_type": "singpass"
+ },
+ "dk_acceptance": "",
+ "domain_name_variants": [
+ "xn--\u0434\u043e\u043c\u0435\u043d.cat"
+ ],
+ "eligibility_type": "",
+ "eligibility_type_relationship": "",
+ "es_annex_acceptance": "1",
+ "ftld_token": "",
+ "gay_donation_acceptance": "1",
+ "gay_rights_protection_acceptance": "1",
+ "id_number": "123456789X",
+ "id_type": "",
+ "idn_script": "SPA",
+ "iisse_acceptance": "",
+ "insurance_acceptance": "",
+ "intended_use": "generic",
+ "law_acceptance": "",
+ "legal_type": "Individual",
+ "maintainer": "",
+ "membership_id": "A",
+ "mobile_phone_number_verification": "",
+ "ngo_ong_eligibility_acceptance": "",
+ "ngo_ong_policy_acceptance": "",
+ "passport_number": "X123456",
+ "rurf_blocked_domains": "",
+ "self_service": "1",
+ "trade_auth_key": "",
+ "trademark": "1",
+ "trademark_id": "",
+ "travel_acceptance": "1",
+ "vat": "11843009X",
+ "verification_code": "",
+ "vote_acceptance": "",
+ "voto_acceptance": ""
+ },
+ "admin_handle": "XX123456-XX",
+ "api_history": [
+ {
+ "cmd": "deleteDomainRequest",
+ "created_at": "2018-09-05 13:58:55",
+ "domain_id": 12345678,
+ "in": "",
+ "out": ""
+ }
+ ],
+ "application_id": "A743C511084404F31B15757DC979A1412-ABI",
+ "application_mode": "",
+ "application_mode_expiration_date": "",
+ "application_mode_title": "",
+ "application_notice_id": "983bdc1a0000100000188801724",
+ "application_smd": "",
+ "auth_code": "",
+ "autorenew": "default",
+ "billing_handle": "XX123456-XX",
+ "can_renew": false,
+ "comments": "",
+ "comments_last_changed_at": "2018-01-30 14:37:49",
+ "creation_date": "2013-07-04 17:14:44",
+ "delete_status": "quarantine",
+ "deleted_at": "0000-00-00 00:00:00",
+ "dnssec": "unsigned",
+ "dnssec_keys": [
+ {
+ "alg": 8,
+ "flags": 257,
+ "protocol": 3,
+ "pub_key": "WSgigdu8545g96",
+ "readonly": 1
+ }
+ ],
+ "domain": {
+ "name": "shop",
+ "extension": "example"
+ },
+ "expiration_date": "2014-07-04 17:14:44",
+ "hard_quarantine_expiry_date": "",
+ "has_active_sectigo_zone": false,
+ "has_history": false,
+ "history": [
+ {
+ "contents": "Domain: test-example.tldAction: registration succeededStatus: ACTOrder date: 2018-01-30Activation date: 2018-01-30Renewal date: 2019-01-27Expiration date: 2019-01-29Comments: registration of this domain has succeeded Nameserver addresses are automatically resolved by system; Nameserver IP addresses are only saved for glue records",
+ "domain": "example.com",
+ "ip": "12.123.3.12",
+ "subject": "Sent status e-mail to admin@someemail.nl",
+ "timestamp": "2018-01-30T14:38:45+01:00",
+ "type": "I"
+ }
+ ],
+ "id": 123456789,
+ "internal_auth_code": "",
+ "is_abusive": false,
+ "is_client_hold_enabled": "no",
+ "is_deleted": false,
+ "is_dnssec_enabled": false,
+ "is_hosted_whois": false,
+ "is_lockable": false,
+ "is_locked": false,
+ "is_parked": false,
+ "is_premium": false,
+ "is_private_whois_allowed": false,
+ "is_private_whois_enabled": false,
+ "is_sectigo_dns_enabled": false,
+ "is_spamexperts_enabled": false,
+ "last_changed": "2014-04-18 7:13:05",
+ "modify_owner_allowed": false,
+ "name_servers": [
+ {
+ "ip": "",
+ "ip6": "",
+ "name": "ns1.dns.example",
+ "seq_nr": 0
+ },
+ {
+ "ip": "",
+ "ip6": "",
+ "name": "ns2.dns.example",
+ "seq_nr": 1
+ }
+ ],
+ "ns_group": "dns-openprovider",
+ "ns_template_id": 0,
+ "ns_template_name": "",
+ "nsgroup_id": 1,
+ "order_date": "2013-07-04 17:14:44",
+ "owner": {
+ "company_name": "Example company",
+ "full_name": "Test Van Person"
+ },
+ "owner_company_name": "Company Name",
+ "owner_handle": "XX123456-XX",
+ "quarantine_expiration_date": "",
+ "registry_expiration_date": "2020-01-29 0:00:00",
+ "registry_statuses": {
+ "client_hold": {
+ "is_changeable": false,
+ "value": 0
+ },
+ "client_transfer_prohibited": {
+ "is_changeable": false,
+ "value": 0
+ }
+ },
+ "renew": 2,
+ "renewal_date": "2022-01-01 0:00:00",
+ "reseller_handle": "XX123456-XX",
+ "reseller_id": 12345,
+ "restorable_until": "",
+ "scheduled_at": "",
+ "scheduled_from": "",
+ "soft_quarantine_expiry_date": "",
+ "status": "REQ",
+ "tech_handle": "XX123456-XX",
+ "trade_allowed": false,
+ "trade_auth_code_required": "no",
+ "transfer_auth_code_required": "yes",
+ "transfer_cancel_supported": false,
+ "type": "TRANSFER",
+ "unit": "y",
+ "use_domicile": false,
+ "verification_email_exp_date": "0000-00-00 00:00:00",
+ "verification_email_name": "test@example.com",
+ "verification_email_status": "not verified",
+ "verification_email_status_description": "-",
+ "whois_privacy_data": {
+ "expiration_date": "2020-04-29 17:15:19"
+ }
+ }
+ ],
+ "total": 1
+ },
+ "desc": ""
+}
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go
index d2c019d5a..bf576ccfb 100644
--- a/internal/registrar/registrar.go
+++ b/internal/registrar/registrar.go
@@ -2,8 +2,11 @@ package registrar
import (
"context"
+ "encoding/json"
"errors"
"fmt"
+ "io"
+ "log/slog"
"strings"
"time"
)
@@ -55,6 +58,77 @@ type Registrar interface {
Register(ctx context.Context, r Registration) (Registered, error)
Lookup(ctx context.Context, domain string) (Registered, bool, error) // false: not in our account
Balance(ctx context.Context) (Money, error)
+
+ // CheckTransfer is best effort: Transferable may be true for a domain
+ // the registrar later refuses (a lock or code it cannot see from here).
+ CheckTransfer(ctx context.Context, domain string) (TransferCheck, error)
+ // RequestTransfer sends the transfer once. ErrRefused is definite and
+ // nothing is pending: the status is TransferFailed with a Reason.
+ // 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)
+}
+
+type TransferCheck struct {
+ Domain string
+ Transferable bool // false: Reason says why (locked, too recent, ...)
+ Reason string // provider-neutral code: "locked", "recent", "expired", "not_registered", "unsupported", ""
+ Cost Money // the registrar's transfer cost, one year
+ Premium bool
+}
+
+// TransferRequest carries the auth code, a secret: every way it prints or
+// marshals leaves the code out. Read r.AuthCode directly where it is sent.
+type TransferRequest struct {
+ Domain, AuthCode, OwnerHandle, Key string // Key: idempotency, the purchase ID
+ Nameservers []string
+}
+
+func (r TransferRequest) String() string {
+ code := ""
+ if r.AuthCode != "" {
+ code = "[redacted]"
+ }
+ return fmt.Sprintf("registrar.TransferRequest{Domain:%q, AuthCode:%q, OwnerHandle:%q, Key:%q, Nameservers:%q}",
+ r.Domain, code, r.OwnerHandle, r.Key, r.Nameservers)
+}
+
+func (r TransferRequest) GoString() string { return r.String() }
+
+// Format covers every verb, including those (%d, %t, ...) for which fmt
+// would otherwise print the fields without String.
+func (r TransferRequest) Format(f fmt.State, verb rune) { _, _ = io.WriteString(f, r.String()) }
+
+func (r TransferRequest) LogValue() slog.Value { return slog.StringValue(r.String()) }
+
+func (r TransferRequest) MarshalJSON() ([]byte, error) {
+ redacted := r
+ if redacted.AuthCode != "" {
+ redacted.AuthCode = "[redacted]"
+ }
+ type plain TransferRequest // no methods: no recursion into MarshalJSON
+ return json.Marshal(plain(redacted))
+}
+
+type TransferState string
+
+const (
+ TransferPending TransferState = "pending" // accepted, waiting on the losing registrar or registry
+ TransferCompleted TransferState = "completed" // the domain is now in our account
+ TransferFailed TransferState = "failed" // definite; Reason says why
+ TransferNone TransferState = "none" // no transfer for this domain in our account
+)
+
+type TransferStatus struct {
+ State TransferState
+ // Provider-neutral: "auth_code", "rejected", "timeout", "locked", "".
+ // A refusal at submit can also carry a TransferCheck reason ("recent",
+ // "expired", "not_registered", "unsupported"): the same fact, found late.
+ Reason string
+ Registered Registered // set when State == TransferCompleted (expiry from the registrar)
}
var ErrUnavailable = errors.New("registrar: domain not available")
diff --git a/internal/registrar/registrar_test.go b/internal/registrar/registrar_test.go
index 27ffebadf..a79576286 100644
--- a/internal/registrar/registrar_test.go
+++ b/internal/registrar/registrar_test.go
@@ -1,12 +1,16 @@
package registrar_test
import (
+ "bytes"
"context"
"encoding/json"
"errors"
+ "fmt"
+ "log/slog"
"reflect"
"strings"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/registrar"
"github.com/carlosframework/platform/internal/registrar/registrartest"
@@ -244,3 +248,145 @@ func TestContactJSONSnakeCase(t *testing.T) {
t.Errorf("wire %s", raw)
}
}
+
+const transferAuthCode = "gX38tslFG2#%F%%1"
+
+func transferRequest() registrar.TransferRequest {
+ return registrar.TransferRequest{
+ Domain: "shop.example", AuthCode: transferAuthCode, OwnerHandle: "contact-1", Key: "purchase-1",
+ Nameservers: []string{"ns1.dns.example", "ns2.dns.example"},
+ }
+}
+
+func TestTransferRequestStringRedactsAuthCode(t *testing.T) {
+ r := transferRequest()
+ for _, got := range []string{
+ fmt.Sprintf("%v %#v %+v", r, r, r),
+ fmt.Sprintf("%s %q %x %d", r, r, r, r),
+ fmt.Sprintf("%v %+v %#v", &r, []registrar.TransferRequest{r}, []registrar.TransferRequest{r}),
+ fmt.Sprintf("%+v %#v", struct{ R registrar.TransferRequest }{r}, struct{ R registrar.TransferRequest }{r}),
+ r.String() + r.GoString(),
+ } {
+ if strings.Contains(got, transferAuthCode) || strings.Contains(got, "gX38") {
+ t.Fatalf("auth code in %q", got)
+ }
+ }
+ if !strings.Contains(r.String(), "shop.example") || !strings.Contains(r.String(), "[redacted]") || r.String() != r.GoString() {
+ t.Fatalf("String=%q GoString=%q", r.String(), r.GoString())
+ }
+ var logs bytes.Buffer
+ slog.New(slog.NewJSONHandler(&logs, nil)).Info("transfer", "request", r)
+ slog.New(slog.NewTextHandler(&logs, nil)).Info("transfer", "request", r)
+ if raw, _ := json.Marshal(r); strings.Contains(string(raw), "gX38") || strings.Contains(logs.String(), "gX38") {
+ t.Fatalf("auth code in JSON or logs: %s %s", raw, logs.String())
+ }
+ if (registrar.TransferRequest{}).String() == r.String() {
+ t.Fatal("empty and set auth codes print the same; redaction hides presence")
+ }
+}
+
+func TestFakeTransferLifecycle(t *testing.T) {
+ ctx := context.Background()
+ f := registrartest.New()
+ var provider registrar.Registrar = f
+ check := registrar.TransferCheck{Transferable: true, Cost: registrar.Money{Currency: "eur", Minor: 899}}
+ f.TransferChecks["shop.example"] = check
+ got, err := provider.CheckTransfer(ctx, "shop.example")
+ check.Domain = "shop.example"
+ if err != nil || got != check {
+ t.Fatalf("CheckTransfer = %+v, %v; want %+v", got, err, check)
+ }
+ 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 {
+ t.Fatalf("status before request = %+v, %v", s, err)
+ }
+
+ empty := transferRequest()
+ empty.Nameservers = nil
+ 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 {
+ t.Fatalf("refused request left %+v", s)
+ }
+
+ req := transferRequest()
+ s, err := provider.RequestTransfer(ctx, req)
+ if err != nil || s.State != registrar.TransferPending {
+ t.Fatalf("RequestTransfer = %+v, %v", s, err)
+ }
+ if f.LastTransfer.AuthCode != transferAuthCode || f.LastTransfer.Key != req.Key {
+ t.Fatalf("fake did not record the request: %v", f.LastTransfer)
+ }
+ req.Nameservers[0] = "changed.example"
+ 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 {
+ t.Fatalf("pending status = %+v, %v", s, err)
+ }
+ expires := time.Date(2027, 12, 2, 0, 0, 0, 0, time.UTC)
+ done := registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{
+ 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) {
+ 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) {
+ t.Fatalf("completed transfer not in the account: %+v %v %v", r, found, err)
+ }
+
+ // A failed transfer stays failed with its reason.
+ other := transferRequest()
+ other.Domain = "other.example"
+ if _, err := provider.RequestTransfer(ctx, other); err != nil {
+ 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" {
+ t.Fatalf("failed status = %+v", s)
+ }
+
+ // A scripted refusal: definite, nothing pending, the reason returned.
+ f.Transfers["locked.example"] = registrar.TransferStatus{State: registrar.TransferFailed, Reason: "locked"}
+ locked := transferRequest()
+ locked.Domain = "locked.example"
+ 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 {
+ t.Fatalf("refusal left %+v", s)
+ }
+ if strings.Contains(fmt.Sprintf("%v %+v %#v", f, f, f), "gX38") {
+ t.Fatal("fake prints the recorded auth code")
+ }
+
+ // Lost responses: the error is one-shot; RequestApplies says whether the
+ // request still took effect at the registrar.
+ for _, applies := range []bool{false, true} {
+ t.Run(fmt.Sprint("applies=", applies), func(t *testing.T) {
+ f := registrartest.New()
+ f.RequestErr, f.RequestApplies = registrar.ErrIndeterminate, applies
+ if _, err := f.RequestTransfer(ctx, transferRequest()); !errors.Is(err, registrar.ErrIndeterminate) {
+ t.Fatalf("RequestTransfer error = %v", err)
+ }
+ if f.RequestErr != nil {
+ t.Fatal("RequestErr is not one-shot")
+ }
+ want := registrar.TransferNone
+ if applies {
+ want = registrar.TransferPending
+ }
+ 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"}
+ if !reflect.DeepEqual(f.Calls, wantCalls) {
+ t.Fatalf("Calls = %v, want %v", f.Calls, wantCalls)
+ }
+ })
+ }
+}
diff --git a/internal/registrar/registrartest/fake.go b/internal/registrar/registrartest/fake.go
index 67b6e0489..7e29f39a0 100644
--- a/internal/registrar/registrartest/fake.go
+++ b/internal/registrar/registrartest/fake.go
@@ -2,6 +2,7 @@ package registrartest
import (
"context"
+ "errors"
"fmt"
"slices"
"sync"
@@ -17,6 +18,13 @@ type Fake struct {
RegisterErr error
Calls []string
+ // Transfers, scripted: see RequestTransfer and Advance.
+ TransferChecks map[string]registrar.TransferCheck
+ Transfers map[string]registrar.TransferStatus
+ 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
registered map[string]registrar.Registered
contacts map[string]registrar.Contact
@@ -27,10 +35,12 @@ var _ registrar.Registrar = (*Fake)(nil)
func New() *Fake {
return &Fake{
- Available: make(map[string]registrar.Availability),
- Domains: make(map[string]registrar.Registered),
- registered: make(map[string]registrar.Registered),
- contacts: make(map[string]registrar.Contact),
+ Available: make(map[string]registrar.Availability),
+ Domains: make(map[string]registrar.Registered),
+ TransferChecks: make(map[string]registrar.TransferCheck),
+ Transfers: make(map[string]registrar.TransferStatus),
+ registered: make(map[string]registrar.Registered),
+ contacts: make(map[string]registrar.Contact),
}
}
@@ -113,3 +123,98 @@ func clone(r registrar.Registered) registrar.Registered {
r.Nameservers = slices.Clone(r.Nameservers)
return r
}
+
+// CheckTransfer answers from TransferChecks; an unscripted domain is not
+// transferable ("unsupported").
+func (f *Fake) CheckTransfer(ctx context.Context, domain string) (registrar.TransferCheck, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "check-transfer:"+domain)
+ c, ok := f.TransferChecks[domain]
+ if !ok {
+ c = registrar.TransferCheck{Reason: "unsupported"}
+ }
+ c.Domain = domain
+ return c, nil
+}
+
+// RequestTransfer records r in LastTransfer, auth code included. A
+// Transfers entry scripted before the request is its outcome: TransferFailed
+// is a refusal (ErrRefused, the entry removed: nothing pending), any other
+// state is accepted as scripted. Unscripted, the request is accepted as
+// pending. RequestErr is returned once; RequestApplies says whether that
+// request still took effect (a lost response).
+func (f *Fake) RequestTransfer(ctx context.Context, r registrar.TransferRequest) (registrar.TransferStatus, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "request-transfer:"+r.Domain)
+ r.Nameservers = slices.Clone(r.Nameservers)
+ f.LastTransfer = r
+ refused := registrar.TransferStatus{State: registrar.TransferFailed, Reason: "rejected"}
+ if r.Domain == "" || r.AuthCode == "" || r.OwnerHandle == "" || len(r.Nameservers) == 0 {
+ return refused, fmt.Errorf("%w: incomplete transfer", registrar.ErrRefused)
+ }
+ outcome, scripted := f.Transfers[r.Domain]
+ if !scripted || outcome.State == "" || outcome.State == registrar.TransferNone {
+ outcome = registrar.TransferStatus{State: registrar.TransferPending}
+ }
+ if f.RequestErr != nil {
+ err := f.RequestErr
+ f.RequestErr = nil
+ if f.RequestApplies {
+ f.setTransfer(r.Domain, outcome)
+ }
+ if errors.Is(err, registrar.ErrRefused) {
+ return refused, err
+ }
+ return registrar.TransferStatus{}, err
+ }
+ if outcome.State == registrar.TransferFailed {
+ delete(f.Transfers, r.Domain)
+ 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) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "transfer-status:"+domain)
+ s, ok := f.Transfers[domain]
+ if !ok {
+ return registrar.TransferStatus{State: registrar.TransferNone}, nil
+ }
+ return cloneTransfer(s), 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).
+func (f *Fake) Advance(domain string, s registrar.TransferStatus) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.setTransfer(domain, s)
+}
+
+func (f *Fake) setTransfer(domain string, s registrar.TransferStatus) {
+ if f.Transfers == nil {
+ f.Transfers = make(map[string]registrar.TransferStatus)
+ }
+ f.Transfers[domain] = cloneTransfer(s)
+ if s.State == registrar.TransferCompleted {
+ if f.Domains == nil {
+ f.Domains = make(map[string]registrar.Registered)
+ }
+ r := clone(s.Registered)
+ if r.Domain == "" {
+ r.Domain = domain
+ }
+ f.Domains[domain] = r
+ }
+}
+
+func cloneTransfer(s registrar.TransferStatus) registrar.TransferStatus {
+ s.Registered = clone(s.Registered)
+ return s
+}