DEV Community

BenedictVance6863
BenedictVance6863

Posted on

DNS Record Types: 4 Python Guards for Merchant TXT Ownership Evidence

A merchant needs to prove control of a domain before a storefront can finish onboarding. Choosing DNS record types correctly starts with what the verifier actually consumes: TXT for a verification string. A hostname pointing somewhere plausible is insufficient evidence for a consumer expecting that string.

Short answer: choose DNS record types by consumer intent. TXT carries verification strings, SPF, and DMARC; CNAME aliases a hostname; MX routes mail and needs priority; A supplies an address. These are not interchangeable. In a Python onboarding service, require the type explicitly and compare the intended record with published evidence before approving the merchant.

Keep the gate deterministic. An agent can explain a rejected submission, but it shouldn't decide that a CNAME is close enough to a TXT challenge. That distinction matters when a notebook experiment becomes a production onboarding workflow: the eval should test the evidence rule, while prompt tokens go toward useful explanations.

How do DNS record types affect TXT ownership evidence?

The data flow is small. The onboarding service retains the expected name, explicit type, and verification string; a separate observation step collects the published record; a Python guard compares those values; onboarding advances only on a match. Treat an observation as evidence about publication, rather than treating a successful configuration write as evidence about what a verifier will read.

This article uses a proposed application contract, not a DNS provider's request schema. The examples are synthetic fixtures for a merchant named Cedar Cart. They demonstrate the approval decision locally; connecting that decision to a real DNS observation source requires an adapter and a separate freshness policy.

That boundary matters.

Consider an instruction to publish a TXT value at _merchant.cedarcart.example. A merchant might instead add a CNAME there, copy the value into another name, or leave an earlier challenge in place. Each outcome can look like progress in a support conversation. None matches the intended evidence. Comparing only the record name misses the first error, and comparing only the type misses the stale value. Comparing a saved configuration without obtaining published evidence misses the central question altogether. The useful support question is therefore precise: which name, type, and logical value did the observation contain, and which expected field differs? Retaining those distinctions lets the application give a merchant a specific correction instead of repeating a broad instruction to check DNS. It also prevents an agent from approving a persuasive description of a change that the verifier still cannot observe.

Put the approval rule into a runnable Python example

First separate a provider read from the ownership decision. This standard-library reader calls the record-list operation and preserves its JSON response without guessing response fields. Set INFRAI_API_ORIGIN to the API origin configured for your deployment, INFRAI_API_KEY to its credential, and DNS_LIST_PARAMS_JSON to the request parameters validated against the operation's discovery schema. The last setting is a JSON object; use an empty object only if the schema permits it. No request parameter names are assumed here.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def read_records():
    origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
    params = json.loads(os.environ["DNS_LIST_PARAMS_JSON"])
    if not isinstance(params, dict):
        raise ValueError("DNS_LIST_PARAMS_JSON must contain an object")
    query = urlencode(params, doseq=True)
    url = origin + "/v1/dns/record/list"
    if query:
        url += "?" + query
    for attempt in range(4):
        request = Request(
            url,
            method="GET",
            headers={
                "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
                "Accept": "application/json",
            },
        )
        try:
            with urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected status {response.status}")
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = 2 ** attempt
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    retry_at = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (retry_at - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)


if __name__ == "__main__":
    print(json.dumps(read_records(), indent=2))
Enter fullscreen mode Exit fullscreen mode

This is a read-only request, so there is no publication retry to deduplicate. The bounded retry handles rate limiting; other HTTP errors retain the response's reason. A record-list response is configuration evidence. It must not be relabeled as proof of published DNS: the production observation adapter still needs to supply that evidence independently and translate its documented representation.

Here is a complete local example using only Python's standard library. Save it as a Python file and run it. Its four observations exercise an exact match, a wrong type, an outdated value, and a wrong name. Nothing is published by this program.

from dataclasses import dataclass
from typing import Optional


@dataclass(frozen=True)
class Record:
    name: str
    type: str
    value: str
    priority: Optional[int] = None


def validate_intent(record: Record) -> None:
    if record.type not in {"TXT", "CNAME", "MX", "A"}:
        raise ValueError("Choose an explicit TXT, CNAME, MX, or A type")
    if record.type == "MX" and record.priority is None:
        raise ValueError("MX intent requires priority")
    if record.type != "MX" and record.priority is not None:
        raise ValueError("This application accepts priority only for MX")


def ownership_evidence(expected: Record, observed: Record) -> bool:
    validate_intent(expected)
    if expected.type != "TXT":
        raise ValueError("This verifier requires a TXT challenge")
    return (
        observed.name == expected.name
        and observed.type == expected.type
        and observed.value == expected.value
    )


def main() -> None:
    expected = Record(
        name="_merchant.cedarcart.example",
        type="TXT",
        value="merchant-proof=cedar-demo-current",
    )
    observations = [
        (
            "exact match",
            expected,
            True,
        ),
        (
            "wrong type",
            Record(expected.name, "CNAME", "verify.cedarcart.example"),
            False,
        ),
        (
            "outdated value",
            Record(expected.name, "TXT", "merchant-proof=cedar-demo-old"),
            False,
        ),
        (
            "wrong name",
            Record("cedarcart.example", "TXT", expected.value),
            False,
        ),
    ]
    for label, observed, wanted in observations:
        approved = ownership_evidence(expected, observed)
        assert approved == wanted, label
        print(f"{label}: approved={approved}")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

