Skip to content
Guia i visió

White-Label AI API Endpoints: Custom Domains, TLS Automation, and Tenant-Safe Routing

Un punt final d'IA de marca API necessita més que un CNAME. Creeu un cicle de vida de domini verificat que separi la propietat, els certificats, la preparació de DNS, l'encaminament perifèric, l'autorització de clau API, la supervisió de renovació i la sortida segura.

A customer CNAME pointing at your gateway does not create a production-ready branded endpoint. The DNS record may resolve before a certificate is available, the certificate may renew only while validation records remain intact, and an unchecked Host header can route a request into the wrong tenant context.

The safer model is to treat every branded hostname as a durable control-plane resource. Ownership, certificate issuance, DNS cutover, routing activation, suspension, and deletion each need explicit state. At request time, the hostname narrows the permitted tenant context, while the API key remains the authorization boundary.

Separate the domain lifecycle into independent checks

Do not represent a custom domain with a single Boolean such as verified. At minimum, track four independent conditions:

  • Ownership: Has the customer proved control of the hostname?
  • Certificate: Has a valid certificate been issued and deployed at the edge?
  • DNS: Does authoritative DNS point to the expected gateway target?
  • Routing: Is the exact hostname bound to an active tenant and routing profile?

This separation reflects documented edge-provider behavior. Managed custom-hostname products can use different records and statuses for hostname ownership and certificate validation. DNS resolution alone therefore does not prove that the endpoint is ready.

A practical state machine is:

requested
  -> ownership_pending
  -> certificate_pending
  -> dns_pending
  -> ready
  -> suspended
  -> draining
  -> deleted

These are business states, not direct copies of provider statuses. Store the provider's raw status separately, then derive your own state according to documented invariants. For example, mark a domain ready only when ownership is valid, the certificate is active, DNS points to the expected target, and the edge route is enabled.

Recommendation: make transitions monotonic during initial activation. A transient successful TLS probe should not skip ownership validation or routing checks. After activation, reconciliation may move a domain from ready to suspended or an explicit degraded state when those invariants stop holding.

Store a domain as a first-class resource

A domain record for an operational white-label AI API gateway should contain enough information to recover from ambiguous API calls and provider drift:

{
  "domain_id": "dom_01J...",
  "hostname_ascii": "api.customer.example",
  "tenant_id": "ten_01H...",
  "brand_id": "brand_42",
  "state": "certificate_pending",
  "ownership_method": "dns_txt",
  "ownership_record": {
    "name": "_gateway-verify.api.customer.example",
    "value": "verify=..."
  },
  "certificate_status": "pending_validation",
  "expected_cname": "customers.edge.example",
  "routing_profile_id": "route_openai_compatible_v3",
  "provider_hostname_id": "edge_8f2...",
  "creation_operation_id": "op_01J...",
  "last_reconciled_at": "2026-11-02T10:00:00Z",
  "last_reconciliation_result": "certificate_pending"
}

Normalize the hostname to lowercase ASCII using an IDNA-aware library before uniqueness checks. Remove a trailing dot and reject IP literals, URL paths, ports, wildcards unless explicitly supported, and names outside your accepted public-suffix policy. Preserve the submitted display form only as non-authoritative metadata.

Enforce a global uniqueness constraint on the normalized hostname. Two tenants must never be able to claim the same authority, even when they use different capitalization or Unicode representations.

Prevalidate before changing production DNS

When the edge platform supports it, issue and deploy the certificate before asking the customer to change the production CNAME. A typical sequence is:

  1. Create the domain resource with an idempotency key.
  2. Return the ownership and certificate-validation records.
  3. Poll or receive provider events until both validations succeed.
  4. Confirm the certificate is deployed for the exact hostname.
  5. Ask the customer to point the production CNAME at the gateway target.
  6. Resolve authoritative DNS from more than one network location.
  7. Enable the route and perform an authenticated end-to-end probe.
  8. Mark the domain ready.

Fact: managed SaaS-edge documentation describes zero-downtime migration sequences in which validation and certificate issuance occur before the production CNAME changes. Trade-off: this avoids a visible TLS activation gap but requires the customer to create additional TXT, CNAME, or delegated validation records.

