carlos / platform Public

zonehost: zone host seam, fake, Route 53 adapter on a branded delegation set

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3be6b5cea617bf1400e0a099fee934decfd6cb3f parent 32d1546
5 files changed, +1,192 −0
  • internal/zonehost/route53zones/route53.go +371 −0
  • internal/zonehost/route53zones/route53_test.go +492 −0
  • internal/zonehost/zonehost.go +96 −0
  • internal/zonehost/zonehost_test.go +124 −0
  • internal/zonehost/zonehosttest/fake.go +109 −0
diff --git a/internal/zonehost/route53zones/route53.go b/internal/zonehost/route53zones/route53.go
new file mode 100644
index 000000000..34e761374
--- /dev/null
+++ b/internal/zonehost/route53zones/route53.go
@@ -0,0 +1,371 @@
+package route53zones
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/route53"
+ r53types "github.com/aws/aws-sdk-go-v2/service/route53/types"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/rootaws"
+ "github.com/carlosframework/platform/internal/zonehost"
+)
+
+type Config struct {
+ DelegationSetID string
+ Nameservers []string
+ SteeringZoneID, SteeringHost string
+}
+type Host struct {
+ client route53API
+ config Config
+}
+
+var _ zonehost.Host = (*Host)(nil)
+
+type route53API interface {
+ CreateHostedZone(context.Context, *route53.CreateHostedZoneInput, ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error)
+ ListHostedZones(context.Context, *route53.ListHostedZonesInput, ...func(*route53.Options)) (*route53.ListHostedZonesOutput, error)
+ DeleteHostedZone(context.Context, *route53.DeleteHostedZoneInput, ...func(*route53.Options)) (*route53.DeleteHostedZoneOutput, error)
+ ListResourceRecordSets(context.Context, *route53.ListResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error)
+ ChangeResourceRecordSets(context.Context, *route53.ChangeResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error)
+}
+
+// Method values keep the linker from retaining every exported SDK method when
+// the console links html/template. See internal/steering/route53.go (#275).
+type route53Methods struct {
+ create func(context.Context, *route53.CreateHostedZoneInput, ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error)
+ listZones func(context.Context, *route53.ListHostedZonesInput, ...func(*route53.Options)) (*route53.ListHostedZonesOutput, error)
+ delete func(context.Context, *route53.DeleteHostedZoneInput, ...func(*route53.Options)) (*route53.DeleteHostedZoneOutput, error)
+ listRecords func(context.Context, *route53.ListResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error)
+ change func(context.Context, *route53.ChangeResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error)
+}
+
+func (m route53Methods) CreateHostedZone(ctx context.Context, in *route53.CreateHostedZoneInput, opts ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error) {
+ return m.create(ctx, in, opts...)
+}
+func (m route53Methods) ListHostedZones(ctx context.Context, in *route53.ListHostedZonesInput, opts ...func(*route53.Options)) (*route53.ListHostedZonesOutput, error) {
+ return m.listZones(ctx, in, opts...)
+}
+func (m route53Methods) DeleteHostedZone(ctx context.Context, in *route53.DeleteHostedZoneInput, opts ...func(*route53.Options)) (*route53.DeleteHostedZoneOutput, error) {
+ return m.delete(ctx, in, opts...)
+}
+func (m route53Methods) ListResourceRecordSets(ctx context.Context, in *route53.ListResourceRecordSetsInput, opts ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error) {
+ return m.listRecords(ctx, in, opts...)
+}
+func (m route53Methods) ChangeResourceRecordSets(ctx context.Context, in *route53.ChangeResourceRecordSetsInput, opts ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) {
+ return m.change(ctx, in, opts...)
+}
+
+func New(ctx context.Context, c Config) (*Host, error) {
+ if c.DelegationSetID == "" || len(c.Nameservers) != 4 {
+ return nil, fmt.Errorf("route53zones: delegation set and four nameservers are required")
+ }
+ c.Nameservers = slices.Clone(c.Nameservers)
+ seen := map[string]bool{}
+ for i, n := range c.Nameservers {
+ n = canonical(n)
+ if n == "" || strings.ContainsAny(n, " \t\r\n") || seen[n] {
+ return nil, fmt.Errorf("route53zones: invalid or duplicate nameserver %q", n)
+ }
+ seen[n] = true
+ c.Nameservers[i] = n
+ }
+ var opts []func(*awsconfig.LoadOptions) error
+ if strings.TrimSpace(os.Getenv("AWS_REGION")) == "" && strings.TrimSpace(os.Getenv("AWS_DEFAULT_REGION")) == "" {
+ opts = append(opts, awsconfig.WithRegion("us-east-1"))
+ }
+ cfg, err := rootaws.LoadDefaultConfig(ctx, opts...)
+ if err != nil {
+ return nil, fmt.Errorf("route53zones: load AWS config: %w", err)
+ }
+ client := route53.NewFromConfig(cfg)
+ return &Host{config: c, client: route53Methods{create: client.CreateHostedZone, listZones: client.ListHostedZones, delete: client.DeleteHostedZone, listRecords: client.ListResourceRecordSets, change: client.ChangeResourceRecordSets}}, nil
+}
+func (h *Host) Nameservers() []string {
+ ns := slices.Clone(h.config.Nameservers)
+ for i, n := range ns {
+ ns[i] = canonical(n)
+ }
+ return ns
+}
+func canonical(name string) string { return strings.ToLower(strings.TrimSuffix(name, ".")) }
+func fqdn(name string) string { return canonical(name) + "." }
+
+func (h *Host) CreateZone(ctx context.Context, domain, key string) (zonehost.Zone, error) {
+ domain = canonical(domain)
+ if domain == "" || key == "" {
+ return zonehost.Zone{}, fmt.Errorf("route53zones: domain and key are required")
+ }
+ out, err := h.client.CreateHostedZone(ctx, &route53.CreateHostedZoneInput{Name: aws.String(domain), CallerReference: aws.String(key), DelegationSetId: aws.String(h.config.DelegationSetID)})
+ var existing *r53types.HostedZoneAlreadyExists
+ var created *r53types.HostedZone
+ if errors.As(err, &existing) {
+ created, err = h.findByKey(ctx, domain, key)
+ } else if err == nil {
+ created = out.HostedZone
+ }
+ if err != nil {
+ return zonehost.Zone{}, fmt.Errorf("route53zones: create zone: %w", err)
+ }
+ if created == nil || aws.ToString(created.Id) == "" {
+ return zonehost.Zone{}, fmt.Errorf("route53zones: create returned no zone ID")
+ }
+ z := zonehost.Zone{ID: strings.TrimPrefix(aws.ToString(created.Id), "/hostedzone/"), Domain: domain}
+ // Retry branding after recovering a prior create: a crash can fall between
+ // CreateHostedZone and this batch, before the caller has saved the zone ID.
+ if err := h.brand(ctx, z); err != nil {
+ return z, err
+ }
+ return z, nil
+}
+func (h *Host) findByKey(ctx context.Context, domain, key string) (*r53types.HostedZone, error) {
+ in := &route53.ListHostedZonesInput{}
+ for {
+ out, err := h.client.ListHostedZones(ctx, in)
+ if err != nil {
+ return nil, err
+ }
+ for _, z := range out.HostedZones {
+ if aws.ToString(z.CallerReference) != key {
+ continue
+ }
+ if canonical(aws.ToString(z.Name)) != domain {
+ return nil, fmt.Errorf("route53zones: key belongs to another domain")
+ }
+ return &z, nil
+ }
+ if !out.IsTruncated {
+ break
+ }
+ if aws.ToString(out.NextMarker) == "" || aws.ToString(out.NextMarker) == aws.ToString(in.Marker) {
+ return nil, fmt.Errorf("route53zones: invalid zone pagination cursor")
+ }
+ in.Marker = out.NextMarker
+ }
+ return nil, fmt.Errorf("route53zones: existing zone not found by caller reference")
+}
+func (h *Host) records(ctx context.Context, id string) ([]r53types.ResourceRecordSet, error) {
+ in := &route53.ListResourceRecordSetsInput{HostedZoneId: aws.String(id)}
+ var result []r53types.ResourceRecordSet
+ for {
+ out, err := h.client.ListResourceRecordSets(ctx, in)
+ if err != nil {
+ return nil, err
+ }
+ result = append(result, out.ResourceRecordSets...)
+ if !out.IsTruncated {
+ return result, nil
+ }
+ if aws.ToString(out.NextRecordName) == "" || (aws.ToString(in.StartRecordName) == aws.ToString(out.NextRecordName) && in.StartRecordType == out.NextRecordType && aws.ToString(in.StartRecordIdentifier) == aws.ToString(out.NextRecordIdentifier)) {
+ return nil, fmt.Errorf("route53zones: invalid record pagination cursor")
+ }
+ in.StartRecordName = out.NextRecordName
+ in.StartRecordType = out.NextRecordType
+ in.StartRecordIdentifier = out.NextRecordIdentifier
+ }
+}
+func (h *Host) change(ctx context.Context, id string, changes []r53types.Change) error {
+ if len(changes) == 0 {
+ return nil
+ }
+ _, err := h.client.ChangeResourceRecordSets(ctx, &route53.ChangeResourceRecordSetsInput{HostedZoneId: aws.String(id), ChangeBatch: &r53types.ChangeBatch{Changes: changes}})
+ if err != nil {
+ return fmt.Errorf("route53zones: change records: %w", err)
+ }
+ return nil
+}
+func (h *Host) brand(ctx context.Context, z zonehost.Zone) error {
+ records, err := h.records(ctx, z.ID)
+ if err != nil {
+ return fmt.Errorf("route53zones: read SOA: %w", err)
+ }
+ ns := h.Nameservers()
+ if len(ns) != 4 {
+ return fmt.Errorf("route53zones: four nameservers are required")
+ }
+ for _, r := range records {
+ if canonical(aws.ToString(r.Name)) != z.Domain || r.Type != r53types.RRTypeSoa {
+ continue
+ }
+ if len(r.ResourceRecords) != 1 {
+ return fmt.Errorf("route53zones: invalid SOA")
+ }
+ soa := aws.ToString(r.ResourceRecords[0].Value)
+ end := strings.IndexAny(soa, " \t\r\n")
+ if end < 1 || len(strings.Fields(soa)) != 7 {
+ return fmt.Errorf("route53zones: invalid SOA value")
+ }
+ r.ResourceRecords = []r53types.ResourceRecord{{Value: aws.String(fqdn(ns[0]) + soa[end:])}}
+ names := r53types.ResourceRecordSet{Name: aws.String(fqdn(z.Domain)), Type: r53types.RRTypeNs, TTL: aws.Int64(172800)}
+ for _, n := range ns {
+ names.ResourceRecords = append(names.ResourceRecords, r53types.ResourceRecord{Value: aws.String(fqdn(n))})
+ }
+ return h.change(ctx, z.ID, []r53types.Change{{Action: r53types.ChangeActionUpsert, ResourceRecordSet: &r}, {Action: r53types.ChangeActionUpsert, ResourceRecordSet: &names}})
+ }
+ return fmt.Errorf("route53zones: zone has no apex SOA")
+}
+
+func owned(z zonehost.Zone, r r53types.ResourceRecordSet) bool {
+ name := canonical(aws.ToString(r.Name))
+ apex := canonical(z.Domain)
+ return (r.Type == r53types.RRTypeA && (name == apex || name == "www."+apex)) ||
+ (r.Type == r53types.RRTypeTxt && (name == domains.ChallengeName(apex) || name == domains.ChallengeName("www."+apex)))
+}
+
+type recordKey struct {
+ name string
+ typ r53types.RRType
+ id string
+}
+
+func identity(r r53types.ResourceRecordSet) recordKey {
+ return recordKey{canonical(aws.ToString(r.Name)), r.Type, aws.ToString(r.SetIdentifier)}
+}
+
+func (h *Host) SetManaged(ctx context.Context, z zonehost.Zone, m zonehost.ManagedSet) error {
+ if err := m.ValidateForZone(z); err != nil {
+ return err
+ }
+ desired := managedRecords(z, m)
+ wanted := map[recordKey]bool{}
+ for _, r := range desired {
+ wanted[identity(r)] = true
+ }
+ records, err := h.records(ctx, z.ID)
+ if err != nil {
+ return fmt.Errorf("route53zones: list managed records: %w", err)
+ }
+ var changes []r53types.Change
+ for _, r := range records {
+ if owned(z, r) && !wanted[identity(r)] {
+ changes = append(changes, r53types.Change{Action: r53types.ChangeActionDelete, ResourceRecordSet: &r})
+ }
+ }
+ for _, r := range desired {
+ changes = append(changes, r53types.Change{Action: r53types.ChangeActionUpsert, ResourceRecordSet: &r})
+ }
+ return h.change(ctx, z.ID, changes)
+}
+func managedRecords(z zonehost.Zone, m zonehost.ManagedSet) []r53types.ResourceRecordSet {
+ var records []r53types.ResourceRecordSet
+ if m.Apex[0].Region == "" {
+ r := r53types.ResourceRecordSet{Name: aws.String(fqdn(z.Domain)), Type: r53types.RRTypeA, TTL: aws.Int64(300)}
+ for _, a := range m.Apex {
+ r.ResourceRecords = append(r.ResourceRecords, r53types.ResourceRecord{Value: aws.String(a.IP)})
+ }
+ records = append(records, r)
+ } else {
+ for _, a := range m.Apex {
+ r := r53types.ResourceRecordSet{Name: aws.String(fqdn(z.Domain)), Type: r53types.RRTypeA, TTL: aws.Int64(60), SetIdentifier: aws.String(a.SetID), Region: r53types.ResourceRecordSetRegion(a.Region), ResourceRecords: []r53types.ResourceRecord{{Value: aws.String(a.IP)}}}
+ if a.HealthCheckID != "" {
+ r.HealthCheckId = aws.String(a.HealthCheckID)
+ }
+ records = append(records, r)
+ }
+ }
+ if m.WWW {
+ records = append(records, r53types.ResourceRecordSet{Name: aws.String(fqdn("www." + canonical(z.Domain))), Type: r53types.RRTypeA, AliasTarget: &r53types.AliasTarget{DNSName: aws.String(fqdn(z.Domain)), HostedZoneId: aws.String(z.ID), EvaluateTargetHealth: true}})
+ }
+ txtIndex := map[string]int{}
+ for _, txt := range m.TXT {
+ name := fqdn(txt.Name)
+ i, ok := txtIndex[name]
+ if !ok {
+ i = len(records)
+ txtIndex[name] = i
+ records = append(records, r53types.ResourceRecordSet{Name: aws.String(name), Type: r53types.RRTypeTxt, TTL: aws.Int64(300)})
+ }
+ records[i].ResourceRecords = append(records[i].ResourceRecords, r53types.ResourceRecord{Value: aws.String(strconv.Quote(txt.Value))})
+ }
+ return records
+}
+
+// DeleteZone destroys all contents, including customer and email records.
+// Only the zone's own SOA and NS remain for DeleteHostedZone to remove.
+func (h *Host) DeleteZone(ctx context.Context, z zonehost.Zone) error {
+ records, err := h.records(ctx, z.ID)
+ if noSuchZone(err) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("route53zones: list zone for deletion: %w", err)
+ }
+ var changes []r53types.Change
+ for _, r := range records {
+ if canonical(aws.ToString(r.Name)) == canonical(z.Domain) && (r.Type == r53types.RRTypeSoa || r.Type == r53types.RRTypeNs) {
+ continue
+ }
+ changes = append(changes, r53types.Change{Action: r53types.ChangeActionDelete, ResourceRecordSet: &r})
+ }
+ // Keep teardown batches within the API's 1,000 resource-record limit.
+ for len(changes) > 0 {
+ end, count := 0, 0
+ for end < len(changes) {
+ n := max(1, len(changes[end].ResourceRecordSet.ResourceRecords))
+ if count+n > 1000 {
+ break
+ }
+ count += n
+ end++
+ }
+ if end == 0 {
+ return fmt.Errorf("route53zones: record set exceeds the deletion batch limit")
+ }
+ err := h.change(ctx, z.ID, changes[:end])
+ if noSuchZone(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ changes = changes[end:]
+ }
+ _, err = h.client.DeleteHostedZone(ctx, &route53.DeleteHostedZoneInput{Id: aws.String(z.ID)})
+ if noSuchZone(err) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("route53zones: delete zone: %w", err)
+ }
+ return nil
+}
+func noSuchZone(err error) bool {
+ var missing *r53types.NoSuchHostedZone
+ return errors.As(err, &missing)
+}
+
+type steered struct{ host *Host }
+
+func (h *Host) Steered() zonehost.ApexSource { return steered{host: h} }
+func (s steered) ApexTargets(ctx context.Context) ([]zonehost.ApexTarget, error) {
+ h := s.host
+ if h.config.SteeringZoneID == "" || h.config.SteeringHost == "" {
+ return nil, fmt.Errorf("route53zones: steering zone and host are required")
+ }
+ records, err := h.records(ctx, h.config.SteeringZoneID)
+ if err != nil {
+ return nil, fmt.Errorf("route53zones: read steering records: %w", err)
+ }
+ var targets []zonehost.ApexTarget
+ for _, r := range records {
+ if canonical(aws.ToString(r.Name)) != canonical(h.config.SteeringHost) || r.Type != r53types.RRTypeA {
+ continue
+ }
+ if r.AliasTarget != nil || len(r.ResourceRecords) != 1 {
+ return nil, fmt.Errorf("route53zones: steering A set must contain one address")
+ }
+ targets = append(targets, zonehost.ApexTarget{IP: aws.ToString(r.ResourceRecords[0].Value), Region: string(r.Region), SetID: aws.ToString(r.SetIdentifier), HealthCheckID: aws.ToString(r.HealthCheckId)})
+ }
+ if err := (zonehost.ManagedSet{Apex: targets}).Validate(); err != nil {
+ return nil, fmt.Errorf("route53zones: invalid steering targets: %w", err)
+ }
+ return targets, nil
+}
diff --git a/internal/zonehost/route53zones/route53_test.go b/internal/zonehost/route53zones/route53_test.go
new file mode 100644
index 000000000..085f9242e
--- /dev/null
+++ b/internal/zonehost/route53zones/route53_test.go
@@ -0,0 +1,492 @@
+package route53zones
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/route53"
+ r53types "github.com/aws/aws-sdk-go-v2/service/route53/types"
+ "github.com/carlosframework/platform/internal/zonehost"
+)
+
+type fakeRoute53 struct {
+ records []r53types.ResourceRecordSet
+ batches [][]r53types.Change
+ creates []*route53.CreateHostedZoneInput
+ lists []*route53.ListResourceRecordSetsInput
+ zonePages []*route53.ListHostedZonesOutput
+ zoneMarkers []string
+ createErr, listErr, changeErr, deleteErr error
+ deleted []string
+ pageSize int
+}
+
+var _ route53API = (*fakeRoute53)(nil)
+
+func (f *fakeRoute53) CreateHostedZone(_ context.Context, in *route53.CreateHostedZoneInput, _ ...func(*route53.Options)) (*route53.CreateHostedZoneOutput, error) {
+ f.creates = append(f.creates, in)
+ if f.createErr != nil {
+ return nil, f.createErr
+ }
+ return &route53.CreateHostedZoneOutput{HostedZone: &r53types.HostedZone{Id: aws.String("/hostedzone/ZBOUGHT"), Name: in.Name, CallerReference: in.CallerReference}}, nil
+}
+func (f *fakeRoute53) ListHostedZones(_ context.Context, in *route53.ListHostedZonesInput, _ ...func(*route53.Options)) (*route53.ListHostedZonesOutput, error) {
+ f.zoneMarkers = append(f.zoneMarkers, aws.ToString(in.Marker))
+ if len(f.zonePages) == 0 {
+ return &route53.ListHostedZonesOutput{}, nil
+ }
+ out := f.zonePages[0]
+ f.zonePages = f.zonePages[1:]
+ return out, nil
+}
+func (f *fakeRoute53) ListResourceRecordSets(_ context.Context, in *route53.ListResourceRecordSetsInput, _ ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error) {
+ copy := *in
+ f.lists = append(f.lists, &copy)
+ if f.listErr != nil {
+ return nil, f.listErr
+ }
+ start := 0
+ if in.StartRecordName != nil {
+ for i, r := range f.records {
+ if aws.ToString(r.Name) == aws.ToString(in.StartRecordName) && r.Type == in.StartRecordType && aws.ToString(r.SetIdentifier) == aws.ToString(in.StartRecordIdentifier) {
+ start = i
+ break
+ }
+ }
+ }
+ end := len(f.records)
+ if f.pageSize > 0 && end > start+f.pageSize {
+ end = start + f.pageSize
+ }
+ out := &route53.ListResourceRecordSetsOutput{ResourceRecordSets: f.records[start:end]}
+ if end < len(f.records) {
+ next := f.records[end]
+ out.IsTruncated = true
+ out.NextRecordName = next.Name
+ out.NextRecordType = next.Type
+ out.NextRecordIdentifier = next.SetIdentifier
+ }
+ return out, nil
+}
+func (f *fakeRoute53) ChangeResourceRecordSets(_ context.Context, in *route53.ChangeResourceRecordSetsInput, _ ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) {
+ if f.changeErr != nil {
+ return nil, f.changeErr
+ }
+ changes := in.ChangeBatch.Changes
+ f.batches = append(f.batches, changes)
+ for _, c := range changes {
+ index := -1
+ for i, r := range f.records {
+ if sameRecord(r, *c.ResourceRecordSet) {
+ index = i
+ break
+ }
+ }
+ if c.Action == r53types.ChangeActionDelete {
+ if index < 0 || !reflect.DeepEqual(f.records[index], *c.ResourceRecordSet) {
+ return nil, fmt.Errorf("delete did not preserve existing record: %#v", c)
+ }
+ f.records = append(f.records[:index], f.records[index+1:]...)
+ } else if index < 0 {
+ f.records = append(f.records, *c.ResourceRecordSet)
+ } else {
+ f.records[index] = *c.ResourceRecordSet
+ }
+ }
+ return &route53.ChangeResourceRecordSetsOutput{}, nil
+}
+func (f *fakeRoute53) DeleteHostedZone(_ context.Context, in *route53.DeleteHostedZoneInput, _ ...func(*route53.Options)) (*route53.DeleteHostedZoneOutput, error) {
+ f.deleted = append(f.deleted, aws.ToString(in.Id))
+ return &route53.DeleteHostedZoneOutput{}, f.deleteErr
+}
+func sameRecord(a, b r53types.ResourceRecordSet) bool {
+ return strings.EqualFold(aws.ToString(a.Name), aws.ToString(b.Name)) && a.Type == b.Type && aws.ToString(a.SetIdentifier) == aws.ToString(b.SetIdentifier)
+}
+func rr(name string, typ r53types.RRType, values ...string) r53types.ResourceRecordSet {
+ r := r53types.ResourceRecordSet{Name: aws.String(name), Type: typ, TTL: aws.Int64(300)}
+ for _, v := range values {
+ r.ResourceRecords = append(r.ResourceRecords, r53types.ResourceRecord{Value: aws.String(v)})
+ }
+ return r
+}
+func fixture() (*Host, *fakeRoute53, zonehost.Zone) {
+ f := &fakeRoute53{records: []r53types.ResourceRecordSet{
+ rr("shop.example.", r53types.RRTypeSoa, "ns.old.example. hostmaster.example. 1 7200 900 1209600 900"),
+ rr("shop.example.", r53types.RRTypeNs, "ns.old.example."),
+ }}
+ h := &Host{client: f, config: Config{DelegationSetID: "NBRAND", Nameservers: []string{"ns1.brand.example", "ns2.brand.example", "ns3.brand.example", "ns4.brand.example"}}}
+ return h, f, zonehost.Zone{ID: "ZBOUGHT", Domain: "shop.example"}
+}
+func latency() zonehost.ManagedSet {
+ return zonehost.ManagedSet{Apex: []zonehost.ApexTarget{
+ {IP: "192.0.2.1", Region: "eu-west-1", SetID: "eu", HealthCheckID: "hc-eu"},
+ {IP: "192.0.2.2", Region: "us-east-1", SetID: "us", HealthCheckID: "hc-us"},
+ }}
+}
+func plain() zonehost.ManagedSet {
+ return zonehost.ManagedSet{Apex: []zonehost.ApexTarget{{IP: "192.0.2.3"}, {IP: "192.0.2.4"}}}
+}
+func TestCreateZoneUsesDelegationSetAndRewritesSOANS(t *testing.T) {
+ h, f, want := fixture()
+ got, err := h.CreateZone(context.Background(), "shop.example", "purchase:zone")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != want {
+ t.Fatalf("zone = %#v", got)
+ }
+ if len(f.creates) != 1 || aws.ToString(f.creates[0].DelegationSetId) != "NBRAND" || aws.ToString(f.creates[0].CallerReference) != "purchase:zone" {
+ t.Fatalf("create = %#v", f.creates)
+ }
+ if len(f.batches) != 1 || len(f.batches[0]) != 2 {
+ t.Fatalf("batches = %#v", f.batches)
+ }
+ for _, c := range f.batches[0] {
+ if c.Action != r53types.ChangeActionUpsert {
+ t.Fatal(c.Action)
+ }
+ r := c.ResourceRecordSet
+ switch r.Type {
+ case r53types.RRTypeSoa:
+ if aws.ToString(r.ResourceRecords[0].Value) != "ns1.brand.example. hostmaster.example. 1 7200 900 1209600 900" {
+ t.Fatalf("SOA = %#v", r)
+ }
+ case r53types.RRTypeNs:
+ want := rr("shop.example.", r53types.RRTypeNs, "ns1.brand.example.", "ns2.brand.example.", "ns3.brand.example.", "ns4.brand.example.")
+ want.TTL = aws.Int64(172800)
+ if !reflect.DeepEqual(*r, want) {
+ t.Fatalf("NS = %#v", r)
+ }
+ default:
+ t.Fatalf("unexpected record %v", r.Type)
+ }
+ }
+}
+func TestCreateZoneRetryRepairsBranding(t *testing.T) {
+ h, f, z := fixture()
+ f.createErr = &r53types.HostedZoneAlreadyExists{}
+ f.zonePages = []*route53.ListHostedZonesOutput{
+ {HostedZones: []r53types.HostedZone{{Id: aws.String("ZOTHER"), Name: aws.String("shop.example."), CallerReference: aws.String("different")}}, IsTruncated: true, NextMarker: aws.String("next")},
+ {HostedZones: []r53types.HostedZone{{Id: aws.String(z.ID), Name: aws.String(z.Domain + "."), CallerReference: aws.String("key")}}},
+ }
+ got, err := h.CreateZone(context.Background(), z.Domain, "key")
+ if err != nil || got != z {
+ t.Fatalf("retry = %v %v", got, err)
+ }
+ if !reflect.DeepEqual(f.zoneMarkers, []string{"", "next"}) || len(f.batches) != 1 {
+ t.Fatalf("retry did not recover/repair: %#v", f)
+ }
+}
+func TestSetManagedLatencyCopiesHealthChecks(t *testing.T) {
+ h, f, z := fixture()
+ m := latency()
+ if err := h.SetManaged(context.Background(), z, m); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.batches) != 1 || len(f.batches[0]) != 2 {
+ t.Fatalf("changes = %#v", f.batches)
+ }
+ for i, c := range f.batches[0] {
+ r := c.ResourceRecordSet
+ a := m.Apex[i]
+ if c.Action != r53types.ChangeActionUpsert || r.Type != r53types.RRTypeA || aws.ToString(r.Name) != "shop.example." || aws.ToInt64(r.TTL) != 60 || aws.ToString(r.HealthCheckId) != a.HealthCheckID || string(r.Region) != a.Region || aws.ToString(r.SetIdentifier) != a.SetID || aws.ToString(r.ResourceRecords[0].Value) != a.IP {
+ t.Fatalf("target %d = %#v", i, r)
+ }
+ }
+}
+func TestSetManagedDropsStaleSet(t *testing.T) {
+ h, f, z := fixture()
+ ctx := context.Background()
+ m := latency()
+ if err := h.SetManaged(ctx, z, m); err != nil {
+ t.Fatal(err)
+ }
+ m.Apex = m.Apex[:1]
+ if err := h.SetManaged(ctx, z, m); err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, c := range f.batches[1] {
+ if c.Action == r53types.ChangeActionDelete && aws.ToString(c.ResourceRecordSet.SetIdentifier) == "us" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("stale set not deleted")
+ }
+}
+func TestWWWIsSameZoneAlias(t *testing.T) {
+ h, f, z := fixture()
+ m := latency()
+ m.WWW = true
+ if err := h.SetManaged(context.Background(), z, m); err != nil {
+ t.Fatal(err)
+ }
+ r := f.records[len(f.records)-1]
+ a := r.AliasTarget
+ if r.Type != r53types.RRTypeA || aws.ToString(r.Name) != "www.shop.example." || r.TTL != nil || len(r.ResourceRecords) != 0 || a == nil || aws.ToString(a.HostedZoneId) != z.ID || aws.ToString(a.DNSName) != "shop.example." || !a.EvaluateTargetHealth {
+ t.Fatalf("www = %#v", r)
+ }
+}
+func TestSetManagedOwnership(t *testing.T) {
+ h, f, z := fixture()
+ ctx := context.Background()
+ unrelated := []r53types.ResourceRecordSet{rr("shop.example.", r53types.RRTypeTxt, `"v=spf1 -all"`), rr("verify.shop.example.", r53types.RRTypeTxt, `"customer"`), rr("shop.example.", r53types.RRTypeMx, "10 mail.example."), rr("_carlos-challenge.shop.example.", r53types.RRTypeAaaa, "2001:db8::1")}
+ f.records = append(f.records, unrelated...)
+ f.pageSize = 1
+ m := plain()
+ m.WWW = true
+ m.TXT = []zonehost.TXT{{Name: "_carlos-challenge.shop.example", Value: "proof"}, {Name: "_carlos-challenge.www.shop.example.", Value: "www proof"}}
+ if err := h.SetManaged(ctx, z, m); err != nil {
+ t.Fatal(err)
+ }
+ txts := 0
+ for _, r := range f.records {
+ if r.Type == r53types.RRTypeTxt && strings.HasPrefix(aws.ToString(r.Name), "_carlos-challenge.") {
+ txts++
+ if aws.ToInt64(r.TTL) != 300 || !strings.HasPrefix(aws.ToString(r.ResourceRecords[0].Value), `"`) {
+ t.Fatal("unquoted TXT or wrong TTL")
+ }
+ }
+ }
+ if txts != 2 {
+ t.Fatal("missing challenges")
+ }
+ // A fresh host must derive ownership without an in-memory write history.
+ h = &Host{client: f, config: h.config}
+ if err := h.SetManaged(ctx, z, plain()); err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range unrelated {
+ found := false
+ for _, got := range f.records {
+ if reflect.DeepEqual(r, got) {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("unrelated record changed: %#v", r)
+ }
+ }
+ if len(f.records) != len(unrelated)+3 {
+ t.Fatalf("stale www/TXT not removed: %v", f.records)
+ }
+ for _, name := range []string{"verify.shop.example", "_carlos-challenge.other.example", "_carlos-challenge.sub.shop.example", "shop.example"} {
+ m := plain()
+ m.TXT = []zonehost.TXT{{Name: name, Value: "bad"}}
+ before := len(f.lists)
+ if err := h.SetManaged(ctx, z, m); err == nil {
+ t.Fatalf("accepted TXT %q", name)
+ }
+ if len(f.lists) != before {
+ t.Fatal("invalid TXT reached API")
+ }
+ }
+}
+func TestSetManagedSwitchesRouting(t *testing.T) {
+ h, f, z := fixture()
+ ctx := context.Background()
+ for _, m := range []zonehost.ManagedSet{latency(), plain(), latency()} {
+ if err := h.SetManaged(ctx, z, m); err != nil {
+ t.Fatal(err)
+ }
+ count := 0
+ for _, r := range f.records {
+ if r.Type != r53types.RRTypeA {
+ continue
+ }
+ count++
+ if m.Apex[0].Region == "" && (r.SetIdentifier != nil || len(r.ResourceRecords) != 2 || aws.ToInt64(r.TTL) != 300) {
+ t.Fatalf("plain = %#v", r)
+ }
+ }
+ want := len(m.Apex)
+ if m.Apex[0].Region == "" {
+ want = 1
+ }
+ if count != want {
+ t.Fatalf("apex sets = %d, want %d", count, want)
+ }
+ }
+}
+func TestDeleteZoneRemovesEverythingButOwnSOANS(t *testing.T) {
+ h, f, z := fixture()
+ f.pageSize = 1
+ f.records = append(f.records, rr("shop.example.", r53types.RRTypeMx, "10 mail.example."), rr("verify.shop.example.", r53types.RRTypeTxt, `"customer"`), rr("child.shop.example.", r53types.RRTypeNs, "ns.child.example."), rr("child.shop.example.", r53types.RRTypeSoa, "ns.child.example. host.child.example. 1 2 3 4 5"))
+ if err := h.SetManaged(context.Background(), z, latency()); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.DeleteZone(context.Background(), z); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.records) != 2 || f.records[0].Type != r53types.RRTypeSoa || f.records[1].Type != r53types.RRTypeNs || !reflect.DeepEqual(f.deleted, []string{z.ID}) {
+ t.Fatalf("teardown: records %v, deleted %v", f.records, f.deleted)
+ }
+}
+func TestDeleteZoneNotFoundAndFailures(t *testing.T) {
+ for _, stage := range []string{"list", "change", "delete"} {
+ for _, missing := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/%v", stage, missing), func(t *testing.T) {
+ h, f, z := fixture()
+ f.records = append(f.records, rr("shop.example.", r53types.RRTypeA, "192.0.2.1"))
+ var boom error = errors.New("denied")
+ if missing {
+ boom = &r53types.NoSuchHostedZone{}
+ }
+ switch stage {
+ case "list":
+ f.listErr = boom
+ case "change":
+ f.changeErr = boom
+ case "delete":
+ f.deleteErr = boom
+ }
+ err := h.DeleteZone(context.Background(), z)
+ if missing && err != nil {
+ t.Fatal(err)
+ }
+ if !missing && !errors.Is(err, boom) {
+ t.Fatalf("lost error: %v", err)
+ }
+ if stage != "delete" && len(f.deleted) != 0 {
+ t.Fatal("deleted zone after failed read/change")
+ }
+ })
+ }
+ }
+}
+func TestSteeredReadsSteeringHost(t *testing.T) {
+ h, f, _ := fixture()
+ h.config.SteeringZoneID = "ZSTEER"
+ h.config.SteeringHost = "edge.apps.example"
+ f.records = nil
+ f.pageSize = 1
+ for _, a := range latency().Apex {
+ r := rr("edge.apps.example.", r53types.RRTypeA, a.IP)
+ r.Region = r53types.ResourceRecordSetRegion(a.Region)
+ r.SetIdentifier = aws.String(a.SetID)
+ r.HealthCheckId = aws.String(a.HealthCheckID)
+ f.records = append(f.records, r)
+ }
+ f.records = append(f.records, rr("other.apps.example.", r53types.RRTypeA, "192.0.2.9"), rr("edge.apps.example.", r53types.RRTypeTxt, `"ignore"`))
+ got, err := h.Steered().ApexTargets(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, latency().Apex) {
+ t.Fatalf("targets = %#v", got)
+ }
+ for _, in := range f.lists {
+ if aws.ToString(in.HostedZoneId) != "ZSTEER" {
+ t.Fatal("wrong zone")
+ }
+ }
+ if len(f.lists) != 4 || aws.ToString(f.lists[1].StartRecordIdentifier) != "us" {
+ t.Fatal("pagination lost record identifier")
+ }
+ h.config.SteeringZoneID = ""
+ if _, err := h.Steered().ApexTargets(context.Background()); err == nil {
+ t.Fatal("missing zone accepted")
+ }
+}
+
+func TestCreateZoneBrandingFailureCanRetry(t *testing.T) {
+ h, f, z := fixture()
+ ctx := context.Background()
+ boom := errors.New("change failed")
+ f.changeErr = boom
+ got, err := h.CreateZone(ctx, z.Domain, "key")
+ if got != z || !errors.Is(err, boom) {
+ t.Fatalf("failed branding: %v %v", got, err)
+ }
+ f.changeErr = nil
+ f.createErr = &r53types.HostedZoneAlreadyExists{}
+ f.zonePages = []*route53.ListHostedZonesOutput{{HostedZones: []r53types.HostedZone{{Id: aws.String(z.ID), Name: aws.String(z.Domain), CallerReference: aws.String("key")}}}}
+ got, err = h.CreateZone(ctx, z.Domain, "key")
+ if got != z || err != nil || len(f.batches) != 1 {
+ t.Fatalf("retry: %v %v", got, err)
+ }
+}
+
+func TestCreateZoneRefusesKeyForOtherDomain(t *testing.T) {
+ h, f, z := fixture()
+ f.createErr = &r53types.HostedZoneAlreadyExists{}
+ f.zonePages = []*route53.ListHostedZonesOutput{{HostedZones: []r53types.HostedZone{{Id: aws.String("ZOTHER"), Name: aws.String("other.example."), CallerReference: aws.String("key")}}}}
+ if _, err := h.CreateZone(context.Background(), z.Domain, "key"); err == nil {
+ t.Fatal("key reused across domains")
+ }
+ if len(f.lists) != 0 || len(f.batches) != 0 {
+ t.Fatal("reused key reached another zone")
+ }
+}
+
+func TestSetManagedAPIFailures(t *testing.T) {
+ for _, stage := range []string{"list", "change"} {
+ t.Run(stage, func(t *testing.T) {
+ h, f, z := fixture()
+ boom := errors.New("denied")
+ if stage == "list" {
+ f.listErr = boom
+ } else {
+ f.changeErr = boom
+ }
+ if err := h.SetManaged(context.Background(), z, plain()); !errors.Is(err, boom) {
+ t.Fatalf("lost API error: %v", err)
+ }
+ if len(f.batches) != 0 {
+ t.Fatal("failed API call mutated records")
+ }
+ })
+ }
+}
+
+func TestSetManagedGroupsTXTValues(t *testing.T) {
+ h, f, z := fixture()
+ m := plain()
+ m.TXT = []zonehost.TXT{
+ {Name: "_CARLOS-CHALLENGE.SHOP.EXAMPLE.", Value: `proof with "quotes"`},
+ {Name: "_carlos-challenge.shop.example", Value: "second proof"},
+ }
+ if err := h.SetManaged(context.Background(), z, m); err != nil {
+ t.Fatal(err)
+ }
+ r := f.records[len(f.records)-1]
+ want := rr("_carlos-challenge.shop.example.", r53types.RRTypeTxt, `"proof with \"quotes\""`, `"second proof"`)
+ if !reflect.DeepEqual(r, want) {
+ t.Fatalf("TXT = %#v", r)
+ }
+}
+
+func TestDeleteZoneBatchesWholeRecordSets(t *testing.T) {
+ h, f, z := fixture()
+ for i := 0; i < 1001; i++ {
+ f.records = append(f.records, rr(fmt.Sprintf("customer%d.shop.example.", i), r53types.RRTypeTxt, `"value"`))
+ }
+ if err := h.DeleteZone(context.Background(), z); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.batches) != 2 || len(f.batches[0]) != 1000 || len(f.batches[1]) != 1 || len(f.records) != 2 || len(f.deleted) != 1 {
+ t.Fatal("teardown failed to batch and remove all records")
+ }
+}
+
+func TestSteeredRefusesEmptyOrMalformedTargets(t *testing.T) {
+ for _, records := range [][]r53types.ResourceRecordSet{
+ nil,
+ {rr("edge.apps.example.", r53types.RRTypeA, "192.0.2.1", "192.0.2.2")},
+ {rr("edge.apps.example.", r53types.RRTypeA, "invalid")},
+ } {
+ h, f, _ := fixture()
+ h.config.SteeringZoneID = "ZSTEER"
+ h.config.SteeringHost = "edge.apps.example"
+ f.records = records
+ if _, err := h.Steered().ApexTargets(context.Background()); err == nil {
+ t.Fatalf("accepted %#v", records)
+ }
+ }
+}
diff --git a/internal/zonehost/zonehost.go b/internal/zonehost/zonehost.go
new file mode 100644
index 000000000..2fed2a66f
--- /dev/null
+++ b/internal/zonehost/zonehost.go
@@ -0,0 +1,96 @@
+// Package zonehost manages DNS zones for bought domains.
+package zonehost
+
+import (
+ "context"
+ "fmt"
+ "net/netip"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+type ApexTarget struct{ IP, Region, SetID, HealthCheckID string }
+type TXT struct{ Name, Value string }
+type ManagedSet struct {
+ Apex []ApexTarget
+ WWW bool
+ TXT []TXT
+}
+type Zone struct{ ID, Domain string }
+
+type Host interface {
+ // CreateZone is idempotent on key.
+ CreateZone(ctx context.Context, domain, key string) (Zone, error)
+ // DeleteZone destroys the zone's contents, including customer and email
+ // records, then deletes the zone. A missing zone is success.
+ DeleteZone(ctx context.Context, z Zone) error
+ // SetManaged replaces apex A, www A and the apex/www challenge TXT sets.
+ // All other name+type pairs belong to other writers and are left alone.
+ SetManaged(ctx context.Context, z Zone, m ManagedSet) error
+ Nameservers() []string
+}
+
+type ApexSource interface {
+ ApexTargets(ctx context.Context) ([]ApexTarget, error)
+}
+type staticApex []ApexTarget
+
+func StaticApex(ips []string) ApexSource {
+ targets := make(staticApex, len(ips))
+ for i, ip := range ips {
+ targets[i] = ApexTarget{IP: ip}
+ }
+ return targets
+}
+func (s staticApex) ApexTargets(ctx context.Context) ([]ApexTarget, error) {
+ return append([]ApexTarget(nil), s...), ctx.Err()
+}
+
+func (m ManagedSet) Validate() error {
+ if len(m.Apex) == 0 {
+ return fmt.Errorf("zonehost: at least one apex target is required")
+ }
+ latency := m.Apex[0].Region != ""
+ ids := map[string]bool{}
+ for _, a := range m.Apex {
+ ip, err := netip.ParseAddr(a.IP)
+ if err != nil || !ip.Is4() {
+ return fmt.Errorf("zonehost: invalid apex IPv4 address %q", a.IP)
+ }
+ if (a.Region != "") != latency {
+ return fmt.Errorf("zonehost: cannot mix plain and latency apex targets")
+ }
+ if latency {
+ if a.SetID == "" {
+ return fmt.Errorf("zonehost: latency target requires a set ID")
+ }
+ if ids[a.SetID] {
+ return fmt.Errorf("zonehost: duplicate set ID %q", a.SetID)
+ }
+ ids[a.SetID] = true
+ } else if a.SetID != "" || a.HealthCheckID != "" {
+ return fmt.Errorf("zonehost: plain targets cannot carry a set ID or health check")
+ }
+ }
+ return nil
+}
+
+// ValidateForZone applies the fixed TXT ownership boundary for both providers
+// and test fakes. Plan 1 owns only the apex and www proof records.
+func (m ManagedSet) ValidateForZone(z Zone) error {
+ if err := m.Validate(); err != nil {
+ return err
+ }
+ apex := strings.ToLower(strings.TrimSuffix(z.Domain, "."))
+ if apex == "" || z.ID == "" {
+ return fmt.Errorf("zonehost: zone ID and domain are required")
+ }
+ for _, txt := range m.TXT {
+ name := strings.ToLower(strings.TrimSuffix(txt.Name, "."))
+ if name != domains.ChallengeName(apex) && name != domains.ChallengeName("www."+apex) {
+ return fmt.Errorf("zonehost: TXT name %q is outside the managed challenge names", txt.Name)
+ }
+ }
+ return nil
+}
diff --git a/internal/zonehost/zonehost_test.go b/internal/zonehost/zonehost_test.go
new file mode 100644
index 000000000..0d8b7b627
--- /dev/null
+++ b/internal/zonehost/zonehost_test.go
@@ -0,0 +1,124 @@
+package zonehost_test
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/zonehost"
+ "github.com/carlosframework/platform/internal/zonehost/zonehosttest"
+)
+
+func TestManagedSetValidate(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ apex []zonehost.ApexTarget
+ bad bool
+ }{
+ {"empty", nil, true},
+ {"plain", []zonehost.ApexTarget{{IP: "192.0.2.1"}, {IP: "192.0.2.2"}}, false},
+ {"latency", []zonehost.ApexTarget{{IP: "192.0.2.1", Region: "eu-west-1", SetID: "eu"}, {IP: "192.0.2.2", Region: "us-east-1", SetID: "us"}}, false},
+ {"mixed", []zonehost.ApexTarget{{IP: "192.0.2.1", Region: "eu-west-1", SetID: "eu"}, {IP: "192.0.2.2"}}, true},
+ {"duplicate ID", []zonehost.ApexTarget{{IP: "192.0.2.1", Region: "eu-west-1", SetID: "same"}, {IP: "192.0.2.2", Region: "us-east-1", SetID: "same"}}, true},
+ {"missing ID", []zonehost.ApexTarget{{IP: "192.0.2.1", Region: "eu-west-1"}}, true},
+ {"invalid A", []zonehost.ApexTarget{{IP: "::1"}}, true},
+ {"plain ID", []zonehost.ApexTarget{{IP: "192.0.2.1", SetID: "unused"}}, true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if err := (zonehost.ManagedSet{Apex: tt.apex}).Validate(); (err != nil) != tt.bad {
+ t.Fatalf("Validate() = %v, want error %v", err, tt.bad)
+ }
+ })
+ }
+}
+
+func TestFakeSetManagedReplaces(t *testing.T) {
+ ctx := context.Background()
+ f := zonehosttest.New("ns1.brand.example.")
+ z, err := f.CreateZone(ctx, "shop.example", "key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ again, err := f.CreateZone(ctx, "shop.example", "key")
+ if err != nil || again != z {
+ t.Fatalf("retry: %v %v", again, err)
+ }
+ first := zonehost.ManagedSet{Apex: []zonehost.ApexTarget{{IP: "192.0.2.1"}}, WWW: true, TXT: []zonehost.TXT{{Name: "_carlos-challenge.shop.example", Value: "old"}}}
+ if err := f.SetManaged(ctx, z, first); err != nil {
+ t.Fatal(err)
+ }
+ next := zonehost.ManagedSet{Apex: []zonehost.ApexTarget{{IP: "192.0.2.2"}}}
+ if err := f.SetManaged(ctx, z, next); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(f.Managed[z.Domain], next) {
+ t.Fatalf("managed = %#v", f.Managed)
+ }
+ next.Apex[0].IP = "192.0.2.3"
+ if f.Managed[z.Domain].Apex[0].IP != "192.0.2.2" {
+ t.Fatal("fake retained caller slice")
+ }
+ bad := zonehost.ManagedSet{Apex: first.Apex, TXT: []zonehost.TXT{{Name: "verify.shop.example", Value: "customer"}}}
+ if err := f.SetManaged(ctx, z, bad); err == nil {
+ t.Fatal("unowned TXT accepted")
+ }
+ if err := f.DeleteZone(ctx, z); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.DeleteZone(ctx, z); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.Zones) != 0 || len(f.Managed) != 0 {
+ t.Fatal("zone was not removed")
+ }
+ ns := f.Nameservers()
+ ns[0] = "changed"
+ if f.Nameservers()[0] != "ns1.brand.example" {
+ t.Fatal("nameservers not isolated or normalized")
+ }
+}
+
+func TestFakeOneShotErrors(t *testing.T) {
+ ctx := context.Background()
+ f := zonehosttest.New()
+ boom := errors.New("injected")
+ f.CreateErr = boom
+ if _, err := f.CreateZone(ctx, "shop.example", "key"); !errors.Is(err, boom) {
+ t.Fatal(err)
+ }
+ z, err := f.CreateZone(ctx, "shop.example", "key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.SetErr = boom
+ m := zonehost.ManagedSet{Apex: []zonehost.ApexTarget{{IP: "192.0.2.1"}}}
+ if err := f.SetManaged(ctx, z, m); !errors.Is(err, boom) {
+ t.Fatal(err)
+ }
+ if err := f.SetManaged(ctx, z, m); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.Calls) != 4 {
+ t.Fatalf("calls = %v", f.Calls)
+ }
+}
+
+func TestStaticApex(t *testing.T) {
+ ips := []string{"192.0.2.1", "192.0.2.2"}
+ src := zonehost.StaticApex(ips)
+ ips[0] = "changed"
+ got, err := src.ApexTargets(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []zonehost.ApexTarget{{IP: "192.0.2.1"}, {IP: "192.0.2.2"}}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("targets = %v", got)
+ }
+ got[0].IP = "changed"
+ again, _ := src.ApexTargets(context.Background())
+ if !reflect.DeepEqual(again, want) {
+ t.Fatal("source retained returned slice")
+ }
+}
diff --git a/internal/zonehost/zonehosttest/fake.go b/internal/zonehost/zonehosttest/fake.go
new file mode 100644
index 000000000..db8a44378
--- /dev/null
+++ b/internal/zonehost/zonehosttest/fake.go
@@ -0,0 +1,109 @@
+package zonehosttest
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/zonehost"
+)
+
+type Fake struct {
+ Zones map[string]zonehost.Zone
+ Managed map[string]zonehost.ManagedSet
+ Calls []string
+ CreateErr, SetErr error
+
+ mu sync.Mutex
+ nameservers []string
+ keys map[string]zonehost.Zone
+ nextID int
+}
+
+var _ zonehost.Host = (*Fake)(nil)
+
+func New(ns ...string) *Fake {
+ f := &Fake{Zones: map[string]zonehost.Zone{}, Managed: map[string]zonehost.ManagedSet{}, keys: map[string]zonehost.Zone{}, nameservers: slices.Clone(ns)}
+ for i, n := range f.nameservers {
+ f.nameservers[i] = strings.TrimSuffix(n, ".")
+ }
+ return f
+}
+func (f *Fake) Nameservers() []string { return slices.Clone(f.nameservers) }
+func (f *Fake) CreateZone(ctx context.Context, domain, key string) (zonehost.Zone, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ domain = strings.ToLower(strings.TrimSuffix(domain, "."))
+ f.Calls = append(f.Calls, "create:"+domain)
+ if err := ctx.Err(); err != nil {
+ return zonehost.Zone{}, err
+ }
+ if domain == "" || key == "" {
+ return zonehost.Zone{}, fmt.Errorf("zonehost: domain and key are required")
+ }
+ if z, ok := f.keys[key]; ok {
+ if z.Domain != domain {
+ return zonehost.Zone{}, fmt.Errorf("zonehost: key belongs to another domain")
+ }
+ return z, nil
+ }
+ if f.CreateErr != nil {
+ err := f.CreateErr
+ f.CreateErr = nil
+ return zonehost.Zone{}, err
+ }
+ if _, ok := f.Zones[domain]; ok {
+ return zonehost.Zone{}, fmt.Errorf("zonehost: domain already has a zone")
+ }
+ f.nextID++
+ z := zonehost.Zone{ID: fmt.Sprintf("zone-%d", f.nextID), Domain: domain}
+ f.Zones[domain] = z
+ f.keys[key] = z
+ return z, nil
+}
+func (f *Fake) SetManaged(ctx context.Context, z zonehost.Zone, m zonehost.ManagedSet) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "set:"+z.Domain)
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := m.ValidateForZone(z); err != nil {
+ return err
+ }
+ if f.Zones[z.Domain] != z {
+ return fmt.Errorf("zonehost: zone does not exist")
+ }
+ if f.SetErr != nil {
+ err := f.SetErr
+ f.SetErr = nil
+ return err
+ }
+ m.Apex = slices.Clone(m.Apex)
+ m.TXT = slices.Clone(m.TXT)
+ f.Managed[z.Domain] = m
+ return nil
+}
+
+// DeleteZone destroys the fake zone and all its records; absence is success.
+func (f *Fake) DeleteZone(ctx context.Context, z zonehost.Zone) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls = append(f.Calls, "delete:"+z.Domain)
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if f.Zones[z.Domain] != z {
+ return nil
+ }
+ delete(f.Zones, z.Domain)
+ delete(f.Managed, z.Domain)
+ for key, stored := range f.keys {
+ if stored == z {
+ delete(f.keys, key)
+ }
+ }
+ return nil
+}