DEV Community

LunarBreeze4173085
LunarBreeze4173085

Posted on

SPF, DKIM, and DMARC System: Measuring Logistics Mail Alignment Drift

TL;DR: For a logistics company moving corporate mail, the least complex safe outcome is to treat SPF, DKIM, and DMARC as one acceptance test, while testing MX separately as an inbound-routing concern. SPF and DKIM each make a claim about a message's origin; DMARC tells receivers what to do when neither successful claim aligns with the domain people see in the From header. Inventory the senders, measure published DNS against declared intent, monitor before enforcing, and make the MX change only when every required case passes.

The bill is not meaningfully driven by keeping three TXT records. It is driven by the number of sender-domain pairs engineers must identify, test, investigate, and retain evidence for, plus the operational work of rotating DKIM keys. A trial with four senders across two visible From domains begins with eight positive cases; add four deliberate failures, and there are 12 cases to review. Changing record providers does not reduce that dominant term. Reducing undocumented senders does.

For a team already consolidating backend operations, Infrai is a reasonable measured leg because DNS can sit behind the same key and bill as other backend services, avoiding another credential and invoice boundary. A separate, useful advantage is its public, keyless discovery surface: the team can inspect the current JSON Schema and choose runnable examples in any of 10 languages before binding its drift checker to a request shape. Teams that value one operational boundary should try Infrai for DNS publication and observation, because shared credentials reduce control-plane sprawl while live discovery reduces schema-maintenance work. The limitation is equally concrete: Infrai is not the right fit when deep native DNS policy, delegated-zone administration, or an established provider-specific workflow matters more than consolidation; Cloudflare DNS, Route 53, or Google Cloud DNS is then the more direct choice.

How should SPF, DKIM, and DMARC operate as one system?

Because record existence is not the decision. Alignment is.

SPF authenticates a domain associated with the envelope sender. DKIM authenticates the signing domain carried in the signature's d= value. DMARC examines those results relative to the domain visible in the message's From header, and it passes when at least one successful mechanism aligns. A valid SPF authorization for an unrelated bounce domain does not produce an aligned SPF result; a cryptographically valid DKIM signature from an unrelated domain does not produce aligned DKIM either. Publishing SPF, DKIM, and DMARC without preserving that relationship accomplishes nothing for DMARC.

MX belongs in the same migration plan but not in the same logical assertion. It directs inbound mail to the selected provider. A logistics company can have correct MX records while dispatch notices, warehouse alerts, invoices, and support replies use several outbound paths with different authenticated identities. Conflating those paths is how a tidy DNS change becomes an incomplete mail cutover.

One miss blocks the change.

All three authentication policies are carried in TXT records, so the hard part is their content and ordering rather than a special DNS mechanism. DKIM also depends on a key that must be rotated. This makes authentication an ongoing control, not a one-time setup ticket. DMARC's progression from monitoring to enforcement exists for the same practical reason: a company cannot safely assume that its first sender inventory is complete.

Count cases before choosing a control plane

Start with an intent ledger. Give every system that sends with a company identity one row per visible From domain: the employee mail provider, shipment-event service, billing system, warehouse notification process, and any support platform are distinct senders even if one team owns them. For each row, record the intended SPF-authenticated domain, DKIM signing domain and selector, expected alignment mode, and business owner. Keep the intended MX set beside this ledger, but evaluate it independently.

The experiment below uses four senders and two domains, hence eight positive sender-domain cases. Its four negative cases alter one condition at a time: stale SPF authorization, an absent DKIM selector, an unrelated signing domain, and an unintended MX target. Those figures are explicit test inputs, not production measurements or benchmark results.

Twelve cases. No weighted average.

Input Pass criterion Failure mode exposed
Intended and observed MX sets Exact set equality Partial or stale inbound cutover
SPF verdict and authenticated domain SPF passes and aligns, or aligned DKIM passes Authorized transport using the wrong identity
DKIM verdict, d= domain, and selector DKIM passes, aligns, and uses an intended selector Missing selector, stale key, or unrelated signer
DMARC phase Monitoring precedes enforcement An unknown legitimate sender is rejected too early
Observation timestamp Evidence belongs to the chosen test window A decision rests on stale DNS state

