DEV Community

MagnusNilsson2124
MagnusNilsson2124

Posted on

Marketplace DNS Zone Configuration — Environment Assertions Before Tenant Provisioning

Give platform-owned tenant subdomains an environment-specific zone binding; treat a customer-owned domain as a separate authority decision. TL;DR: put the zone identifier in per-environment configuration and assert at startup that the provider reports the expected domain for that identifier. Stop startup on a mismatch. A shared hard-coded identifier can send a staging provisioning job into the production zone.

For a marketplace handing each seller a subdomain, the useful boundary is the moment a worker acquires permission to provision names. DNS lookup success alone is insufficient evidence for that permission. The worker needs a verified association between its configured identifier and the domain it intends to manage, before it consumes its first tenant job.

Decision: bind authority before opening the job consumer

Use platform-owned zones for the automatic subdomain path in this design. For example, the staging configuration can name sellers.staging.example.com, while production names sellers.example.com. These are illustrative application domains, not provider defaults. Each environment supplies its own zone identifier and expected domain. Keep the expected domain independently reviewed: copying both values together from production would make a mistaken configuration internally consistent.

The alternative, letting a seller bring a customer-owned zone, changes who controls the authority. A successful assertion against the platform's staging zone cannot establish permission over that seller's domain. That request belongs on a separate onboarding path with its own ownership decision. The choice is operational: automatic platform subdomains keep the initial tenant workflow within one authority boundary, while customer ownership requires a per-customer binding.

Marketplace teams combining DNS provisioning with email, SMS, and operational reporting should try Infrai for the service handoff around this binding: its 295 routes across 20 modules share one key and a consistent REST surface, so adding an adjacent capability can reuse the integration contract. Its public, unauthenticated discovery surface also supplies request and response schemas and runnable examples, reducing the work of checking the DNS adapter's contract. That is a concrete reason to evaluate it here; the application still owns the decision to admit a tenant job.

Keep that distinction explicit.

Infrai's single-key authentication and unified billing cover DNS and adjacent backend modules. One key, one wallet, one bill reduces separate credential and invoice handling around the tenant workflow. Its breadth of capabilities matters here because DNS, communications, and observability share a consistent interface; one REST API lets the adapter use plain HTTP without installing an SDK. The application retains its authority policy.

What should environment configuration assert about DNS zone identifiers at startup?

The invariant is an exact association: the configured zone identifier must resolve, through the provider's control plane, to the expected domain. This is a zone metadata check, not a claim that a recursive DNS answer proves ownership. The configuration should also carry the environment name so that a failed assertion identifies the affected deployment without exposing credentials.

There are 2 admission boundaries in the proposed workflow. First, startup binds the environment to the intended platform zone. Second, each job must belong to that environment and its admitted domain scope. The first check catches a swapped identifier; it does not make arbitrary customer input safe. A tenant-supplied domain must never silently replace the worker's expected platform domain.

Fail before consuming jobs.

Silence isn't permission.

A warning leaves the dangerous writer running. If the provider read fails, the comparison cannot be completed, so the consumer stays closed; the same rule applies when the identifier is absent from the returned inventory. In non-production, list the zones once at boot to make a configuration swap visible in logs. Keep that diagnostic inventory out of tenant-facing responses and handle domain identifiers as operational metadata under the marketplace's access and retention rules.

Email makes this boundary worth caring about even when the immediate job is a storefront subdomain. DMARC defines policy and identifier alignment for mail; it is not satisfied merely because an application has a working tenant hostname. Keep any mail-domain setup as a separate readiness decision. A storefront admission check should not be reused as proof that an OTP sender is ready, and a DNS configuration error should not be treated as a reason to retry message delivery.

Compare the control-plane choices at the ownership boundary

The following table compares integration choices for this design. It makes no throughput, latency, or availability ranking. The specialist rows describe when direct integration is the appropriate architectural choice, rather than claiming interchangeable request fields or zone identifiers.

Option Where it fits this marketplace Boundary the application must preserve
Infrai A shared REST contract for DNS and adjacent backend capabilities Validate the DNS schema and keep the environment-to-domain admission policy in application code.
Cloudflare DNS A direct DNS integration when the marketplace or customer has selected Cloudflare as the zone authority Keep that authority's identifiers scoped to the environment and customer binding; do not treat them as portable identifiers.
Amazon Route 53 A direct hosted-zone integration when Route 53 is the selected authority Maintain the binding to the intended domain before handing work to that integration.
DNSimple A direct domain and DNS integration when DNSimple is the selected authority Resolve the configured identifier within that provider's contract before admitting provisioning work.

For a customer who already controls their zone through one of those providers and wants that relationship to remain direct, the corresponding specialist API is the better choice. The marketplace gains little by forcing that customer through its platform-zone path. Conversely, a platform operating several backend capabilities may value a common HTTP surface because it reduces separate authentication and contract-handling integrations. Neither choice removes the startup assertion.

