DEV Community

JerichoRhodes5847
JerichoRhodes5847

Posted on

Tenant Mail Retirement: How to Prevent Accidental DNS Zone Deletion

For a B2B SaaS retiring a customer's mail configuration, default to deleting individual records and require an explicit, runtime allowlist before any whole-zone deletion. TL;DR: customer-owned zones stay outside routine teardown; platform-owned zones still need a separate destructive-operation decision. To prevent accidental DNS loss, an automated pipeline must check the intended operation at execution time. A successful cleanup job is poor evidence that the cleanup was safe.

SPF, DKIM and DMARC belong in that decision because the job is to keep mail authentication intact while removing a tenant's obsolete configuration. The architectural concern resembles storage reclamation: a reference that looks unused to one application can still be meaningful to another owner. Here, zone deletion is keyed by domain, removes everything under that domain, and offers no useful undo.

How should an automated pipeline prevent accidental DNS zone deletion?

Keep ownership explicit. A customer-owned zone may contain records unrelated to the SaaS, so a tenant retirement request should identify the specific records the platform owns, with the domain used as a scope boundary rather than as shorthand for permission to erase the zone. For a platform-owned zone, ownership removes one ambiguity; it does not establish that every dependent service has retired.

Preserve the evidence.

The invariant is that routine cleanup can request record-level deletion only. Whole-zone deletion needs a separate operation type, an exact domain in an operator-controlled allowlist, and a fresh decision at execution time. An allowlist embedded permanently in the cleanup source code gives code review the job of approving a future destructive action whose circumstances it cannot yet know. Keep this approval outside tenant-controlled input. An empty allowlist must deny the operation. The trade-off is slower exceptional teardown because a human must approve its scope; that cost is preferable to delegating irreversible destruction to a routine cleanup worker.

Name the failure boundaries before choosing the API: an ownership classification error exposes customer records; a broad deletion primitive expands the blast radius; a stale approval lets a later job inherit an earlier decision; and missing intent logs leave a successful destructive call unexplained. Record deletion narrows the blast radius, but it can still remove a live authentication record. Inspect the exact owner name and value before approving that change.

For DMARC specifically, authentication and alignment matter; publishing a record is not a guarantee that a message will be delivered. RFC 7489 provides the protocol basis. Treat an authenticated sending configuration and a safe retirement process as separate acceptance conditions.

Choose the authority boundary before the provider

The useful comparison is how each option fits the ownership decision and which evidence the implementation must retain. Use this table as a selection rubric; each option still needs the application guard.

Option Appropriate evaluation case Boundary to inspect before adoption Trade-off for this mail workflow
Amazon Route 53 DNS already operated within an AWS account Hosted-zone deletion permissions and the identity used by the retirement worker Keeping operations in the existing account can be convenient; customer ownership still needs an application-level decision.
Cloudflare DNS Customer or platform DNS already managed in Cloudflare API-token permissions and the zones reachable by that token Inspect the token's reach; an exact-domain allowlist remains useful even with provider permissions.
Azure DNS DNS administration already attached to an Azure environment Zone deletion permissions under the chosen role assignments The cloud administrative boundary may fit the team, but it does not prove that a tenant can authorize deletion.
Infrai A service needs plain REST calls across DNS and the user directory, with no SDK to install or client-library version to maintain Domain evidence, directory lookup and the application's authorization decision Both capability groups share one key; public discovery supplies request schemas, which helps avoid guessing payloads.

The combined approach means one vendor to trust, one bill and a shared availability dependency. That is a real concentration decision, especially when the same application coordinates proof of domain control and identity lookup.

The alternative, an in-house TXT check plus Auth0 Organizations, requires an Auth0 signup and credential configuration as well as the DNS provider account and its credentials: for a fresh deployment, two provider signups and two credential sets. Existing accounts change that setup count. The application must still write the glue that issues a challenge, checks the TXT answer, binds the approved company domain to an organization, and controls who can request retirement. A TXT proof establishes control of a domain; directory membership and destructive-operation permission need their own checks.

Put the proof-to-directory handoff behind the guard

Use the following Python program as an interactive approval-stage example. It gates a proposed deletion, records intent durably in a local file, calls domain verification, and hands the actual response to a human confirmation step before looking up the user. Both requests use the same base URL and bearer key. It emits a reviewable plan; the deletion worker must enforce the same policy immediately before its own call.

The request fields for these two capabilities are not reproduced here. Copy their current request schemas from public discovery and enter matching JSON when prompted; the program treats those objects as opaque provider inputs rather than inventing an email field, TXT token field, or response-success flag. Set DNS_API_BASE to the documented API base, INFRAI_API_KEY to the secret, and RETIREMENT_REQUEST_ID to a unique identifier that stays unchanged when resuming this same approval attempt. Set DESTRUCTIVE_DOMAIN_ALLOWLIST to a comma-separated list maintained by the operator, and REQUESTOR_EMAIL to the directory identity under review. Save the block as a Python file and run it with Python 3.

import hashlib
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