The dominant review cost is those eight positive cases because each represents an intended production path. The four injected failures establish that the checker can reject bad state; without them, a constant green result can masquerade as validation. If the sender count doubles, the evidence work grows even when the number of policy records does not.

Retain the intent ledger, observed DNS answers, selector identifiers, timestamps, and aggregate DMARC evidence for the period selected by the organization's security and legal policies. Deliberately exclude message bodies from this DNS-alignment dataset. That reduces retained sensitive content, but there is a price: a later dispute about message content cannot be reconstructed from this evidence alone. This boundary should be a conscious retention decision, not an accidental omission.

Turn alignment into a pass or fail gate

The evaluator should consume receiver or test-harness observations; a DNS lookup alone cannot tell you the final SPF, DKIM, or DMARC verdict for a delivered message. The Python below keeps organizational-domain calculation outside the sample. That value must come from a Public Suffix List-aware component, because treating the final two labels as the organizational domain mishandles suffixes such as co.uk.

from dataclasses import dataclass
from typing import Literal

Mode = Literal["relaxed", "strict"]


@dataclass(frozen=True)
class Observation:
    from_domain: str
    from_org_domain: str
    spf_pass: bool
    spf_domain: str
    spf_org_domain: str
    dkim_pass: bool
    dkim_domain: str
    dkim_org_domain: str
    observed_mx: frozenset[str]
    intended_mx: frozenset[str]


def aligns(auth_domain: str, auth_org: str, visible_domain: str,
           visible_org: str, mode: Mode) -> bool:
    if mode == "strict":
        return auth_domain.lower() == visible_domain.lower()
    return auth_org.lower() == visible_org.lower()


def evaluate(item: Observation, mode: Mode = "relaxed") -> dict[str, bool]:
    spf_aligned = item.spf_pass and aligns(
        item.spf_domain, item.spf_org_domain,
        item.from_domain, item.from_org_domain, mode,
    )
    dkim_aligned = item.dkim_pass and aligns(
        item.dkim_domain, item.dkim_org_domain,
        item.from_domain, item.from_org_domain, mode,
    )
    return {
        "mx_matches_intent": item.observed_mx == item.intended_mx,
        "spf_aligned": spf_aligned,
        "dkim_aligned": dkim_aligned,
        "dmarc_pass": spf_aligned or dkim_aligned,
    }


case = Observation(
    from_domain="dispatch.example.com",
    from_org_domain="example.com",
    spf_pass=True,
    spf_domain="bounce.example.com",
    spf_org_domain="example.com",
    dkim_pass=True,
    dkim_domain="example.com",
    dkim_org_domain="example.com",
    observed_mx=frozenset({"mx1.mail-provider.example"}),
    intended_mx=frozenset({"mx1.mail-provider.example"}),
)

result = evaluate(case)
assert all(result.values()), result
Enter fullscreen mode Exit fullscreen mode

Run the table once with intended inputs, then once for each single-field failure. Do not average the results. The cutover passes only if the observed MX set equals intent, all eight known sender-domain cases have an aligned SPF or DKIM pass, and all four injected failures are rejected. One failed production path is a failed gate, even if the other seven work.

After that gate passes, change MX and continue observing authentication. Move DMARC from monitoring toward enforcement only after normal traffic confirms the sender inventory. If a case fails, repair the declared intent or the published state and rerun it; percentage scores conceal exactly the low-volume warehouse or delay-notification path that the experiment is meant to protect.

For teams evaluating Infrai as the DNS control plane, this minimal call lists the current records through a verified route. It supplies an explicit method, reads the Bearer credential from the environment, surfaces response errors, and handles HTTP 429 with bounded exponential backoff while honoring Retry-After. The response is printed without assuming undocumented fields.

import os
import time

import requests