If prevalidation is unavailable, expose the likely interruption explicitly. Do not promise zero downtime when certificate issuance starts only after traffic has moved.

Route by exact authority, then authorize the key

The trusted edge should maintain an exact allowlist from hostname to permitted tenant or brand context:

api.customer.example -> {
  tenant_id: "ten_01H...",
  brand_id: "brand_42",
  state: "ready"
}

Reject unknown, inactive, and ambiguous authorities. Never send them to a default tenant. For HTTP/1.1, validate Host; for HTTP/2 and HTTP/3, validate :authority. Where TLS is terminated at the same edge, compare the request authority with the SNI and certificate context as supported by the proxy.

Forwarding headers require the same discipline. The public edge should remove incoming X-Forwarded-Host, Forwarded, and any internal tenant headers, then add a canonical host and resolved tenant signal. The origin should accept those signals only over authenticated edge-to-origin connections.

The runtime authorization sequence should be:

  1. Resolve the normalized authority through the active hostname allowlist.
  2. Authenticate the API key independently.
  3. Load the immutable tenant identifier attached to the key.
  4. Verify that the key's tenant is permitted on the resolved hostname.
  5. Apply model, budget, rate-limit, and routing policy using tenant and key IDs.
  6. Write usage records against those immutable IDs, not the hostname.

This preserves the role of Partner API automation without turning a domain-management operation into an authorization shortcut.

Return 421 Misdirected Request when the authority does not match the configured origin or connection context. Return 403 Forbidden when the hostname is valid but the authenticated key belongs to a tenant that is not allowed to use it. Keep error bodies generic enough that they do not disclose which tenant owns a hostname.

Canonical and branded endpoint compatibility

Some customers need one key to work on both the gateway's canonical endpoint and their branded endpoint. That is acceptable only when both hostnames resolve to the same authorized tenant context. Strictly binding each key to one hostname reduces cross-brand use, but complicates migrations and clients that switch between endpoints.

Recommendation: model allowed endpoint contexts as key policy rather than comparing strings inside application code. For example, a key may allow tenant:any-active-hostname, brand:brand_42, or one exact domain_id.

Expose lifecycle operations through the Partner API

A minimal API should support create, inspect, revalidate, suspend, resume, and delete:

POST   /partner/v1/custom-domains
GET    /partner/v1/custom-domains/{domain_id}
POST   /partner/v1/custom-domains/{domain_id}/revalidate
POST   /partner/v1/custom-domains/{domain_id}/suspend
POST   /partner/v1/custom-domains/{domain_id}/resume
DELETE /partner/v1/custom-domains/{domain_id}

Create and delete operations should accept stable idempotency keys. Provider APIs, DNS propagation, and network timeouts can leave the caller unsure whether an operation succeeded. Persist the operation record before invoking the edge provider, and return the same domain or deletion operation when the request is retried with the same key and equivalent payload.

Emit signed lifecycle events such as custom_domain.verification_required, custom_domain.certificate_active, custom_domain.ready, custom_domain.dns_drifted, custom_domain.renewal_at_risk, and custom_domain.deleted. Events are notifications, not the only source of truth; consumers should be able to retrieve current state after missed or duplicated delivery.

Reconcile DNS, certificates, and routing continuously

Activation is not the end of the lifecycle. DNS records are edited, validation records disappear, edge configuration drifts, and certificates approach renewal.

Run a periodic reconciler that checks:

  • Authoritative DNS and the expected CNAME or delegated target
  • Provider hostname and certificate statuses
  • Certificate names, expiry, and renewal health
  • Presence of required DNS validation records
  • Exact edge-route ownership and activation state
  • The tenant's current eligibility to serve traffic

DNS-validated certificate automation may depend on validation CNAME records remaining publicly resolvable. Alert before expiry instead of assuming automatic renewal will always succeed.

Use bounded retries with exponential backoff and jitter for certificate operations. Preserve ACME account and order state where you operate issuance directly. Repeated deletion and recreation can consume certificate-order or registered-domain rate limits. Pending hostname records may also consume provider quota until explicitly removed.

Operational prediction: without reconciliation, the most common failures will appear after successful onboarding, during DNS edits, certificate renewal, provider-side drift, or customer churn. This is an architectural expectation, not a measured failure rate.

