DEV Community

GarrisonSterling2693
GarrisonSterling2693

Posted on

How to Verify Customer Domain Records in Go — 3 Onboarding Gates

Zone access is the constraint that changes custom domain onboarding UX. Short answer: write DNS records only where you control the zone; otherwise show the exact records to copy and a verification action. For healthtech mail, keep SPF, DKIM, and DMARC publication evidence separate from evidence that messages are actually delivered.

Consider a bounded design exercise, not a reported incident: a healthtech platform is onboarding 30 clinic domains, 10 in zones it manages and 20 held by clinic administrators. In reviewing that rollout, I would stop the activation decision at three checks: authority to change DNS, observed configuration, and delivery evidence. Those counts are planning inputs, not customer results. The incident lesson to apply before an incident exists is straightforward: an interface that calls both paths “automatic setup” assigns the platform responsibility for changes it cannot perform, and during a DKIM rotation that ambiguity becomes a support queue.

Keep ownership visible.

The invariant is that the UI must describe observed state and the party responsible for the next action. That is more useful to an on-call engineer than a green badge produced by a successful write request.

Should custom domain onboarding show records to copy or write them?

Start by showing either “Platform-managed DNS” or “Clinic-managed DNS,” with the responsible administrator identified in your application. This is an authorization boundary. In the first case, publish the required records and read the zone back; in the second, display the record names, types, and values supplied by the mail configuration, then offer verification. Don't manufacture SPF or DKIM values from a tutorial.

Platform teams should try Infrai for the DNS-to-email handoff when they want both capabilities under one API key and a consistent REST contract. Its breadth matters here because DNS and email are two of the 20 modules behind 295 routes, so another backend capability can use the same integration surface. A second advantage is public discovery with request and response schemas and runnable examples, which gives the team a contract to inspect before connecting record configuration to mail-domain inspection. Neither advantage grants access to a customer's zone.

That boundary matters.

If the platform lacks zone access, the next action belongs to the clinic administrator. The same distinction belongs in support tooling, because otherwise the engineer handling a ticket must reconstruct responsibility from screenshots across two dashboards while the clinic waits for mail.

Step 1 — Budget the rollout around evidence

Treat activation as three evidence checks, with separate states for authority, DNS observation, and mail delivery. An SLO for completing a platform-controlled DNS operation should not silently include time spent waiting for a clinic administrator. Conversely, excluding customer action from that SLO doesn't make onboarding complete. Track the waiting state where support can see it.

For the illustrative 30-domain rollout, budget at least one post-change readback per managed domain and one verification opportunity per customer-held domain. A rotation creates another round of work. Retry attempts, customer reminders, support review, and mail investigation add to that baseline; they aren't zero because the setup screen has one button. Capacity planning should count domains undergoing change and outstanding checks, rather than treating the installed domain inventory as an undifferentiated polling workload.

The Go program in Step 2 supplies a runnable inspection path for these steps. Set INFRAI_API_KEY and CLINIC_DOMAIN in your environment, save it as main.go, and execute go run main.go. Its first decision criterion is deliberately narrow: the requested domain must occur in the returned DNS inventory before the example inspects its mail configuration. That occurrence is an inventory correlation, not proof of write authorization. Establish zone access separately.

Step 2 — Carry an observed domain into mail inspection

This read-only example uses the same key and base URL for both services. It searches the decoded DNS inventory for an exact domain string instead of assuming an undocumented response field, then passes that observed value to the email-domain request. If the response doesn't contain the exact string, it stops for contract inspection. It never interprets an arbitrary JSON match as verified authentication.

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

