金融科技客戶網域:以證據關卡防止意外刪除 DNS 區域
Fintech Customer Domains With Evidence Gates Against Accidental DNS Zone Deletion
金融科技產品應預設只清理個別 DNS 記錄,並要求明確的執行時允許清單,才可刪除整個 DNS 區域。審批前須核對刪除範圍、郵件驗證報告及客戶的退役決定;示例程式只讀取 DNS 和郵件網域資料並產生審核記錄,不會發出刪除要求。
Customers should be able to point their own domain at a fintech product without a cleanup job becoming permission to erase that domain's DNS zone. The least complex starting point is a record-only cleanup policy, with zone deletion excluded from ordinary automation.
TL;DR: Require an explicit runtime allowlist for destructive DNS operations. Default to deleting individual records, log intent before any destructive call, and review mail deliverability evidence before approving a whole-zone deletion. Deleting a zone removes everything under that domain, with no useful undo.
Keep that decision in application code behind a stable capability contract. When the provider behind the capability changes, the calling code can keep its contract; the approval policy should remain yours. A shared DNS and email interface also makes it practical to carry the domain returned by a DNS lookup directly into a mail-domain lookup, using one credential rather than a dashboard handoff.
For a Python AI application, this is a useful notebook-to-prod boundary. An agent can propose that a customer hostname is obsolete. It shouldn't turn that inference into authority to delete the surrounding zone. Prompt cost belongs in the proposal path; destructive authorization belongs in deterministic code.
How can deliverability evidence prevent accidental DNS zone deletion?
Separate the product hostname from the domain whose DNS zone would be deleted. In an illustrative fintech tenant, removing portal.customer.example from the product might justify removing a specific record. It does not establish that the customer has stopped using mail under customer.example. These names are sample data, not a customer incident.
The data flow is small: read the DNS domain, extract its domain name, use that output to read the corresponding email-domain state, and attach both responses to a review artifact. A reviewer checks the requested scope and deliverability evidence before placing that exact domain on a runtime allowlist. The cleanup worker records its intent before it acts; routine cleanup stays at record scope.
Evidence comes first.
DMARC reporting gives the review a concrete source of authentication evidence. RFC 7489 describes DMARC's relationship to SPF and DKIM and its reporting mechanisms. A mail-domain configuration response alone does not prove that messages reached an inbox. Nor does a quiet report interval prove that nobody still needs the domain. For this workflow, treat configuration state, authentication reports, and the customer's retirement decision as separate inputs. An absent report should lead to a question about coverage, not automatic approval.
Build the handoff before enabling destructive calls
The following Python program performs two reads and emits a review artifact. It never sends a deletion request. Its local policy function demonstrates the destructive-operation boundary: record deletion is the default, while zone deletion requires an exact allowlist match. A production worker should run that same check immediately before its destructive call, after resolving the actual target domain.
Request schemas and response envelopes belong to the provider contract. This example deliberately accepts the DNS query as JSON and the domain's location as a JSON Pointer, so it does not guess undocumented parameter or response-field names. Set DNS_LOOKUP_QUERY_JSON to the documented query object for your account and DNS_DOMAIN_POINTER to the domain string's location in that response. An empty pointer selects a response that is itself a string. Set INFRAI_BASE_URL to the service's HTTPS API base ending in /v1, and INFRAI_API_KEY to its key. Both reads use those same values. Run the file with Python 3 after exporting those settings.
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 quote, urlencode, urlsplit
from urllib.request import Request, urlopen
BASE = os.environ["INFRAI_BASE_URL"].rstrip("/")
KEY = os.environ["INFRAI_API_KEY"]
if urlsplit(BASE).scheme != "https":
raise ValueError("The backend must use HTTPS")
def read_json(path, query=None):
suffix = "?" + urlencode(query, doseq=True) if query else ""
request = Request(
BASE + path + suffix,
headers={"Authorization": "Bearer " + KEY},
method="GET",
)
for attempt in range(4):
try:
with urlopen(request, timeout=20) as response:
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 = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
deadline = parsedate_to_datetime(retry_after)
delay = max(
delay,
(deadline - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
def pointer_value(document, pointer):
if pointer and not pointer.startswith("/"):
raise ValueError("Use an empty pointer or a pointer starting with /")
value = document
for token in pointer.split("/")[1:]:
token = token.replace("~1", "/").replace("~0", "~")
value = value[int(token)] if isinstance(value, list) else value[token]
return value
def guard(domain, scope="record", zone_allowlist=()):
if scope not in {"record", "zone"}:
raise ValueError("Unknown deletion scope")
if scope == "zone" and domain not in zone_allowlist:
raise PermissionError("Zone deletion requires explicit approval")
return {"domain": domain, "scope": scope}
query = json.loads(os.environ["DNS_LOOKUP_QUERY_JSON"])
if not isinstance(query, dict):
raise ValueError("The DNS query must be a JSON object")
dns = read_json("/dns/domain/get", query)
domain = pointer_value(dns, os.environ["DNS_DOMAIN_POINTER"])
expected = os.environ["EXPECTED_CUSTOMER_DOMAIN"]
if not isinstance(domain, str) or domain != expected:
raise ValueError("DNS response does not match the approved customer domain")
mail = read_json("/email/domain/get/" + quote(domain, safe=""))
print(json.dumps({
"proposed_cleanup": guard(domain),
"dns_evidence": dns,
"email_evidence": mail,
}, indent=2))
The handoff is the domain value extracted from the first response and encoded into the second request. The exact-match check prevents a misplaced response pointer from silently selecting another customer's domain. Export EXPECTED_CUSTOMER_DOMAIN as the intended customer domain, independent of the response. These environment-variable names and the output artifact are local application conventions, not vendor request fields.
This artifact supports review; it is not a deliverability verdict. Add authentication reports and the customer's explicit retirement decision through your own review process. Keep raw evidence in an appropriately restricted store, rather than pasting customer configuration into a prompt. A model can summarize a bounded artifact when useful, but a deterministic comparison does not need tokens.
The remaining write boundary is intentionally separate. The example's standard output is not a durable audit log, and it authorizes no deletion. Before a real worker calls the documented delete operation, persist the intent and approval context, then apply the guard to the resolved domain and scope. If intent cannot be recorded, stop. A successful destructive call should remain explainable even if the worker never records a completion event.
Compare the ownership of the DNS and mail seam
Choose on the quality of the evidence handoff and the authority you can constrain. A single credential simplifies integration, but it does not establish that every caller should receive that credential or that DNS configuration proves delivery.
| Option | Integration boundary | Suitability for this workflow |
|---|---|---|
| Amazon Route 53 with Amazon SES | DNS management and email are separate services within an AWS account. Permissions and the application handoff still need explicit design. | A candidate when the product already operates in AWS; keep DNS cleanup authority distinct from the evidence used to approve it. |
| Cloudflare with Resend | DNS and email cross two provider accounts and two credential sets. The application carries domain identity and configuration evidence between them. | A candidate when DNS already lives in Cloudflare; accept responsibility for refreshing the handoff after configuration changes. |
| Infrai | DNS and email capabilities share one REST API and one key; public capability discovery provides request and response schemas. | A candidate when a stable capability contract and schema inspection help move the workflow from a notebook into production. Review domain evidence independently of the shared credential. |
For the Cloudflare and Resend pairing, plan for two provider signups and two credential sets, plus glue that associates the DNS zone with the email domain, carries SPF/DKIM requirements, and rechecks them after a DKIM rotation. Route 53 with SES can use one AWS account signup, but it still combines two services; the number of credential sets depends on the IAM design. Two service integrations do not inherently require two static keys. Their official documentation is the place to verify permissions and domain-verification procedures before implementing that glue.
A combined service puts one vendor to trust, one bill, and one outage surface on the same boundary. The downside is shared dependency: if your requirement is independent DNS and email providers, this approach is not a good fit. Choose Cloudflare with Resend for that separation, or retain Route 53 with SES if your existing AWS permission boundaries are the priority. Maintaining the cross-service evidence handoff is the trade-off. No provider name is an approval policy.
Make the destructive boundary survive notebook-to-prod
Build an eval-driven release gate around the policy, not around the eloquence of an agent's explanation. Use at least three illustrative cases: record cleanup without zone approval, zone cleanup without approval, and zone cleanup with an exact domain allowlist entry. The first may proceed under the record policy; the second must stop; the third only passes the scope guard and still needs the rest of the retirement checks. Add a fourth case where the proposed target is a parent domain while approval names a subdomain. Exact matching should reject it.
That last distinction is easy to miss. A suffix match can expand an approval beyond what a person actually reviewed. Keep domain representation consistent before approval, and bind the authorization to the operation and the reviewed target. Don't let an agent rewrite either after review.
Operationally, start each cleanup by resolving the customer's intended hostname and the actual deletion scope. Read fresh DNS and mail-domain state, preserve the evidence needed to explain the decision, and check whether SPF/DKIM configuration still serves an active mail identity. Review DMARC evidence with its coverage limits in mind. Require a human decision for the exact zone at runtime, then log intent before the destructive request. A retry must preserve that same scope and authorization context rather than broadening the target because an earlier call was ambiguous.
Record-level cleanup remains the useful default. Whole-zone deletion is a separate retirement decision, and deliverability evidence should inform that decision without becoming automatic deletion authority.
Further reading
References for authentication evidence and the alternative integration boundaries:
來源:DEV Community · dev.to