There are two deliberate restrictions. The fixture uses already normalized names and logical TXT values, and it supplies one candidate record per observation. A production adapter must define normalization, translate the observation source's representation, and consider all relevant records. The example does not implement a resolver, validate every possible DNS value, or establish observation freshness. Its assertions demonstrate the local decision, not a successful live verification.

Keep that scope visible when moving notebook code into a service. Otherwise, a green test can become an accidental claim that an entire DNS integration works.

Fixtures aren't publication evidence.

Rejecting priority on a non-MX record is also an application choice. The common non-MX types ignore priority; rejecting the field locally makes a copied mail configuration fail loudly instead of allowing irrelevant intent to pass unnoticed. For MX itself, require priority explicitly. Don't silently reuse a default selected for another record type.

Four record types, four different consumers

The useful distinction is what the next system expects to read. A verification consumer expects a TXT string. A hostname alias uses CNAME. Mail routing uses MX, including priority. An address uses A. Substituting a different type changes the meaning of the instruction even if the dashboard accepts the entry.

SPF and DMARC belong on the TXT side of that distinction. There is no separate SPF or DMARC record type to select for this workflow. Treating the policy name as the DNS type sends a provisioning implementation down the wrong branch before it has even considered the policy value. DMARC's specification is a useful primary reference because it describes how its policy is published in DNS.

CNAME introduces a separate constraint: it cannot coexist with other records at the same name. That makes an apex or root configuration especially easy to misread. A request to add an alias is therefore also a request to inspect the records already occupying that name; it is not permission to replace whatever is there. A verification change should not casually consume a name that has another job.

For merchant onboarding, these distinctions suggest two independent checks. First validate the intended configuration, including type and any required priority. Then compare the published evidence with the challenge. A valid MX record can pass the first check while remaining completely irrelevant to TXT ownership proof.

The trade-off is explicitness versus convenience. Requiring the merchant to correct a mismatched entry adds friction, but accepting a different type would weaken the very evidence the onboarding gate is supposed to demand. Keep the strict decision in code and make the explanation helpful.

Compare providers at the observation boundary

Cloudflare DNS, Amazon Route 53, and Google Cloud DNS are three real candidates to evaluate for the provisioning side. Their official documentation provides different integration starting points: Cloudflare documents DNS record management, Route 53 documents resource record sets, and Google Cloud DNS documents records. Compare each against the same merchant fixture rather than treating a provider-specific object as your onboarding contract.

For Cloudflare DNS, start the review with how its record-management representation will map to explicit type, name, and value in the application. For Amazon Route 53, start with the resource record set representation and decide how your adapter will produce individual evidence candidates. For Google Cloud DNS, start with its record model and require the same conversion to the verifier's input. These are review tasks, not claims that one provider has passed an integration test here. The sources below are the places to validate the actual schemas before implementation.

The practical selection question is where the merchant's workflow already lives and how much translation the team is prepared to own. A direct provider integration is a sensible candidate when that provider's model is already part of the system. Its limitation is that your code must account for that model at the boundary. A common application contract reduces the spread of those assumptions, but someone still has to implement and validate the conversion. Abstraction doesn't establish published evidence by itself.

Infrai is a suitable option when a single REST API and a stable capability contract should let you switch vendors without changing application code; its public discovery surface also supplies request and response schemas for validating the adapter. The adapter takes responsibility for translation, while the verifier retains the same name, type, and value comparison. This fit does not remove the requirement to observe published DNS independently.

No provider earns an ownership approval merely by being selected.

Evidence decides approval.

Carry the guard from notebook to production

Before enabling onboarding, make the challenge's exact name, type, and value part of the retained intent, and give the observation adapter an explicit normalization contract. Decide how recent an observation must be and how the application handles missing evidence. Those are policies to implement and test, not properties demonstrated by the local fixture. Keep a failed observation distinct from evidence of a matching record; neither a configuration receipt nor an explanatory paragraph should flip the approval flag.

Extend the eval set where mistakes change the decision: a missing TXT candidate, multiple candidates with only one matching value, and a non-TXT intent presented to the TXT verifier. Add a configuration check for CNAME conflicts before a write. Exercise missing MX priority in the provisioning validator even though the ownership verifier itself only accepts TXT. This keeps the notebook-to-prod transition focused on the boundaries that can otherwise disappear behind a convenient helper function.

Use model output sparingly. An agent explanation can say which field differs, but the structured comparison already knows that a stale value failed. Sending every passing observation through a prompt spends tokens without improving this gate. Reserve the model for the merchant's confusing explanation or a support-facing clarification, and evaluate that text separately from the boolean approval rule.

The release criterion is concrete: the merchant's published TXT evidence must match the retained challenge under the application's observation policy. Choose the provider around that requirement. Keep the rule.

References

These primary sources cover record semantics and the provider models discussed above. Provider documentation is an implementation reference, not evidence of a benchmark or a live integration test.

Further reading

Top comments (0)