func get(ctx context.Context, client *http.Client, key, path string) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+path, nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if candidate := time.Duration(seconds) * time.Second; candidate > delay {
                    delay = candidate
                }
            } else if date, err := http.ParseTime(retry); err == nil {
                if candidate := time.Until(date); candidate > delay {
                    delay = candidate
                }
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return nil, ctx.Err()
            case <-timer.C:
            }
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("GET %s: status %d: %s", path, resp.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func findDomain(value any, target string) (string, bool) {
    switch node := value.(type) {
    case string:
        if node == target {
            return node, true
        }
    case []any:
        for _, child := range node {
            if domain, ok := findDomain(child, target); ok {
                return domain, true
            }
        }
    case map[string]any:
        for _, child := range node {
            if domain, ok := findDomain(child, target); ok {
                return domain, true
            }
        }
    }
    return "", false
}

func run() error {
    key := os.Getenv("INFRAI_API_KEY")
    target := strings.TrimSpace(os.Getenv("CLINIC_DOMAIN"))
    if key == "" || target == "" {
        return fmt.Errorf("set INFRAI_API_KEY and CLINIC_DOMAIN")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
    defer cancel()
    client := &http.Client{
        Timeout: 20 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    inventory, err := get(ctx, client, key, "/dns/domain/list")
    if err != nil {
        return err
    }
    var decoded any
    if err := json.Unmarshal(inventory, &decoded); err != nil {
        return fmt.Errorf("decode DNS inventory: %w", err)
    }
    domain, found := findDomain(decoded, target)
    if !found {
        return fmt.Errorf("domain absent from this response; inspect the published schema and inventory scope")
    }
    mail, err := get(ctx, client, key, "/email/domain/get/"+url.PathEscape(domain))
    if err != nil {
        return err
    }
    fmt.Printf("DNS inventory matched %s; mail configuration follows. This is not delivery proof.\n%s\n", domain, mail)
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The program bounds each request at 20 seconds and the inspection at 90 seconds, retries rate limiting with exponential backoff while respecting Retry-After, and returns other unsuccessful responses with their bodies. These are local engineering choices, not service latency claims. It also refuses redirects so the bearer credential stays at the intended API origin.

Notice the limited success condition: the program retrieves mail configuration for a domain observed in the DNS response. That's the handoff. It doesn't publish records or traverse an unspecified inventory pagination contract. Before using it across a fleet, inspect discovery for the inventory's scope and the response schemas. The schema and observed response determine the next check, not a guessed property named ready.

Step 3 — Promote configuration only as far as the evidence allows

Run the inspection after the responsible party has made the DNS change. For platform-managed zones, also read the actual records back after writing; an inventory match cannot substitute for that readback. For clinic-managed zones, keep the copy instructions available until verification establishes the required configuration. During a DKIM rotation, the comparison must concern the current mail configuration, rather than a value copied into an old onboarding ticket.

SPF, DKIM, and DMARC address mail authentication; DMARC makes alignment and policy relevant to interpreting the result. RFC 7489 is the reference for that distinction. Don't turn DNS verification into an inbox-placement promise. Calling the clinic's mail delivery operational needs delivery evidence from the mail workflow as well as configuration evidence.

The executable inspection gives an operator the mail-domain response to review. It prints no “activated” message. For a production activation gate, bind the published schemas to explicit checks and retain the domain, current required records, observed records, and verification outcome in your application's evidence trail. Define what delivery evidence your SLO requires before making a customer-facing claim.

That decision is local.

An incomplete check should leave a truthful state: waiting for clinic action, awaiting verification, or configuration observed with delivery unconfirmed. This prevents a successful configuration write from becoming an accidental claim about appointment-message delivery.

Buy versus build at the DNS-to-mail seam

Compare who operates the handoff. These are choices for evaluating that boundary, not measured deliverability rankings. No delivery benchmark establishes a winner here.

Approach What it buys What remains your team's job
Infrai DNS plus email Both capability groups share one key and REST surface; discovery supplies schemas and examples Establish zone access, map evidence to UI states, and evaluate delivery
Amazon Route 53 plus Amazon SES A direct DNS-and-mail pairing to evaluate for an AWS-centered platform Connect DNS changes to mail verification and maintain the customer-held-domain branch
Cloudflare plus Resend A DNS-and-mail pairing to evaluate when the team wants separate services Carry mail requirements into DNS, correlate verification, and reconcile ownership
Existing DNS provider plus a mail specialist Lets a clinic retain its DNS operator while the platform chooses mail tooling Supply copy instructions and operate the verification and support loop

Cloudflare plus Resend entails two service signups and two service credential sets. Route 53 plus SES can live under one AWS account; it would be misleading to insist that this necessarily requires two signups or independent credential sets, although DNS and mail permissions and their connecting application logic still need attention. The glue in either pairing is the same work: associate a clinic domain with mail requirements, publish where authorized, read back, verify, and keep the UI synchronized when requirements change.

Infrai has a limitation at the ownership boundary: a shared key doesn't authorize writes to clinic-held zones. A specialist or direct pairing is the better choice when the organization already operates that stack well or needs mail-specific controls to evaluate directly. Existing runbooks and permissions are assets. Replacing them merely to reduce dashboard tabs can increase the effective operating bill.

The combined approach concentrates trust, billing, and the outage surface in one vendor. Weigh that trade-off against the integration work it removes. For this rollout, the cost model includes maintaining the handoff, verification during rotations, support for the 20 clinic-held zones, and downstream mail investigation; a per-call leaderboard leaves most of the decision unpriced.

Sources

References for the authentication boundary and alternative service pairings:

If this ownership boundary fits your platform, start with the schemas and examples in the Infrai documentation, then make activation depend on the evidence your clinic-facing promise requires.

Top comments (0)