Offboard in two phases

Deleting the database row first is unsafe because edge mappings, certificates, or DNS can outlive it. Use an auditable two-phase workflow:

  1. Move the domain to draining and stop advertising it for new integrations.
  2. Decide whether existing requests receive a short grace period or immediate rejection.
  3. Disable the edge route so the hostname cannot resolve to a default tenant.
  4. Remove the custom-hostname and certificate association from the provider.
  5. Ask the customer to remove or replace the DNS record.
  6. Verify that DNS no longer points to your service.
  7. Mark the resource deleted while retaining identifiers and an audit record.

A dangling CNAME that targets a deprovisioned service can create a subdomain-takeover risk. Conversely, leaving a stale mapping active can continue sending a former customer's traffic through your edge. Couple provider cleanup and DNS verification to the same deletion operation, but record each result independently.

Test the boundary, not only the happy path

Before enabling customer domains, automate conformance tests for:

  • A forged Host or X-Forwarded-Host header
  • Conflicting SNI and HTTP authority values
  • An unknown hostname and a known but suspended hostname
  • A valid key from tenant A used on tenant B's hostname
  • Duplicate create and delete requests with the same idempotency key
  • The same hostname submitted with case, trailing-dot, or Unicode variations
  • DNS changed away from the expected target after activation
  • A removed certificate-validation record before renewal
  • Deletion interrupted after the edge mapping is removed but before DNS changes

Also verify that logs, billing, usage attribution, rate limits, and policy decisions use tenant and key IDs. Hostnames are mutable presentation and routing inputs; they should not become financial or security identities.

Implementation checklist

  • Normalize hostnames and enforce global uniqueness.
  • Track ownership, certificate, DNS, and route readiness separately.
  • Prevalidate certificates before cutover where supported.
  • Allowlist exact authorities at the trusted edge.
  • Strip untrusted forwarding headers and create an authenticated origin signal.
  • Authorize the API key against the hostname's tenant context.
  • Use 421 for origin or connection mismatch and 403 for cross-tenant key use.
  • Make create and delete idempotent.
  • Reconcile provider state, DNS, routing, and renewal health continuously.
  • Delete edge mappings explicitly and verify DNS during offboarding.

A branded endpoint is ready only when control-plane state and data-plane behavior agree. Model that agreement explicitly, test the negative paths, and keep the API key as the final tenant authorization boundary.

Related reading

FAQ

Preguntes freqüents

És suficient un CNAME per activar un punt final d'IA de marca API?
No. Un CNAME estableix l'encaminament DNS, però la preparació per a la producció també requereix una verificació del control del domini, un certificat actiu, un mapeig exacte de les vores i una comprovació d'autorització correcta. Feu un seguiment d'aquestes condicions de manera independent.
El nom d'amfitrió personalitzat hauria de determinar l'inquilí?
El nom d'amfitrió pot seleccionar o restringir el possible context d'inquilí, però no hauria d'autoritzar la sol·licitud per si mateix. Autentiqueu la clau API de manera independent i rebutgeu la sol·licitud quan l'arrendatari de la clau no estigui permès en aquest nom d'amfitrió.
When should a gateway return HTTP 421 instead of 403?
Utilitzeu 421 Misdirected Request quan l'autoritat de sol·licitud no coincideix amb un origen configurat per al servidor o el context de connexió, com ara un SNI i un host no coincidents. Utilitzeu 403 quan el nom d'amfitrió sigui vàlid però la clau autenticada no estigui autoritzada per al seu inquilí o marca.
Una clau API pot funcionar en punts finals canònics i personalitzats?
Sí, sempre que tots els noms d'amfitrió acceptats s'assignin al mateix context d'inquilí autoritzat i la política de claus permeti explícitament aquests contextos de punt final. La facturació i l'aplicació de les polítiques encara haurien d'utilitzar identificadors de clau i inquilí immutables.
Què ha de passar quan un client elimina un domini personalitzat?
Suspengueu o dreneu el trànsit, suprimiu el mapeig de vora i l'associació de certificats, comproveu que el DNS ja no s'orienti al servei i conservi un registre d'auditoria. No tracti l'eliminació de la fila de la base de dades local com una baixa completa.