carlos / platform Public

registrar: provider-neutral registrar seam and fake

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 256c673ab842d273478689a64de50eee0beea099 parent 982ee18
4 files changed, +433 −0
  • internal/registrar/boundary_test.go +85 −0
  • internal/registrar/registrar.go +72 −0
  • internal/registrar/registrar_test.go +172 −0
  • internal/registrar/registrartest/fake.go +104 −0
diff --git a/internal/registrar/boundary_test.go b/internal/registrar/boundary_test.go
new file mode 100644
index 000000000..e31d837d9
--- /dev/null
+++ b/internal/registrar/boundary_test.go
@@ -0,0 +1,85 @@
+package registrar_test
+
+import (
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestCoreImportsNoProviders(t *testing.T) {
+ for _, name := range []string{"registrar", "zonehost", "domainreg"} {
+ t.Run(name, func(t *testing.T) {
+ dir := filepath.Join("..", name)
+ if _, err := os.Stat(dir); os.IsNotExist(err) && name != "registrar" {
+ t.Skip("package has not been implemented yet")
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ for _, violation := range providerImports(t, dir) {
+ t.Error(violation)
+ }
+ })
+ }
+}
+
+func providerImports(t *testing.T, dir string) []string {
+ t.Helper()
+ files, err := filepath.Glob(filepath.Join(dir, "*.go"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var violations []string
+ parsed := 0
+ for _, path := range files {
+ if strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed++
+ for _, imp := range file.Imports {
+ p, err := strconv.Unquote(imp.Path.Value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, prefix := range []string{
+ "github.com/aws",
+ "github.com/carlosframework/platform/internal/registrar/openprovider",
+ "github.com/carlosframework/platform/internal/zonehost/route53zones",
+ } {
+ if p == prefix || strings.HasPrefix(p, prefix+"/") {
+ violations = append(violations, path+" imports "+p)
+ }
+ }
+ }
+ }
+ if parsed == 0 {
+ t.Fatalf("no production Go files checked in %s", dir)
+ }
+ return violations
+}
+
+func TestProviderBoundaryDetectsImports(t *testing.T) {
+ for _, path := range []string{
+ "github.com/aws/aws-sdk-go-v2/service/route53",
+ "github.com/carlosframework/platform/internal/registrar/openprovider",
+ "github.com/carlosframework/platform/internal/zonehost/route53zones",
+ } {
+ t.Run(path, func(t *testing.T) {
+ dir := t.TempDir()
+ src := "//go:build windows\n\npackage core\nimport alias " + strconv.Quote(path) + "\n"
+ if err := os.WriteFile(filepath.Join(dir, "core_windows.go"), []byte(src), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if got := providerImports(t, dir); len(got) != 1 {
+ t.Fatalf("violations = %v, want one for %s", got, path)
+ }
+ })
+ }
+}
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go
new file mode 100644
index 000000000..97bca8d06
--- /dev/null
+++ b/internal/registrar/registrar.go
@@ -0,0 +1,72 @@
+package registrar
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+type Money struct {
+ Currency string // ISO 4217 lower case
+ Minor int64 // minor units
+}
+
+type Availability struct {
+ Domain string
+ Available, Premium bool
+ Cost Money
+}
+
+type Contact struct {
+ // Country ISO 3166-1 alpha-2
+ FirstName, LastName, Company, Email, Phone, Street, City, State, PostalCode, Country string
+}
+
+type Registration struct {
+ Domain string
+ Years int
+ Nameservers []string
+ OwnerHandle string
+ Key string // idempotency, the purchase ID
+}
+
+type Registered struct {
+ Domain, RegistrarID string
+ Expires time.Time
+ Nameservers []string
+}
+
+type Registrar interface {
+ Check(ctx context.Context, domain string) (Availability, error)
+ EnsureContact(ctx context.Context, existingHandle string, c Contact) (handle string, err error)
+ 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)
+}
+
+var ErrUnavailable = errors.New("registrar: domain not available")
+var ErrRefused = errors.New("registrar: refused") // definite, nothing registered
+var ErrIndeterminate = errors.New("registrar: outcome unknown") // timeout, 5xx after send
+
+func (c Contact) Validate() error {
+ for _, field := range []struct{ name, value string }{
+ {"FirstName", c.FirstName},
+ {"LastName", c.LastName},
+ {"Email", c.Email},
+ {"Phone", c.Phone},
+ {"Street", c.Street},
+ {"City", c.City},
+ {"PostalCode", c.PostalCode},
+ {"Country", c.Country},
+ } {
+ if strings.TrimSpace(field.value) == "" {
+ return fmt.Errorf("registrar: %s is required", field.name)
+ }
+ }
+ if len(c.Country) != 2 || c.Country[0] < 'A' || c.Country[0] > 'Z' || c.Country[1] < 'A' || c.Country[1] > 'Z' {
+ return errors.New("registrar: Country must be two uppercase ASCII letters")
+ }
+ return nil
+}
diff --git a/internal/registrar/registrar_test.go b/internal/registrar/registrar_test.go
new file mode 100644
index 000000000..d18c0127c
--- /dev/null
+++ b/internal/registrar/registrar_test.go
@@ -0,0 +1,172 @@
+package registrar_test
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/carlosframework/platform/internal/registrar/registrartest"
+)
+
+func fullContact() registrar.Contact {
+ return registrar.Contact{
+ FirstName: "Alex", LastName: "Example", Email: "alex@example.com",
+ Phone: "+442079460000", Street: "1 Example Street", City: "London",
+ PostalCode: "SW1A 1AA", Country: "GB",
+ }
+}
+
+func TestContactValidateRequiresFields(t *testing.T) {
+ if err := (registrar.Contact{}).Validate(); err == nil || !strings.Contains(err.Error(), "FirstName") {
+ t.Fatalf("empty contact: got %v, want error naming FirstName", err)
+ }
+ if err := fullContact().Validate(); err != nil {
+ t.Fatalf("full contact: %v", err)
+ }
+ for _, field := range []string{"FirstName", "LastName", "Email", "Phone", "Street", "City", "PostalCode", "Country"} {
+ t.Run(field, func(t *testing.T) {
+ for _, blank := range []string{"", " \t\n"} {
+ c := fullContact()
+ reflect.ValueOf(&c).Elem().FieldByName(field).SetString(blank)
+ if err := c.Validate(); err == nil || !strings.Contains(err.Error(), field) {
+ t.Errorf("%s=%q: got %v, want error naming %s", field, blank, err, field)
+ }
+ }
+ })
+ }
+ for _, country := range []string{"gb", "GBR", "G1", " G", "Gé"} {
+ t.Run(country, func(t *testing.T) {
+ c := fullContact()
+ c.Country = country
+ if err := c.Validate(); err == nil || !strings.Contains(err.Error(), "Country") {
+ t.Errorf("Country=%q: got %v, want error naming Country", country, err)
+ }
+ })
+ }
+}
+
+func TestFakeRegisterIsIdempotentByKey(t *testing.T) {
+ f := registrartest.New()
+ var provider registrar.Registrar = f
+ r := registrar.Registration{
+ Domain: "shop.example", Years: 1, Key: "purchase-1", OwnerHandle: "contact-1",
+ Nameservers: []string{"ns1.example", "ns2.example"},
+ }
+ first, err := provider.Register(context.Background(), r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := provider.Register(context.Background(), r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(first, second) {
+ t.Fatalf("replayed registration = %+v, want %+v", second, first)
+ }
+ if !reflect.DeepEqual(f.Calls, []string{"register:shop.example"}) {
+ t.Fatalf("Calls = %v, want one register:shop.example", f.Calls)
+ }
+ if first.Domain != r.Domain || first.RegistrarID == "" || first.Expires.IsZero() || !reflect.DeepEqual(first.Nameservers, r.Nameservers) {
+ t.Fatalf("registration = %+v, request = %+v", first, r)
+ }
+}
+
+func TestFakeRegisterErrorIsOneShot(t *testing.T) {
+ ctx := context.Background()
+ for _, injected := range []error{registrar.ErrUnavailable, registrar.ErrRefused, registrar.ErrIndeterminate} {
+ t.Run(injected.Error(), func(t *testing.T) {
+ f := registrartest.New()
+ f.RegisterErr = injected
+ r := registrar.Registration{Domain: "shop.example", Years: 1, Key: "purchase-1"}
+ if _, err := f.Register(ctx, r); !errors.Is(err, injected) {
+ t.Fatalf("Register error = %v, want %v", err, injected)
+ }
+ if f.RegisterErr != nil || len(f.Domains) != 0 {
+ t.Fatalf("failed registration: RegisterErr=%v, Domains=%v", f.RegisterErr, f.Domains)
+ }
+ first, err := f.Register(ctx, r)
+ if err != nil {
+ t.Fatalf("retry: %v", err)
+ }
+ f.RegisterErr = registrar.ErrRefused
+ replayed, err := f.Register(ctx, r)
+ if err != nil || !reflect.DeepEqual(replayed, first) || f.RegisterErr != registrar.ErrRefused {
+ t.Fatalf("replay: result=%+v, err=%v, pending error=%v", replayed, err, f.RegisterErr)
+ }
+ if !reflect.DeepEqual(f.Calls, []string{"register:shop.example", "register:shop.example"}) {
+ t.Fatalf("Calls = %v", f.Calls)
+ }
+ })
+ }
+}
+
+func TestFakeStoredRegistrationsAreIndependent(t *testing.T) {
+ f := registrartest.New()
+ ctx := context.Background()
+ r := registrar.Registration{Domain: "shop.example", Years: 1, Key: "purchase-1", Nameservers: []string{"ns1.example"}}
+ first, err := f.Register(ctx, r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.Nameservers[0] = "changed-input.example"
+ first.Nameservers[0] = "changed-output.example"
+ lookedUp, found, err := f.Lookup(ctx, r.Domain)
+ if err != nil || !found || lookedUp.Nameservers[0] != "ns1.example" {
+ t.Fatalf("Lookup = %+v, %v, %v", lookedUp, found, err)
+ }
+ lookedUp.Nameservers[0] = "changed-lookup.example"
+ f.Domains[r.Domain] = registrar.Registered{Domain: r.Domain}
+ replayed, err := f.Register(ctx, r)
+ if err != nil || replayed.Nameservers[0] != "ns1.example" {
+ t.Fatalf("replay = %+v, %v", replayed, err)
+ }
+ r.Domain, r.Key = "other.example", "purchase-2"
+ other, err := f.Register(ctx, r)
+ if err != nil || other.Domain != r.Domain || other.RegistrarID == replayed.RegistrarID {
+ t.Fatalf("second key = %+v, %v", other, err)
+ }
+}
+
+func TestFakeCheckContactLookupAndBalance(t *testing.T) {
+ f := registrartest.New()
+ ctx := context.Background()
+ a := registrar.Availability{Domain: "shop.example", Available: true, Premium: true, Cost: registrar.Money{Currency: "eur", Minor: 899}}
+ f.Available[a.Domain] = a
+ if got, err := f.Check(ctx, a.Domain); err != nil || got != a {
+ t.Fatalf("Check = %+v, %v; want %+v", got, err, a)
+ }
+ if got, err := f.Check(ctx, "unknown.example"); err != nil || got.Available || got.Domain != "unknown.example" {
+ t.Fatalf("unknown Check = %+v, %v", got, err)
+ }
+ handle, err := f.EnsureContact(ctx, "", fullContact())
+ if err != nil || handle == "" {
+ t.Fatalf("EnsureContact = %q, %v", handle, err)
+ }
+ if updated, err := f.EnsureContact(ctx, handle, fullContact()); err != nil || updated != handle {
+ t.Fatalf("update contact = %q, %v; want %q", updated, err, handle)
+ }
+ if _, err := f.EnsureContact(ctx, "", registrar.Contact{}); err == nil {
+ t.Fatal("empty contact accepted")
+ }
+ if _, found, err := f.Lookup(ctx, a.Domain); err != nil || found {
+ t.Fatalf("unregistered Lookup = %v, %v", found, err)
+ }
+ f.Domains[a.Domain] = registrar.Registered{Domain: a.Domain, RegistrarID: "seeded"}
+ if got, found, err := f.Lookup(ctx, a.Domain); err != nil || !found || got.RegistrarID != "seeded" {
+ t.Fatalf("seeded Lookup = %+v, %v, %v", got, found, err)
+ }
+ if got, err := f.Check(ctx, a.Domain); err != nil || got.Available {
+ t.Fatalf("registered Check = %+v, %v", got, err)
+ }
+ f.BalanceMoney = registrar.Money{Currency: "eur", Minor: 10000}
+ if got, err := f.Balance(ctx); err != nil || got != f.BalanceMoney {
+ t.Fatalf("Balance = %+v, %v", got, err)
+ }
+ wantCalls := []string{"check:shop.example", "check:unknown.example", "contact:", "contact:" + handle, "contact:", "lookup:shop.example", "lookup:shop.example", "check:shop.example", "balance"}
+ 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
new file mode 100644
index 000000000..7232a9a2f
--- /dev/null
+++ b/internal/registrar/registrartest/fake.go
@@ -0,0 +1,104 @@
+package registrartest
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+type Fake struct {
+ Available map[string]registrar.Availability
+ Domains map[string]registrar.Registered
+ BalanceMoney registrar.Money
+ RegisterErr error
+ Calls []string
+
+ mu sync.Mutex
+ registered map[string]registrar.Registered
+ nextContact int
+}
+
+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),
+ }
+}
+
+func (f *Fake) Check(ctx context.Context, domain string) (registrar.Availability, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "check:"+domain)
+ a := f.Available[domain]
+ a.Domain = domain
+ if _, exists := f.Domains[domain]; exists {
+ a.Available = false
+ }
+ return a, nil
+}
+
+func (f *Fake) EnsureContact(ctx context.Context, existingHandle string, c registrar.Contact) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "contact:"+existingHandle)
+ if err := c.Validate(); err != nil {
+ return "", err
+ }
+ if existingHandle != "" {
+ return existingHandle, nil
+ }
+ f.nextContact++
+ return fmt.Sprintf("contact-%d", f.nextContact), nil
+}
+
+func (f *Fake) Register(ctx context.Context, r registrar.Registration) (registrar.Registered, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if stored, ok := f.registered[r.Key]; ok {
+ return clone(stored), nil
+ }
+ f.Calls = append(f.Calls, "register:"+r.Domain)
+ if f.RegisterErr != nil {
+ err := f.RegisterErr
+ f.RegisterErr = nil
+ return registrar.Registered{}, err
+ }
+ if _, exists := f.Domains[r.Domain]; exists {
+ return registrar.Registered{}, registrar.ErrUnavailable
+ }
+ registered := registrar.Registered{
+ Domain: r.Domain, RegistrarID: "registration-" + r.Domain,
+ Expires: time.Now().UTC().AddDate(r.Years, 0, 0),
+ Nameservers: slices.Clone(r.Nameservers),
+ }
+ f.Domains[r.Domain] = clone(registered)
+ f.registered[r.Key] = clone(registered)
+ return registered, nil
+}
+
+func (f *Fake) Lookup(ctx context.Context, domain string) (registrar.Registered, bool, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "lookup:"+domain)
+ r, ok := f.Domains[domain]
+ return clone(r), ok, nil
+}
+
+func (f *Fake) Balance(ctx context.Context) (registrar.Money, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "balance")
+ return f.BalanceMoney, nil
+}
+
+func clone(r registrar.Registered) registrar.Registered {
+ r.Nameservers = slices.Clone(r.Nameservers)
+ return r
+}