DEV Community

EthanBrooks1647
EthanBrooks1647

Posted on

Merchant DMARC Policy Stages — Scheduled Gates During Registrar API Migration

Move the zone behind an ownership-aware adapter, keep DMARC policy stages in configuration, and reverify the sending domain before advancing exactly one stage on each scheduled run. For an e-commerce platform leaving a registrar-specific API, the deciding constraint is who can authorize the DNS change: the merchant or the platform. A scheduler cannot manufacture that authority.

TL;DR: Separate zone migration from policy enforcement. Store each domain's current stage, require fresh verification before promotion, and preserve an observation interval between stages. A customer-owned zone needs an explicit merchant-controlled change boundary; a platform-owned zone can use the platform's authorized writer.

The operational objective is continuity for order receipts and account messages while DNS administration changes. Enforcement is a separate decision. Advancing because the migration job finished would confuse two different signals.

Decision: separate ownership from enforcement

Use a per-domain rollout ledger alongside the stage configuration. The ledger identifies the sending domain, zone owner, current stage, last accepted transition, and any pause reason. These are application fields, not provider request parameters. For the illustrative merchant domain shop.example, the configured sequence is none, quarantine, reject. Those are the three DMARC policy values described in RFC 7489; the schedule and observation criteria belong to the operator.

Keep ownership explicit. A merchant can own a sending domain while the platform operates its transactional email. That arrangement doesn't automatically authorize the platform to edit the merchant's DNS. During migration, the rollout must identify the authorized writer for the destination zone before requesting any stronger policy. Otherwise the scheduler can prepare a perfectly valid decision that nobody is entitled to apply.

Record the pause.

A paused customer-owned domain should remain visible with its current policy and required action. Platform-owned domains can follow the same state machine with a different authorization boundary. This preserves one rollout model without pretending that every merchant has delegated the same rights.

The focus here is transactional-message continuity: an authentication gate protects the next policy change, while observation between changes gives the operator a chance to examine the consequences for legitimate mail. Authentication alone doesn't establish that every legitimate sender has been inventoried. For commerce, consider the streams actually in use, including receipts and account messages, before enforcement becomes more restrictive.

What must we reverify before advancing a DMARC policy?

The central invariant is one accepted transition per domain per scheduled observation window. Reverification must precede that transition. Never loop through all remaining stages because one run obtained a successful verification result; the waiting period is part of the decision.

Recheck SPF and DKIM because either can regress after an earlier verification. DMARC evaluates authentication alignment, so treat a generic domain-exists result as insufficient evidence for enforcement. RFC 7489 explains the distinction. The gate should also require the operator's observation criteria to be satisfied, with unresolved legitimate sending streams causing a pause. A successful DNS write isn't a deliverability verdict.

The failure boundaries need separate treatment. If verification cannot complete, retain the current stage. If the DNS write has an uncertain outcome, reconcile the record before retrying. If the write succeeds but recording the new stage fails, the next run must compare desired policy with observed policy before attempting another transition. A durable transition identifier and an exclusive per-domain claim belong around this operation; an in-memory flag cannot protect against overlapping workers. Record the scheduler's observation-window identifier as well, so a duplicate invocation cannot consume another stage within that window. Consider a hypothetical duplicate delivery for shop.example: the first worker applies quarantine, then the duplicate sees quarantine as the current stage. Without a persisted window identifier, that duplicate could mistake reject for a fresh, eligible transition. The domain lock alone wouldn't prevent this sequential error. Rollback is a configuration change to the desired stage, followed by the same authorized application path. It isn't proof that receivers have already observed the replacement record. Keep observation and application distinct in the ledger.

For compliance review, store the domain, authorization decision, and transition evidence needed to explain the change. Message bodies and recipient addresses don't belong in a DNS rollout ledger.

Compare the seam between DNS and email

The useful comparison is who owns the zone, who owns the mail account, and which system connects their evidence. These are integration choices; the application still owns its staged rollout.

Integration choice Ownership fit Handoff the application must own Limitation and valid use case
Amazon Route 53 with Amazon SES A platform operating its zones and email within an AWS account boundary Associate DNS changes with the appropriate email identity, schedule checks, and persist stage transitions Two services still need explicit authorization and orchestration; appropriate where that AWS boundary already matches operations
Cloudflare DNS with Resend A merchant or platform keeping DNS and email in separate provider accounts Map the zone to the email domain and coordinate two credential sets Separate administration increases handoff work; useful when DNS ownership should remain independent of the mail service
Cloudflare DNS with Amazon SES A DNS owner retaining Cloudflare while the application uses an AWS mail identity Connect the DNS authorization boundary to email verification and rollout state Cross-provider reconciliation stays in the application; useful when a zone move should not dictate a mail-provider move
Infrai An authorized operator wanting DNS and email capabilities under one consistent contract Connect record evidence to the sending-domain check with the same key and base URL Its 295 routes across 20 modules reduce integration surfaces, and public discovery exposes request and response schemas; appropriate where a combined operating boundary fits