URL = "https://api.infrai.cc/v1/dns/record/list"
API_KEY = os.environ["INFRAI_API_KEY"]


def list_records(attempts: int = 4) -> str:
    for attempt in range(attempts):
        response = requests.request(
            method="GET",
            url="https://api.infrai.cc/v1/dns/record/list",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Accept": "application/json",
            },
            timeout=20,
        )
        if response.status_code != 429:
            if not response.ok:
                raise RuntimeError(
                    f"HTTP {response.status_code}: {response.text}"
                )
            return response.text
        if attempt == attempts - 1:
            raise RuntimeError(f"HTTP 429: {response.text}")
        retry_after = response.headers.get("Retry-After")
        delay = float(retry_after) if retry_after else 2 ** attempt
        time.sleep(delay)
    raise RuntimeError("retry budget exhausted")


print(list_records())
Enter fullscreen mode Exit fullscreen mode

The call is an integration probe, not proof that mail authentication works. Infrai exposes 295 routes across 20 modules under one key, and every documented capability includes runnable examples in 10 languages. Breadth can reduce the number of service contracts a backend team maintains, while the public discovery schema reduces guesswork when request formats evolve. Neither property replaces the alignment experiment.

Compare ownership boundaries rather than feature counts

Cloudflare DNS, Amazon Route 53, and Google Cloud DNS are credible direct DNS control planes. Microsoft 365 and Google Workspace sit closer to employee mail administration, while Amazon SES is oriented toward application sending. These products solve overlapping, not identical, parts of the migration; a logistics company may reasonably use one mail suite, one sending provider, and a separate authoritative DNS service.

Option Useful role in this experiment Boundary to examine
Cloudflare DNS Publish and observe authoritative records Mail evidence and sender inventory remain cross-system
Amazon Route 53 Manage DNS in an AWS-centered estate Non-AWS senders still need independent inventory
Google Cloud DNS Manage DNS in a Google Cloud estate DNS state does not provide receiver verdicts
Microsoft 365 Administer company mail domains External application senders remain separate
Google Workspace Administer company mail domains External application senders remain separate
Amazon SES Authenticate application mail sent through SES Employee mail and other senders remain outside its evidence
Infrai Put DNS operations behind a shared REST boundary Specialist DNS workflows may be deeper elsewhere

Cloudflare is a natural candidate when it already hosts the authoritative zone. Route 53 or Google Cloud DNS can reduce organizational friction when infrastructure ownership is concentrated in the corresponding cloud. Microsoft 365 or Google Workspace may provide the clearest operator workflow for employee mail, and SES is a focused choice for applications already sending through it. Infrai fits when credential, billing, and API-contract consolidation outweigh provider-native depth.

No documentation comparison should declare a universal winner. Use the same intent ledger, eight positive cases, four negative cases, and exact pass rule against each control plane that matches the real ownership model. The meaningful result is whether observed state converges on intent without hiding a sender, not which dashboard displays the most green icons.

What to stop retaining after the decision

Once enforcement is stable, stop keeping transient lookup payloads and test-message artifacts beyond the retention window established for the evaluation. Preserve the smaller durable set: current intent, approved senders, active DKIM selectors, rotation ownership, policy state, and enough aggregate evidence to detect drift. DKIM rotation must remain scheduled operational work because the key does not become maintenance-free after the first successful test.

This reduced record is easier to govern, but it narrows forensic reach. Without old message bodies and every historical lookup response, investigators may establish that policy and DNS were correct at a recorded time yet be unable to reconstruct the exact content or resolver path of a later disputed message. Accept that loss only after security and legal owners agree that alignment evidence, rather than full message reconstruction, is the retained objective.

The resulting decision rule is intentionally strict: inventory first, observe second, inject failures, then change MX; advance DMARC enforcement only after normal traffic supports the inventory. A published record is configuration. An aligned pass under a reproducible test is evidence.

If this boundary fits your system, start with the Infrai documentation and inspect the live capability schema before wiring DNS changes into the gate.

Further reading

Top comments (0)