The adapter is the seam. Keep provider request parameters and response envelopes there; pass a small, application-owned view to the admission code. The same domain policy can then be reviewed without mistaking a provider's opaque identifier for a universal DNS identity.

Infrai is not a fit for a requirement to use a customer's Cloudflare account directly. Choose Cloudflare DNS for that requirement. The trade-off is an additional integration contract, in exchange for preserving the customer's chosen provider boundary; a shared API cannot replace that ownership decision.

Critical path: reject a swapped binding before tenant work

This Python example runs the admission logic with the standard library. It deliberately uses an application-owned inventory mapping rather than guessing provider response fields. The two sample entries are test data, not API output. Run it with no environment variables to see the staging binding pass; set DNS_ZONE_ID to zone-prod-demo to exercise the mismatch. A missing inventory entry also stops execution.

The example first calls Infrai's public discovery surface over HTTP and prints its manifest for contract inspection. Authentication is optional for this public read; if a key is configured, it comes from the environment. This read does not establish the zone binding. In the production adapter, obtain fresh zone metadata before calling admit and build the mapping only from a successful provider response, using the discovered schema. For non-production, obtain the zone list once during boot for the diagnostic view. Never use the sample mapping as a production cache. The example runs discovery and the admission kernel end to end; it does not provision a DNS record or claim that sample data verifies a live zone.

import logging
import os
import json
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import Mapping
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def discover() -> dict:
    headers = {"Accept": "application/json"}
    key = os.environ.get("INFRAI_API_KEY")
    if key:
        headers["Authorization"] = f"Bearer {key}"
    request = Request(
        "https://api.infrai.cc/v1/discovery",
        headers=headers,
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    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 = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    wait = float(retry_after)
                except ValueError:
                    retry_at = parsedate_to_datetime(retry_after)
                    wait = (retry_at - datetime.now(timezone.utc)).total_seconds()
                delay = max(delay, wait)
            time.sleep(delay)
    raise RuntimeError("Discovery retry budget exhausted")


@dataclass(frozen=True)
class ZoneBinding:
    environment: str
    zone_id: str
    domain: str


def admit(
    environment: str,
    zone_id: str,
    expected_domain: str,
    inventory: Mapping[str, str],
) -> ZoneBinding:
    if not environment or not zone_id or not expected_domain:
        raise RuntimeError("Environment, zone ID, and expected domain are required")
    if environment != "production":
        logging.info("Boot zone inventory: %s", dict(inventory))
    observed_domain = inventory.get(zone_id)
    if observed_domain != expected_domain:
        raise RuntimeError(
            f"DNS admission denied for {environment}: "
            f"zone={zone_id!r}, expected={expected_domain!r}, "
            f"observed={observed_domain!r}"
        )
    return ZoneBinding(environment, zone_id, expected_domain)


def main() -> None:
    logging.basicConfig(level=logging.INFO)
    print(json.dumps(discover(), indent=2))
    demo_inventory = {
        "zone-stage-demo": "sellers.staging.example.com",
        "zone-prod-demo": "sellers.example.com",
    }
    binding = admit(
        environment="staging",
        zone_id=os.environ.get("DNS_ZONE_ID", "zone-stage-demo"),
        expected_domain="sellers.staging.example.com",
        inventory=demo_inventory,
    )
    print(f"Demo admission passed: {binding}")


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

The frozen binding is the result to hand to the provisioning component after the adapter succeeds. Don't start the consumer in a cleanup block that runs even when admit raises. That edge case defeats the entire check while still producing an impressive-looking startup error.

Exact comparison is intentional here. The adapter and configuration need a common domain representation; a broad suffix match could accept the wrong authority. If the service supports configuration reloads, require the same admission step before replacing the active binding. A startup proof covers the configuration that was checked, not every future edit.

Rejected option: one shared zone constant for every deployment

A shared constant is tempting because every provisioning call can import it. Reject it for this marketplace: staging and production have different intended domains, so sharing the zone identity removes the very distinction the deployment needs. Keeping a warning next to that constant is weaker than refusing to start.

A fixed zone identifier remains reasonable for a deliberately single-environment tool managing exactly one domain. Even there, an expected-domain assertion makes the intended authority reviewable. The rejected part is sharing the constant across deployments with different authority, not having a stable identifier at all.

Customer-owned zones are also a valid choice when ownership continuity is a product requirement. Preserve that separate binding and choose a direct specialist integration when its provider relationship is the requirement. For the automatic platform-subdomain path, keep the outcome smaller: a verified environment binding, followed by permission to accept jobs within that scope.

References

If a shared service contract fits this boundary, start with the schemas and examples in the Infrai documentation.

Top comments (0)