Route 53 plus SES means two service integrations, but it needn't mean two signups or two independent credential sets: the account and permission design determine that. Cloudflare plus Resend normally means two provider signups and two credential sets. Either combination still needs application glue for ownership mapping, fresh checks, retries, and a durable stage ledger.

Breadth behind a consistent API helps at this seam because adding email checks to DNS automation needn't introduce another integration contract. Public schema discovery also gives the adapter a concrete request and response contract to inspect. The combined approach means one vendor to trust, one bill, and concentrated operational dependency. Choose separate providers where independent ownership is the stronger requirement.

Critical path: carry DNS evidence into the mail check

The following Python program is a runnable, read-only handoff probe. It fetches DNS records, derives the configured sending domain from an exact matching DNS name in that response, then fetches that email domain using the same credentials and base URL. It prints evidence rather than declaring a policy safe to advance.

This narrow boundary matters: an arbitrary successful JSON response isn't an SPF, DKIM, or DMARC verdict. The production adapter must interpret the documented response schema and perform the required sending-domain reverification before it authorizes a write. The probe validates that the two sides of the migration refer to the same domain; it isn't the promotion worker.

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

BASE_URL = os.environ["INFRAI_BASE_URL"].rstrip("/")
API_KEY = os.environ["INFRAI_API_KEY"]
DOMAIN = os.environ["SENDING_DOMAIN"].lower().rstrip(".")
STAGES = ("none", "quarantine", "reject")


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                deadline = parsedate_to_datetime(value)
                return max(0.0, (deadline - datetime.now(timezone.utc)).total_seconds())
            except (TypeError, ValueError, OverflowError):
                pass
    return min(30.0, 2 ** attempt) + random.random()


def get_json(path):
    for attempt in range(5):
        request = Request(
            BASE_URL + path,
            headers={"Authorization": "Bearer " + API_KEY},
            method="GET",
        )
        try:
            with urlopen(request, timeout=30) as response:
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
    raise RuntimeError("Retry budget exhausted")


def string_values(value):
    if isinstance(value, str):
        yield value
    elif isinstance(value, dict):
        for child in value.values():
            yield from string_values(child)
    elif isinstance(value, list):
        for child in value:
            yield from string_values(child)


def main():
    if not DOMAIN or "/" in DOMAIN:
        raise ValueError("SENDING_DOMAIN must be a DNS name")
    current_stage = os.environ["CURRENT_DMARC_POLICY"]
    current_index = STAGES.index(current_stage)
    candidate = STAGES[min(current_index + 1, len(STAGES) - 1)]
    dns_snapshot = get_json("/dns/record/list")
    matches = {
        name.lower().rstrip(".")
        for name in string_values(dns_snapshot)
        if name.lower().rstrip(".") in {DOMAIN, "_dmarc." + DOMAIN}
    }
    if not matches:
        raise RuntimeError("No exact domain evidence; pause for schema-aware inspection")
    dns_name = sorted(matches, key=len)[0]
    sending_domain = dns_name.removeprefix("_dmarc.")
    email_snapshot = get_json("/email/domain/get/" + quote(sending_domain, safe=""))
    print(json.dumps({
        "sending_domain": sending_domain,
        "current_policy": current_stage,
        "candidate_policy": candidate,
        "dns_evidence": dns_snapshot,
        "email_evidence": email_snapshot,
        "promotion_authorized": False,
    }, indent=2))


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

Use Python 3.9 or later. Set INFRAI_BASE_URL to the documented versioned API base, INFRAI_API_KEY to the key, SENDING_DOMAIN to the merchant sending domain such as shop.example, and CURRENT_DMARC_POLICY to its recorded policy. The two paths are relative to that versioned base. Both requests are GET operations, so this probe makes no policy writes. Keep its output in the operator's controlled environment because account-level DNS evidence may include domains beyond the one being migrated.

The recursive string scan avoids inventing response field names. Its exact-match test is only a diagnostic association check; it doesn't establish ownership, successful verification, or record correctness. A schema-aware production adapter should select the intended record and reject ambiguous matches.

No match means pause.

After that handoff, the scheduled worker has a short decision sequence: acquire the domain's transition claim, read its current stage, reverify the sending domain, evaluate the observation gate, and apply at most the next configured policy through the authorized zone writer. Persist the accepted transition and release the claim. Reads may be retried with backoff; write retries also require idempotency and reconciliation. Those responsibilities belong in the worker rather than in a diagnostic probe that cannot justify an enforcement decision.

Rejected option: couple migration completion to enforcement

Reject a job that imports the registrar's records and immediately advances DMARC to reject. Migration completion says nothing about the observation interval between policy stages, and a verification performed before the migration can become stale. The shortcut is especially unsuitable when merchants retain DNS ownership and the platform cannot independently authorize the next update.

A registrar-specific integration still has a valid use case: a merchant-controlled zone that is staying with that registrar and has a supported, authorized operating process. Retaining that integration can avoid an unnecessary zone move.

The verification gate remains.

For this migration, the acceptance rule is concrete: the new adapter can identify the domain, the authorized owner can apply the intended policy, reverification is fresh, and a scheduled run advances no more than one stage. Until those conditions hold, preserve the current stage and expose the pause.

References

Top comments (0)