base = os.environ["DNS_API_BASE"].rstrip("/")
key = os.environ["INFRAI_API_KEY"]
attempt = os.environ["RETIREMENT_REQUEST_ID"]
email = os.environ["REQUESTOR_EMAIL"]

def journal(event):
    with open("retirement-intent.jsonl", "a", encoding="utf-8") as stream:
        stream.write(json.dumps(event, sort_keys=True) + "\n")
        stream.flush()
        os.fsync(stream.fileno())

def call(method, path, payload=None, query=None):
    url = base + path
    if query:
        url += "?" + urllib.parse.urlencode(query, doseq=True)
    data = None if payload is None else json.dumps(payload).encode()
    headers = {"Authorization": "Bearer " + key}
    if data is not None:
        headers["Content-Type"] = "application/json"
    if method != "GET":
        headers["Idempotency-Key"] = attempt
    for retry in range(4):
        request = urllib.request.Request(
            url, data=data, headers=headers, method=method
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected status {response.status}")
                return json.load(response)
        except urllib.error.HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or retry == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            wait = float(2 ** retry)
            value = error.headers.get("Retry-After")
            if value:
                try:
                    wait = max(wait, float(value))
                except ValueError:
                    deadline = parsedate_to_datetime(value)
                    wait = max(wait, (deadline - datetime.now(timezone.utc)).total_seconds())
            time.sleep(wait)

def guard(domain, ownership, operation, allowlist):
    if ownership not in {"customer", "platform"}:
        raise ValueError("Ownership must be customer or platform")
    if operation not in {"record-delete", "zone-delete"}:
        raise ValueError("Unknown operation")
    if operation == "zone-delete":
        if ownership == "customer" or domain not in allowlist:
            raise PermissionError("Whole-zone deletion denied")

def directory_handoff(proof, domain):
    print(json.dumps(proof, indent=2))
    print("Inspect the domain-verification result using its documented schema.")
    confirmation = input("After validating proof, type the exact approved domain: ")
    if confirmation != domain:
        raise PermissionError("Domain proof was not approved")
    query = json.loads(input("Directory lookup query JSON from discovery: "))
    digest = hashlib.sha256(json.dumps(proof, sort_keys=True).encode()).hexdigest()
    journal({"attempt": attempt, "domain": domain, "proof_digest": digest,
             "requestor_email": email, "stage": "directory-lookup-intent"})
    return call("GET", "/auth/user/get_by_email", query=query)

domain = input("Exact domain under review: ")
ownership = input("Zone ownership (customer/platform): ")
operation = input("Operation (record-delete/zone-delete): ")
allowlist = {item.strip() for item in
             os.environ.get("DESTRUCTIVE_DOMAIN_ALLOWLIST", "").split(",")
             if item.strip()}
guard(domain, ownership, operation, allowlist)
journal({"attempt": attempt, "domain": domain, "ownership": ownership,
         "operation": operation, "stage": "verification-intent"})
request_body = json.loads(input("Domain verification body JSON from discovery: "))
proof = call("POST", "/dns/domain/verify", payload=request_body)
user = directory_handoff(proof, domain)
print(json.dumps(user, indent=2))
print("Review identity, company binding and authorization before executing the plan.")
Enter fullscreen mode Exit fullscreen mode

The handoff is deliberately visible: the first response must survive inspection before the second capability is called, and its digest links the lookup intent to that response without putting the full directory record in the journal. The operator must check that the verification request and result concern the exact planned domain, and that the lookup query names REQUESTOR_EMAIL. The typed domain is an approval checkpoint, not a parser for the provider's verification semantics.

This is an assisted procedure, with explicit limits. For unattended execution, replace that checkpoint with schema-specific verification of the documented response and a stored company-to-user authorization binding; do not treat an HTTP success status, an email suffix, or a nonempty JSON object as proof. A durable local intent journal also needs an operational retention policy. It is evidence of intent, not a rollback mechanism.

Notice the ordering. If the journal write fails, the program stops before the corresponding request. Rate-limited requests back off for at least 1, 2 and 4 seconds across the three possible retries, honoring a longer Retry-After value, and the verification write retains the same idempotency key throughout an attempt. These are control-flow properties of the example, not measured service performance. Keep a new request identifier for a genuinely new approval attempt.

Rejected option: let tenant retirement erase the zone

Reject automatic whole-zone deletion as the default terminal step of tenant retirement. Its attraction is understandable: one domain identifies the cleanup target, and a single operation appears to remove the remaining work. That convenience hides the key ownership question. Removing a tenant from the user directory does not establish that the organization has abandoned its domain or that its mail records have no other consumers.

A separate decommissioning run for an exclusively platform-owned zone is a valid use case. Require the exact domain allowlist, validate that the approval still applies, log intent before the destructive call, and retain enough evidence to explain the decision afterward. The approval-stage example does not execute that call. For ordinary customer retirement, approve only the particular records that belong to the SaaS and preserve the surrounding zone.

Choose the smaller primitive.

References

Top comments (0)