mirror of
https://github.com/taylanbakircioglu/haproxy-openmanager.git
synced 2026-10-02 15:08:13 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c8832330a | |||
| 81ab674072 | |||
| 6bf6d016f5 | |||
| 0a0226c758 | |||
| 8e534ef170 |
@@ -107,7 +107,7 @@ This architecture provides better security (no inbound connections to HAProxy se
|
||||
✅ **SSL Certificate Management** - Centralized SSL with expiration tracking
|
||||
✅ **CSR Creation** *(v1.9.0)* - Generate a private key + CSR in-app (RSA 2048/4096, ECDSA P-256/P-384, full subject + SANs), have it signed by any external CA, then import the signed certificate — the key never leaves the server
|
||||
✅ **ACME Auto SSL (Let's Encrypt)** - Automated certificate issuance, renewal, and deployment via ACME protocol
|
||||
✅ **ACME DNS-01 Challenge** *(v1.8.0)* - TXT-record validation for internal/isolated clusters (no public port 80) and wildcard certificates; pluggable DNS providers (Manual + Cloudflare), opt-in, HTTP-01 unchanged
|
||||
✅ **ACME DNS-01 Challenge** *(v1.8.0)* - TXT-record validation for internal/isolated clusters (no public port 80) and wildcard certificates; pluggable DNS providers (Manual + Cloudflare + GoDaddy *(v1.10.0)*), opt-in, HTTP-01 unchanged
|
||||
✅ **ACME Certificate Diagnostic Panel** - Automated preflight that checks agent readiness, DNS resolution, port 80 reachability, and ACME challenge ACL before issuing certificates
|
||||
✅ **WAF Rules** - Web Application Firewall management and deployment
|
||||
✅ **Agent Script Versioning** - Update agents via UI (Monaco editor) with auto-upgrade
|
||||
@@ -256,7 +256,7 @@ This architecture provides better security (no inbound connections to HAProxy se
|
||||
- **Stuck Order Detection** *(v1.4.0)*: Setup wizard surfaces orders that the CA has validated but not yet downloaded, with one-click `Complete` action and automatic 60-second retry
|
||||
- **Multi-Provider Support**: Configurable ACME directory URL supports Let's Encrypt, ZeroSSL, Google Trust Services, Buypass, and custom CAs
|
||||
- **HTTP-01 Challenge**: Built-in challenge responder with automatic HAProxy routing injection; reserved backend name `_acme_challenge_backend` is auto-managed and protected from manual edits / agent sync collisions
|
||||
- **DNS-01 Challenge** *(v1.8.0 — Issue #35)*: Validate via a DNS TXT record instead of HTTP on port 80, for **internal/isolated clusters with no public ingress** and for **wildcard** certificates (`*.example.com`). Pluggable per-account DNS provider (Manual + Cloudflare to start; credentials encrypted at rest and verified on save), same PENDING → APPLIED pipeline, bounded automatic retry on propagation lag, and a DNS-01 event timeline. Opt-in via a global setting; HTTP-01 behaviour is unchanged. (See the *DNS-01 Challenge* subsection under ACME Auto SSL below.)
|
||||
- **DNS-01 Challenge** *(v1.8.0 — Issue #35)*: Validate via a DNS TXT record instead of HTTP on port 80, for **internal/isolated clusters with no public ingress** and for **wildcard** certificates (`*.example.com`). Pluggable per-account DNS provider (Manual + Cloudflare + GoDaddy *(v1.10.0)*; credentials encrypted at rest and verified on save), same PENDING → APPLIED pipeline, bounded automatic retry on propagation lag, and a DNS-01 event timeline. Opt-in via a global setting; HTTP-01 behaviour is unchanged. (See the *DNS-01 Challenge* subsection under ACME Auto SSL below.)
|
||||
- **ACME Account Management**: Register, view, and deactivate ACME accounts from the UI
|
||||
- **Staging Mode**: Test certificate issuance with Let's Encrypt staging environment before production
|
||||
- **Custom Staging Endpoint** *(v1.4.0)*: Optional `staging_url_override` setting lets you point staging mode at a private ACME test CA (e.g. Pebble) without touching the production directory URL
|
||||
@@ -989,9 +989,9 @@ DNS-01 is **opt-in** and fully backward compatible: it is disabled until an admi
|
||||
|
||||
- **Enable it**: Settings → ACME / SSL Automation → **DNS-01 Challenge (advanced)** → turn on *Enable DNS-01 Challenge* and Save. While off, DNS-01 options are hidden and no DNS-01 orders can be created.
|
||||
- **Per-account provider**: in ACME Automation, create (or reconfigure) an ACME account with **Challenge Method = DNS-01** and a **DNS Provider**. Provider credentials are **verified before saving** and **encrypted at rest** (Fernet, mirroring the VRRP/MFA secret pattern); they are never returned by the API or written to logs.
|
||||
- **Supported providers**: **Manual** (publish the TXT record yourself in any DNS — including fully internal DNS — then click *Verify*; works everywhere but cannot auto-renew unattended) and **Cloudflare** (API token with `Zone:DNS:Edit` + `Zone:Read`; the TXT record is created and cleaned up automatically and renews unattended). The provider interface is pluggable — more providers can be added without changing the issuance flow.
|
||||
- **Supported providers**: **Manual** (publish the TXT record yourself in any DNS — including fully internal DNS — then click *Verify*; works everywhere but cannot auto-renew unattended), **Cloudflare** (API token with `Zone:DNS:Edit` + `Zone:Read`; the TXT record is created and cleaned up automatically and renews unattended), and **GoDaddy** *(v1.10.0)* (a **Production** API Key + Secret pair from `developer.godaddy.com/keys` — the first key that dashboard issues is an OTE/test key and is rejected; the zone must be in the same GoDaddy account, which needs at least one registered domain before GoDaddy allows DNS API access at all. A **Personal Access Token** works too: paste it as the API Key and leave the Secret blank — that is the forward path as GoDaddy retires the `sso-key` scheme. TXT records are created and cleaned up automatically and renew unattended). The provider interface is pluggable — more providers can be added without changing the issuance flow.
|
||||
- **Same pipeline**: after validation the certificate follows the normal PENDING → APPLIED flow (assign to clusters / Apply Management) and the agent serves it — identical to HTTP-01 from finalize onward, with **zero agent or rendered-config changes** for DNS-01.
|
||||
- **Manual flow**: the order detail shows the exact `_acme-challenge.<domain>` record name + TXT value (copyable); publish it and click *I've added the records — Verify*. For Cloudflare it is automatic.
|
||||
- **Manual flow**: the order detail shows the exact `_acme-challenge.<domain>` record name + TXT value (copyable); publish it and click *I've added the records — Verify*. For Cloudflare and GoDaddy it is automatic.
|
||||
- **Resilience**: a propagation-lag failure is recovered by a **bounded fresh-order retry chain** (1 original + 3 retries with increasing backoff, kept under Let's Encrypt's rate limits); any orphaned TXT record is cleaned up by a reconcile sweep. The order detail shows a DNS-01 event timeline (publish → validation → cleanup).
|
||||
- **Wildcards**: `*.example.com` is validated at `_acme-challenge.example.com`; it does **not** cover the apex — add `example.com` as a separate name if you need both (the providers handle the two coexisting TXT values automatically).
|
||||
- **Scope (this release)**: the Site Wizard remains HTTP-01-only; issue DNS-01 / wildcard certificates from **ACME Automation**.
|
||||
@@ -2474,6 +2474,7 @@ Developed with ❤️ for the HAProxy community
|
||||
|
||||
## Release Notes
|
||||
|
||||
- **v1.10.0** (2026-08-07) — **GoDaddy DNS provider for DNS-01** (Issue #35 follow-up): DNS-01 challenges can now be published and cleaned up automatically through **GoDaddy**, alongside the existing Manual and Cloudflare providers, so wildcard and internal-cluster certificates on GoDaddy-hosted zones **renew unattended**. Credentials are a **Production API Key + Secret** pair from `developer.godaddy.com/keys` (a **Personal Access Token** also works — paste it as the Key and leave the Secret blank, which is the forward path as GoDaddy retires `sso-key`); they are **verified against the GoDaddy API before being saved** and **encrypted at rest** (Fernet, the same path as Cloudflare), and are never returned by the API, logged, or written to an order event. GoDaddy's v1 API has **no per-value TXT write** — `PUT` replaces an entire RRset — so add/remove are read-modify-write with sibling values merged back, empty-`data` tombstones filtered out, and `DELETE` used for the last value (`PUT []` is rejected); this is what keeps the **apex + wildcard** case (two TXT values at one `_acme-challenge` name) working, and the record path is hard-gated so it can never collapse onto the zone-wide endpoint that would wipe SPF/DKIM/DMARC. Zone lookup probes the records API rather than the domain listing, so **delegated sub-zones** resolve and small accounts are not falsely rejected. Registry-only addition: one new provider module plus one registry line — no frontend change (the credential form is schema-driven). No schema, API-shape, agent, or rendered-config changes; Manual, Cloudflare and HTTP-01 are unaffected.
|
||||
- **v1.9.0** (2026-08-04) — **CSR creation** (in-app key + CSR generation and signed-certificate import): a new **CSR tab** on the SSL Certificates page generates a private key and Certificate Signing Request server-side (RSA 2048/4096 or ECDSA P-256/P-384; full subject — O/OU/L/ST/C/email — plus DNS SANs with wildcard support), for certificates signed by an **external or corporate CA**. The operator downloads/copies the CSR PEM, has it signed, then imports the signed certificate (+ optional chain): the backend verifies the certificate against the stored key (hard gate), rejects expired certs, warns on SAN drift, and creates a normal SSL certificate entry (source `CSR`) that flows through the standard **PENDING → Apply Management → agent pull** pipeline. The private key **never leaves the server** — no CSR endpoint returns it, and after import the CSR row's key copy is destroyed (the key then lives only on the certificate, like every other key). Additive schema change: one new table `ssl_csrs` (SCHEMA_VERSION 9 → 10, auto-migrated, no existing table altered); key generation runs off the event loop and is rate-limited per user; existing `ssl.*` permissions govern all new endpoints. No agent or rendered-config changes.
|
||||
- **v1.8.10** (2026-07-20) — **Security hardening** (GHSA-7rhv-c5pc-69r8, GHSA-3p5c-m5m4-mjpx, GHSA-3vh4): three advisory classes remediated, backend-only, no agent changes. (1) **RCE**: the agent script-template read/write endpoints now require the `agents.version` permission on top of authentication — a poisoned template is executed as root on every HAProxy node, so authentication alone was insufficient. (2) **Missing authentication**: operator/UI endpoints that were served without a JWT (dashboard stats, pool/cluster listings, agent inventory, WAF rules, config validate/optimize, SSL config-versions, health deep/agents/clusters) are now gated by a `require_authenticated_user` dependency, and agent data-plane endpoints that treated the `X-API-Key` header as *optional* (heartbeat, config, ssl-certificates, upgrade-status, pending-requests) now hard-reject a missing key. In every case the auth check was moved **ahead of** the handler's `try:` block so a 401 can no longer be rewritten into a 500 by the generic exception handler. (3) **SSRF**: a new `utils/ssrf_guard.py` (https-only, IPv4-pinned connector, all resolved addresses must be public, no redirects) protects the ACME directory fetch, the signed-request target and the ACME connection test, which accept operator- or DB-supplied URLs; the connection test also stopped reflecting arbitrary upstream JSON. Frontend dependency advisories patched in the same release. No schema, API-shape or rendered-config changes.
|
||||
- **v1.8.9** (2026-07-13) — **ACL `-f` pattern-file support** (Issue #38 follow-up): ACL definitions that reference a host-side pattern file (`acl … -f /etc/haproxy/lists/blocked.lst`) are accepted on import and edit instead of being rejected. The referenced file lives on the HAProxy node and cannot be validated from the manager, so the manager emits an **advisory warning** rather than a hard rejection and lets the agent's `haproxy -c` check be the fail-safe gate (a broken reference fails validation on the node and the previous config is restored). Consistent with the SPOE handling introduced in v1.8.8.
|
||||
|
||||
@@ -1,3 +1,41 @@
|
||||
# Upgrade Notes — v1.10.0 (GoDaddy DNS-01 provider)
|
||||
|
||||
**Backward compatible & additive.** Nothing changes unless you select **GoDaddy** as an ACME
|
||||
account's DNS provider:
|
||||
|
||||
- **Schema:** **no `SCHEMA_VERSION` bump.** The GoDaddy credentials (API Key + Secret) are stored
|
||||
as two keys inside the *existing* encrypted
|
||||
`letsencrypt_account_dns_credentials.credentials_encrypted` blob — no new table, no new column,
|
||||
no migration.
|
||||
- **✅ Built-in roles are NOT re-seeded.** The re-seed warning in the v1.9.0 notes below is
|
||||
triggered by a `SCHEMA_VERSION` bump. This release does not bump it, so any customization you
|
||||
made to `super_admin` / `operator` / `security_admin` / `viewer` survives untouched.
|
||||
- **Permissions / API shape:** unchanged. `GET /api/letsencrypt/dns-providers` simply returns one
|
||||
extra entry in its `providers` array; every request and response shape is identical, and the
|
||||
credential form is rendered from that schema, so there is no frontend behaviour change either.
|
||||
- **Environment:** no new variable. GoDaddy credentials use the same Fernet-at-rest path as
|
||||
Cloudflare (`DNS_PROVIDER_ENCRYPTION_KEY`, falling back to a key derived from `SECRET_KEY`).
|
||||
- **Agents:** zero agent changes. DNS-01 is invisible to agents; an issued certificate follows the
|
||||
normal PENDING → Apply Management → agent pull pipeline exactly as before.
|
||||
- **Using it:** the API Key must be a **Production** key from `developer.godaddy.com/keys` (the
|
||||
first key that dashboard issues is an OTE/test key and is rejected), the zone must be in the same
|
||||
GoDaddy account, and that account needs at least one registered domain before GoDaddy permits DNS
|
||||
API access. A Personal Access Token also works — paste it as the Key and leave the Secret blank.
|
||||
Credentials are checked against the GoDaddy API before they are stored, so an invalid, OTE or
|
||||
ineligible key fails at save time. Note the check is a **read**: a Personal Access Token that has
|
||||
`domains.domain:read` but not `domains.dns:update` saves successfully and only fails at the first
|
||||
publish, with a 403 in the order timeline.
|
||||
- **Rollback:** don't select GoDaddy. Existing Manual and Cloudflare accounts and all HTTP-01
|
||||
issuance are untouched. **Downgrading after adopting GoDaddy is not a no-op**: on 1.9.0
|
||||
`godaddy` is not a known provider, so any account still set to it degrades to the manual-confirm
|
||||
path (in-flight DNS-01 orders wait for a confirmation nobody can give and expire after 48h, and
|
||||
renewals stop), and the cleanup sweep marks published TXT records cleaned without removing them.
|
||||
Before downgrading, switch affected accounts back to Manual or Cloudflare and let the reconcile
|
||||
sweep remove outstanding `_acme-challenge` records first. The stored credential row itself is
|
||||
inert — an encrypted blob for an unknown provider.
|
||||
|
||||
---
|
||||
|
||||
# Upgrade Notes — v1.9.0 (CSR creation)
|
||||
|
||||
**Backward compatible & additive.** Upgrading to v1.9.0 changes nothing for existing
|
||||
|
||||
@@ -5,8 +5,8 @@ A small adapter layer so DNS-01 challenges can publish/clean up the
|
||||
additive at the RRset level (add/remove a single value by name+content, never
|
||||
overwrite-by-name) so multiple coexisting values at one name (wildcard + apex) work.
|
||||
|
||||
MVP providers: manual (user publishes the TXT themselves) and Cloudflare. New providers
|
||||
plug in via the registry without touching the orchestration.
|
||||
Providers: manual (user publishes the TXT themselves), Cloudflare, and GoDaddy (v1.10.0). New
|
||||
providers plug in via the registry without touching the orchestration.
|
||||
"""
|
||||
from .base import DnsProvider, DnsProviderError
|
||||
from .registry import get_provider, list_providers, is_supported
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
"""GoDaddy DNS provider for ACME DNS-01 (Issue #35 follow-up, v1.10.0).
|
||||
|
||||
Uses the GoDaddy Domains API v1 over aiohttp (no new dependency). The base URL is a hardcoded
|
||||
constant and redirects are not followed (no user-controlled URL — only the already-validated
|
||||
domain name selects which zone is touched), which is the same reason cloudflare.py is exempt from
|
||||
utils/ssrf_guard.py. Every failure is wrapped in DnsProviderError with a SANITIZED message: the
|
||||
API Key and Secret are scrubbed out of any text that could reach a log, an order event, or
|
||||
letsencrypt_orders.error_detail.
|
||||
|
||||
Two GoDaddy-specific hazards drive the shape of this module — neither exists on Cloudflare:
|
||||
|
||||
1. NO PER-VALUE WRITE. `PUT /v1/domains/{d}/records/TXT/{name}` REPLACES the entire RRset at that
|
||||
type+name; it does not merge. A certificate for `example.com` + `*.example.com` publishes two
|
||||
DIFFERENT TXT values at the SAME name `_acme-challenge.example.com` (base.py's additive
|
||||
contract), so a naive single-value PUT would silently destroy the sibling and fail the wildcard
|
||||
authorization. Every mutation here is therefore read-modify-write: GET the current RRset, merge,
|
||||
PUT the whole list back. An EMPTY array is rejected (422 INVALID_BODY, "Records must be
|
||||
specified"), so removing the LAST value must use DELETE — never `PUT []`.
|
||||
|
||||
2. ZONE-DESTRUCTIVE SIBLING PATHS. `PUT /v1/domains/{d}/records/TXT` (three segments, no name)
|
||||
wipes EVERY TXT in the zone — SPF, DKIM, DMARC, Microsoft/Google verification — and
|
||||
`PUT /v1/domains/{d}/records` wipes the whole zone (this is dehydrated issue #430 verbatim).
|
||||
The record path is built only by _rrset_path(), which refuses an empty zone or relative name so
|
||||
a URL can never collapse onto one of those endpoints.
|
||||
|
||||
Concurrency: v1 has no ETag, no If-Match and no per-record id, so read-modify-write can lose an
|
||||
update if two mutations at one name overlap. Today they cannot: orders are advanced sequentially
|
||||
(`for oid in claimed_ids: await advance_dns01_order(oid)` in main.py) and an order's challenges are
|
||||
published sequentially (`for ch in challenges: await provider.add_txt_record(...)` in
|
||||
dns01_orchestrator.py), so the apex+wildcard pair is strictly ordered and the second publish sees
|
||||
the first. _rrset_lock() makes that safety structural rather than incidental. Across REPLICAS the
|
||||
window is real but narrow (two orders publishing at the same record name in overlapping cycles) and
|
||||
self-healing: a lost publish ends `invalid` and the bounded retry chain mints a fresh order, a lost
|
||||
cleanup is retried by the reconcile sweep, and an orphaned `_acme-challenge` TXT is inert. The real
|
||||
fix is the v3 API (POST + DELETE by recordId, natively per-value), which is PAT-only and a
|
||||
follow-up; it is deliberately not used here because v1 + sso-key is what operators can use today.
|
||||
|
||||
Credentials: an API Key + Secret pair from https://developer.godaddy.com/keys. It must be a
|
||||
PRODUCTION key — the first key the dashboard issues is an OTE (test) key and an OTE credential
|
||||
against api.godaddy.com returns 401. A Personal Access Token also works: paste it as the API Key
|
||||
and leave the Secret blank, and the Authorization header becomes `Bearer <token>`. That path is not
|
||||
cosmetic — GoDaddy marks sso-key "deprecated, supported through 2026" and the current v1 OpenAPI
|
||||
advertises only bearer auth, so the PAT is the migration target, not an alternative.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import quote
|
||||
|
||||
import aiohttp
|
||||
|
||||
from .base import DnsProvider, DnsProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
GODADDY_API_BASE = "https://api.godaddy.com/v1"
|
||||
_TIMEOUT = aiohttp.ClientTimeout(total=20)
|
||||
|
||||
# GoDaddy enforces a 600s (10 min) TTL floor at request time. The published v1 OpenAPI declares no
|
||||
# minimum, so a smaller value is not caught by the schema — it fails with
|
||||
# 422 {"code":"INVALID_BODY","fields":[{"message":"must have a minimum value of 600", ...}]}.
|
||||
# Pin the floor; DNS-01 has no reason to want anything longer.
|
||||
_TXT_TTL = 600
|
||||
|
||||
# Read-modify-write serialization, keyed by the RRset (record name), not the zone — the RRset is the
|
||||
# actual unit of contention, and keying on it avoids serializing unrelated subdomains of one zone.
|
||||
# The orchestrator is sequential today (see the module docstring), so this is defence in depth: it
|
||||
# is what stops a future `asyncio.gather()` over the publish loop from silently breaking every
|
||||
# wildcard+apex certificate. Bounded in practice by the certificate inventory of one process, so
|
||||
# there is no eviction; the entries are empty Lock objects.
|
||||
_RRSET_LOCKS: Dict[str, asyncio.Lock] = {}
|
||||
|
||||
|
||||
def _rrset_lock(record_name: str) -> asyncio.Lock:
|
||||
key = (record_name or "").rstrip(".").lower()
|
||||
lock = _RRSET_LOCKS.get(key)
|
||||
if lock is None:
|
||||
# Safe without a guard: a single event loop never preempts between the get and the assign.
|
||||
lock = _RRSET_LOCKS[key] = asyncio.Lock()
|
||||
return lock
|
||||
|
||||
|
||||
def _scrub(text: str, *secrets: str) -> str:
|
||||
"""Remove credential substrings from a message before it can reach a log or an order event.
|
||||
|
||||
GoDaddy error bodies do not echo the Authorization header, so this is belt-and-braces — but it
|
||||
makes base.py's "never leak a secret" invariant structural instead of a matter of care. Short
|
||||
strings are skipped so a 1-2 char credential fragment cannot blank out ordinary prose.
|
||||
"""
|
||||
out = text or ""
|
||||
for secret in secrets:
|
||||
if secret and len(secret) >= 4:
|
||||
out = out.replace(secret, "***")
|
||||
return out[:300]
|
||||
|
||||
|
||||
def _relative_name(fqdn: str, zone: str) -> str:
|
||||
"""Convert an absolute record name to the zone-relative form GoDaddy's API requires.
|
||||
|
||||
GoDaddy record names are RELATIVE to the zone with NO trailing dot, and the zone apex is the
|
||||
literal "@" — never an empty string (which would collapse the URL onto the zone-wide TXT
|
||||
endpoint) and never the domain name itself.
|
||||
|
||||
("_acme-challenge.example.com", "example.com") -> "_acme-challenge"
|
||||
("_acme-challenge.foo.bar.example.com", "example.com") -> "_acme-challenge.foo.bar"
|
||||
("example.com", "example.com") -> "@"
|
||||
"""
|
||||
f = (fqdn or "").rstrip(".").lower()
|
||||
z = (zone or "").rstrip(".").lower()
|
||||
if z and f == z:
|
||||
return "@"
|
||||
if z and f.endswith("." + z):
|
||||
return f[: -(len(z) + 1)]
|
||||
# Defensive: callers always pass a zone that _resolve_domain derived from this very name.
|
||||
return f or "@"
|
||||
|
||||
|
||||
def _rrset_path(zone: str, rel_name: str) -> str:
|
||||
"""Build the 4-segment record path `/domains/{zone}/records/TXT/{name}`.
|
||||
|
||||
SAFETY GATE: an empty rel_name would collapse the URL to `/domains/{zone}/records/TXT` — the
|
||||
endpoint that replaces EVERY TXT record in the zone (SPF, DKIM, DMARC, domain verifications).
|
||||
A "." or ".." segment does the same thing one step later: `quote()` leaves both untouched
|
||||
(they are unreserved) and yarl normalizes dot segments away when it builds the URL, so
|
||||
".../records/TXT/.." would resolve to ".../records" — the whole-zone endpoint. Refuse both
|
||||
rather than build them. `safe=''` percent-encodes the apex "@" as "%40" (accepted bare too,
|
||||
but safer through proxies); "_", "-" and "." are unreserved and pass through unchanged, so a
|
||||
multi-label relative name stays one readable path segment.
|
||||
"""
|
||||
if not zone or not rel_name:
|
||||
raise DnsProviderError("Internal error: refusing to build a zone-wide GoDaddy TXT record path.")
|
||||
if rel_name.strip(".") == "" or any(part in (".", "..") for part in rel_name.split("/")):
|
||||
raise DnsProviderError("Internal error: refusing to build a GoDaddy TXT path from a dot segment.")
|
||||
return f"/domains/{quote(zone, safe='')}/records/TXT/{quote(rel_name, safe='')}"
|
||||
|
||||
|
||||
def _live_values(records: List[Dict]) -> List[str]:
|
||||
"""The non-empty `data` values in an RRset read.
|
||||
|
||||
GoDaddy leaves tombstone rows with `"data": ""` behind at a name after some removals. Echoing
|
||||
one back in a PUT body is rejected with 422 INVALID_BODY, so every field implementation
|
||||
(lego, acme.sh, Posh-ACME) filters them independently — so do we.
|
||||
"""
|
||||
out: List[str] = []
|
||||
for rec in records or []:
|
||||
data = (rec or {}).get("data") or ""
|
||||
if data:
|
||||
out.append(data)
|
||||
return out
|
||||
|
||||
|
||||
def _merge_add(existing: List[Dict], value: str) -> Optional[List[Dict]]:
|
||||
"""PUT body that adds `value` while preserving every coexisting sibling value.
|
||||
|
||||
Returns None when `value` is already present — an idempotent no-op, which is where an ACME
|
||||
retry cycle lands.
|
||||
"""
|
||||
live = _live_values(existing)
|
||||
if value in live:
|
||||
return None
|
||||
return [{"data": d, "ttl": _TXT_TTL} for d in live] + [{"data": value, "ttl": _TXT_TTL}]
|
||||
|
||||
|
||||
def _merge_remove(existing: List[Dict], value: str) -> Optional[List[Dict]]:
|
||||
"""PUT body that removes ONLY `value`, keeping every sibling.
|
||||
|
||||
Three-state result, because GoDaddy needs three different calls:
|
||||
None -> `value` is not there; already gone, tolerate (base.py's remove contract).
|
||||
[] -> it was the last value; the caller must DELETE, since `PUT []` is rejected.
|
||||
list -> PUT this body.
|
||||
"""
|
||||
live = _live_values(existing)
|
||||
if value not in live:
|
||||
return None
|
||||
return [{"data": d, "ttl": _TXT_TTL} for d in live if d != value]
|
||||
|
||||
|
||||
def _require_rrset(body: Any) -> List[Dict]:
|
||||
"""The RRset read, or a refusal.
|
||||
|
||||
FAIL CLOSED. A read that did not come back as a JSON array must never be treated as "the RRset
|
||||
is empty" — the very next call is a full-RRset PUT, so coercing an unreadable read to [] would
|
||||
replace every coexisting sibling value with just ours. Failing instead is free: the orchestrator
|
||||
reverts the publish flag and retries next cycle, while a destructive PUT is unrecoverable.
|
||||
"""
|
||||
if not isinstance(body, list):
|
||||
raise DnsProviderError(
|
||||
"GoDaddy returned an unreadable TXT record list; refusing to replace the record set."
|
||||
)
|
||||
return body
|
||||
|
||||
|
||||
def _error_fields(body: Any) -> Tuple[str, str]:
|
||||
"""The whitelisted (code, message) pair from a GoDaddy error body.
|
||||
|
||||
Only these two string fields are ever read; the raw body is never interpolated into a
|
||||
user-facing message.
|
||||
"""
|
||||
if not isinstance(body, dict):
|
||||
return "", ""
|
||||
code = body.get("code")
|
||||
message = body.get("message")
|
||||
return (code if isinstance(code, str) else ""), (message if isinstance(message, str) else "")
|
||||
|
||||
|
||||
def _retry_after_seconds(headers, body: Any) -> int:
|
||||
"""Seconds to wait after a 429.
|
||||
|
||||
The current platform sends `Retry-After` and `ratelimit-reset` headers with no body, while the
|
||||
legacy v1 OpenAPI documents an `ErrorLimit` body carrying `retryAfterSec`. All three shapes are
|
||||
live in the wild — and so is none of them, hence the 60s default.
|
||||
"""
|
||||
for key in ("Retry-After", "ratelimit-reset"):
|
||||
raw = (headers or {}).get(key)
|
||||
if raw:
|
||||
try:
|
||||
return max(1, int(str(raw).strip()))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(body, dict):
|
||||
raw = body.get("retryAfterSec")
|
||||
if isinstance(raw, int) and raw > 0:
|
||||
return raw
|
||||
return 60
|
||||
|
||||
|
||||
class _GoDaddyHTTPError(DnsProviderError):
|
||||
"""A DnsProviderError that also carries the HTTP status and GoDaddy `code`.
|
||||
|
||||
Callers INSIDE this module branch on the status (tolerate a 404 read-back, fall through a
|
||||
zone probe), while everything outside — dns01_orchestrator, letsencrypt.py — still sees a
|
||||
plain sanitized DnsProviderError and needs no change.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, status: int, code: str = ""):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
|
||||
|
||||
class GoDaddyDNSProvider(DnsProvider):
|
||||
name = "godaddy"
|
||||
label = "GoDaddy"
|
||||
automated = True
|
||||
credential_fields: List[Dict] = [
|
||||
{
|
||||
"key": "api_key",
|
||||
"label": "API Key",
|
||||
"type": "password",
|
||||
"required": True,
|
||||
"max_length": 200,
|
||||
"help": ("Production API Key from developer.godaddy.com/keys — the first key the dashboard "
|
||||
"issues is an OTE (test) key and will be rejected. A Personal Access Token also "
|
||||
"works: paste it here and leave the Secret blank."),
|
||||
},
|
||||
{
|
||||
"key": "api_secret",
|
||||
"label": "API Secret",
|
||||
"type": "password",
|
||||
"required": False,
|
||||
"max_length": 200,
|
||||
"help": ("The Secret half of the same API Key pair. Leave blank ONLY if the field above "
|
||||
"holds a Personal Access Token. The account also needs at least one registered "
|
||||
"domain for GoDaddy to allow DNS API access at all."),
|
||||
},
|
||||
]
|
||||
|
||||
def __init__(self, credentials: Dict[str, str] | None = None):
|
||||
super().__init__(credentials)
|
||||
# Normalize, never validate: dns01_orchestrator.py calls get_provider() OUTSIDE any
|
||||
# DnsProviderError guard, so a constructor that raised on malformed credentials would escape
|
||||
# as an unhandled exception in the 60s background cycle. The UI drops blank fields before
|
||||
# submitting, so a left-blank field arrives as a MISSING key rather than "" — `.get() or ""`
|
||||
# covers both.
|
||||
self._api_key = (self.credentials.get("api_key") or "").strip()
|
||||
self._api_secret = (self.credentials.get("api_secret") or "").strip()
|
||||
# Per-INSTANCE zone cache. A module-level cache would leak one ACME account's zone visibility
|
||||
# into another's; an instance lives for exactly one orchestrator step, which is precisely the
|
||||
# scope where caching pays off (apex + wildcard resolve the same zone from the same name).
|
||||
self._zone_cache: Dict[str, str] = {}
|
||||
|
||||
def _auth_header(self) -> str:
|
||||
"""`sso-key <key>:<secret>` when a Secret is present, else `Bearer <token>` for a PAT.
|
||||
|
||||
Literal prefix, one space, a single colon — no base64, no URL-encoding, no quotes. Keeping
|
||||
this as one swappable string is what makes GoDaddy's sso-key sunset a credential change
|
||||
rather than a code change.
|
||||
"""
|
||||
if self._api_secret:
|
||||
return f"sso-key {self._api_key}:{self._api_secret}"
|
||||
return f"Bearer {self._api_key}"
|
||||
|
||||
def _headers(self) -> Dict[str, str]:
|
||||
# Accept is not optional: these endpoints content-negotiate application/xml and
|
||||
# text/javascript. Content-Type is required on every write or GoDaddy answers 400/415.
|
||||
return {
|
||||
"Authorization": self._auth_header(),
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def _http_error(self, status: int, code: str, message: str, retry_after: Optional[int]) -> _GoDaddyHTTPError:
|
||||
"""Map an HTTP status to a sanitized, operator-actionable DnsProviderError.
|
||||
|
||||
These strings land in acme_order_events and letsencrypt_orders.error_detail and are shown
|
||||
in the order timeline, so each one names what to fix. GoDaddy's own `code`/`message` is
|
||||
appended when present because the two 403 causes — account not eligible for the DNS API vs.
|
||||
a PAT missing `domains.dns:update` — are indistinguishable by status alone. Scrubbing
|
||||
happens HERE, at the single point where provider-supplied text enters a message, so a new
|
||||
caller cannot forget it.
|
||||
"""
|
||||
code = _scrub(code, self._api_key, self._api_secret)
|
||||
message = _scrub(message, self._api_key, self._api_secret)
|
||||
if status == 401:
|
||||
detail = ("GoDaddy rejected the API credentials. Check they are a PRODUCTION Key/Secret pair "
|
||||
"from developer.godaddy.com/keys — the first key the dashboard issues is an OTE "
|
||||
"(test) key and is not valid here.")
|
||||
elif status == 403:
|
||||
detail = ("GoDaddy denied access to the DNS API. The account needs at least one registered "
|
||||
"domain, and a Personal Access Token needs the domains.domain:read and "
|
||||
"domains.dns:update scopes.")
|
||||
elif status == 404:
|
||||
detail = ("GoDaddy has no zone for this domain (check it is registered in this account and "
|
||||
"uses GoDaddy nameservers).")
|
||||
elif status == 409:
|
||||
detail = "GoDaddy reports this domain is not eligible to have its DNS records changed."
|
||||
elif status == 422:
|
||||
detail = "GoDaddy rejected the record change as invalid (HTTP 422)."
|
||||
elif status == 429:
|
||||
detail = f"GoDaddy rate limit reached; retry in ~{retry_after or 60}s."
|
||||
else:
|
||||
detail = f"GoDaddy API error (HTTP {status})."
|
||||
if code or message:
|
||||
detail += f" (GoDaddy: {code}{': ' + message if message else ''})"
|
||||
return _GoDaddyHTTPError(detail, status=status, code=code)
|
||||
|
||||
async def _request(self, session: aiohttp.ClientSession, method: str, path: str, **kwargs) -> Any:
|
||||
"""One GoDaddy API call. Returns the parsed JSON body, or None for the empty-bodied writes.
|
||||
|
||||
Raises a SANITIZED _GoDaddyHTTPError / DnsProviderError — never the credentials, never the
|
||||
request, never a response body verbatim.
|
||||
"""
|
||||
url = f"{GODADDY_API_BASE}{path}"
|
||||
try:
|
||||
async with session.request(
|
||||
method, url, headers=self._headers(), allow_redirects=False, **kwargs
|
||||
) as resp:
|
||||
try:
|
||||
# content_type=None: every GoDaddy write answers 200/204 with an EMPTY body, and
|
||||
# aiohttp would otherwise raise on the missing/other content type before parsing.
|
||||
body = await resp.json(content_type=None)
|
||||
except ValueError:
|
||||
# ONLY a decode failure (JSONDecodeError subclasses ValueError) is swallowed —
|
||||
# an empty write body, or an HTML error page on a >=400. A transport failure
|
||||
# mid-read (ClientPayloadError, TimeoutError) must NOT land here: it would look
|
||||
# identical to "empty body", and a caller that reads an RRset would then see
|
||||
# None and could mistake it for an empty RRset. Those propagate to the handlers
|
||||
# below and become a real DnsProviderError.
|
||||
body = None
|
||||
# 2xx only. Redirects are deliberately not followed (aiohttp would forward the
|
||||
# Authorization header), so a 3xx is a failed call — treating `< 400` as success
|
||||
# would report a redirected write as a silent no-op.
|
||||
if 200 <= resp.status < 300:
|
||||
return body
|
||||
code, message = _error_fields(body)
|
||||
retry_after = _retry_after_seconds(resp.headers, body) if resp.status == 429 else None
|
||||
raise self._http_error(resp.status, code, message, retry_after)
|
||||
except DnsProviderError:
|
||||
raise
|
||||
except aiohttp.ClientError as exc:
|
||||
# Only the exception TYPE is interpolated: an aiohttp client error's str() can carry the
|
||||
# request URL, and the message is persisted to the order timeline.
|
||||
raise DnsProviderError(f"Could not reach the GoDaddy API ({type(exc).__name__}).")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise DnsProviderError(f"Unexpected GoDaddy API failure ({type(exc).__name__}).")
|
||||
|
||||
async def verify_credentials(self) -> Dict:
|
||||
if not self._api_key:
|
||||
return {"ok": False, "detail": "No GoDaddy API Key provided."}
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=_TIMEOUT) as session:
|
||||
# Cheapest read-only check: one request, no zone needed. Deliberately NOT
|
||||
# GET /v1/domains/{domain} — GoDaddy has rejected that details call for small
|
||||
# accounts since 2024-05 while record-level calls keep working, so verifying with it
|
||||
# produces false negatives on accounts where DNS-01 would succeed.
|
||||
body = await self._request(session, "GET", "/domains?limit=1")
|
||||
if not isinstance(body, list):
|
||||
return {"ok": False, "detail": "GoDaddy returned an unexpected response to the credential check."}
|
||||
if not body:
|
||||
# An empty list is NOT a failure: sub-zones delegated to GoDaddy nameservers are
|
||||
# manageable via the records API but never appear in the domain listing.
|
||||
return {"ok": True, "detail": ("GoDaddy credentials valid, but no domains are visible in this "
|
||||
"account — the domain you validate must be registered here, or "
|
||||
"be a zone delegated to GoDaddy nameservers.")}
|
||||
return {"ok": True, "detail": "GoDaddy credentials valid."}
|
||||
except DnsProviderError as exc:
|
||||
detail = str(exc)
|
||||
if not self._api_secret:
|
||||
# The Bearer path is silent otherwise, and a half-filled form is the likeliest cause.
|
||||
detail += (" Note: no API Secret was entered, so the API Key was sent as a Personal Access "
|
||||
"Token (Bearer). If you have a Key + Secret pair, enter both halves.")
|
||||
return {"ok": False, "detail": detail}
|
||||
except Exception: # noqa: BLE001 — never leak an internal/transport error verbatim
|
||||
return {"ok": False, "detail": "Could not verify the GoDaddy credentials."}
|
||||
|
||||
async def _resolve_domain(self, session: aiohttp.ClientSession, record_name: str) -> str:
|
||||
"""Find the most-specific (longest-suffix) GoDaddy-managed zone for an absolute record name.
|
||||
|
||||
GoDaddy has no `/zones?name=` equivalent, so this walks suffixes longest-to-shortest and
|
||||
probes `GET /v1/domains/{candidate}/records/NS`. That probe (rather than the domain listing
|
||||
or the domain-details call) is deliberate: it finds sub-zones delegated to GoDaddy
|
||||
nameservers, which never appear in `GET /v1/domains` at all, and it does not depend on the
|
||||
details endpoint that small accounts are rejected from.
|
||||
"""
|
||||
cached = self._zone_cache.get(record_name)
|
||||
if cached:
|
||||
return cached
|
||||
labels = record_name.rstrip(".").lower().split(".")
|
||||
for i in range(len(labels) - 1):
|
||||
candidate = ".".join(labels[i:])
|
||||
if candidate.count(".") < 1:
|
||||
break # a zone needs at least two labels
|
||||
try:
|
||||
body = await self._request(
|
||||
session, "GET", f"/domains/{quote(candidate, safe='')}/records/NS"
|
||||
)
|
||||
except _GoDaddyHTTPError as exc:
|
||||
if exc.status in (404, 422):
|
||||
continue # not a zone in this account — keep walking
|
||||
# 401/403/409/429/5xx are credential, eligibility or platform failures, not
|
||||
# "wrong zone". Continuing would burn the rate-limit budget re-failing on every
|
||||
# remaining suffix and would bury the real cause under "no managed domain".
|
||||
raise
|
||||
if isinstance(body, list) and body:
|
||||
self._zone_cache[record_name] = candidate
|
||||
return candidate
|
||||
raise DnsProviderError(f"No managed GoDaddy domain found for {record_name}.")
|
||||
|
||||
async def add_txt_record(self, name: str, value: str) -> None:
|
||||
async with _rrset_lock(name):
|
||||
async with aiohttp.ClientSession(timeout=_TIMEOUT) as session:
|
||||
zone = await self._resolve_domain(session, name)
|
||||
path = _rrset_path(zone, _relative_name(name, zone))
|
||||
try:
|
||||
existing = await self._request(session, "GET", path)
|
||||
except _GoDaddyHTTPError as exc:
|
||||
if exc.status != 404:
|
||||
raise
|
||||
# Some accounts 404 reading back a record set in a zone whose WRITES succeed
|
||||
# (acme.sh #6517). Reachable only when the NS probe resolved the zone but the
|
||||
# TXT read 404s — if the NS probe itself 404s we never get here and the caller
|
||||
# sees "No managed GoDaddy domain found", which is the honest answer. We cannot
|
||||
# merge what we cannot read, and a single-value PUT would destroy any coexisting
|
||||
# sibling, so PATCH is the only correct recovery: it is the one genuinely
|
||||
# ADDITIVE primitive in v1 ("Appends DNS records ... Existing records with the
|
||||
# same type and name are preserved"). It cannot dedupe, but a duplicate
|
||||
# identical TXT is harmless for validation and cleanup removes the whole RRset.
|
||||
await self._request(
|
||||
session, "PATCH", f"/domains/{quote(zone, safe='')}/records",
|
||||
json=[{"type": "TXT", "name": _relative_name(name, zone),
|
||||
"data": value, "ttl": _TXT_TTL}],
|
||||
)
|
||||
return
|
||||
body = _merge_add(_require_rrset(existing), value)
|
||||
if body is None:
|
||||
return # already published — idempotent, this is where ACME retries land
|
||||
await self._request(session, "PUT", path, json=body)
|
||||
|
||||
async def remove_txt_record(self, name: str, value: str) -> None:
|
||||
async with _rrset_lock(name):
|
||||
async with aiohttp.ClientSession(timeout=_TIMEOUT) as session:
|
||||
try:
|
||||
zone = await self._resolve_domain(session, name)
|
||||
except _GoDaddyHTTPError as exc:
|
||||
# Raise only what a later sweep could plausibly succeed at. reconcile_dns01_cleanup
|
||||
# swallows the error and leaves dns_record_cleaned FALSE, so the row is re-selected
|
||||
# every cycle — and its query takes a bare LIMIT 50, so rows that can NEVER succeed
|
||||
# (revoked key, account lost DNS-API eligibility) would monopolise the whole
|
||||
# cleanup budget and starve every other account. For those terminal statuses we
|
||||
# give up quietly: the orphaned `_acme-challenge` TXT is inert, and the same
|
||||
# credential failure is already loud on the publish path, where it is actionable.
|
||||
if exc.status == 429 or exc.status >= 500:
|
||||
raise
|
||||
return
|
||||
except DnsProviderError:
|
||||
return # zone genuinely not resolvable — nothing we could clean up
|
||||
path = _rrset_path(zone, _relative_name(name, zone))
|
||||
try:
|
||||
existing = await self._request(session, "GET", path)
|
||||
except _GoDaddyHTTPError as exc:
|
||||
if exc.status == 404:
|
||||
return # RRset (or the read) is gone — tolerate
|
||||
raise
|
||||
body = _merge_remove(_require_rrset(existing), value)
|
||||
if body is None:
|
||||
return # our value is not there — already gone, tolerate
|
||||
if not body:
|
||||
# The LAST value at this name. `PUT []` is rejected (422 INVALID_BODY, "Records
|
||||
# must be specified"), so emptying an RRset REQUIRES DELETE. This removes only
|
||||
# TXT at this exact name; other names and other record types are preserved.
|
||||
# Do NOT fall back to the "write an empty string to delete" folklore — that hack
|
||||
# is what creates the tombstone rows _live_values has to filter.
|
||||
try:
|
||||
await self._request(session, "DELETE", path)
|
||||
except _GoDaddyHTTPError as exc:
|
||||
if exc.status == 404:
|
||||
return # raced with another cleanup — tolerate
|
||||
raise
|
||||
return
|
||||
await self._request(session, "PUT", path, json=body)
|
||||
@@ -10,11 +10,13 @@ from typing import Dict, List, Type
|
||||
|
||||
from .base import DnsProvider
|
||||
from .cloudflare import CloudflareDNSProvider
|
||||
from .godaddy import GoDaddyDNSProvider
|
||||
from .manual import ManualDNSProvider
|
||||
|
||||
_PROVIDERS: Dict[str, Type[DnsProvider]] = {
|
||||
ManualDNSProvider.name: ManualDNSProvider,
|
||||
CloudflareDNSProvider.name: CloudflareDNSProvider,
|
||||
GoDaddyDNSProvider.name: GoDaddyDNSProvider,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+399
-4
@@ -2,7 +2,8 @@
|
||||
|
||||
Covers the TXT-value math (RFC 8555 §8.4 — raw SHA-256 digest, base64url, NOT hex),
|
||||
the _acme-challenge record-name derivation (wildcard stripping), credential encryption
|
||||
round-trip + tamper handling, and the DNS provider registry/allow-list.
|
||||
round-trip + tamper handling, the DNS provider registry/allow-list, and (v1.10.0) the
|
||||
GoDaddy provider's zone-relative name derivation and additive RRset merge math.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
@@ -53,9 +54,9 @@ def test_decrypt_invalid_token_returns_none():
|
||||
|
||||
def test_provider_registry_and_allow_list():
|
||||
names = {p["name"] for p in list_providers()}
|
||||
assert {"manual", "cloudflare"} <= names
|
||||
assert is_supported("manual") and is_supported("cloudflare")
|
||||
assert not is_supported("route53") # not in MVP allow-list
|
||||
assert {"manual", "cloudflare", "godaddy"} <= names
|
||||
assert is_supported("manual") and is_supported("cloudflare") and is_supported("godaddy")
|
||||
assert not is_supported("route53") # not in the allow-list
|
||||
|
||||
assert get_provider("manual").automated is False
|
||||
cf = get_provider("cloudflare", {"api_token": "x"})
|
||||
@@ -91,6 +92,400 @@ def test_cloudflare_token_sanitize():
|
||||
assert p._raw_token == '"my-token_123"'
|
||||
|
||||
|
||||
# --- v1.10.0: GoDaddy provider (pure logic only — no network, no DB) ---
|
||||
|
||||
|
||||
def test_godaddy_credential_fields_schema():
|
||||
# Re-assert DnsCredentialsUpsert's validator rules directly against the declared schema, so the
|
||||
# UI can never render a field whose submission the API would reject with a 422.
|
||||
import re
|
||||
from services.dns_providers.godaddy import GoDaddyDNSProvider
|
||||
|
||||
fields = GoDaddyDNSProvider.credential_fields
|
||||
assert [f["key"] for f in fields] == ["api_key", "api_secret"]
|
||||
for f in fields:
|
||||
assert re.match(r"^[a-zA-Z0-9_]{1,50}$", f["key"]) # DnsCredentialsUpsert key regex
|
||||
assert f["type"] == "password" # renders Input.Password, not Input
|
||||
assert isinstance(f["max_length"], int) and 0 < f["max_length"] <= 4000 # validator value cap
|
||||
assert f["help"] and isinstance(f["help"], str) # shown in the Form.Item `extra` slot
|
||||
# api_secret is optional on purpose: leaving it blank is how a Personal Access Token is used
|
||||
# (Bearer), which is the migration path off the sso-key scheme GoDaddy is retiring.
|
||||
assert fields[0]["required"] is True and fields[1]["required"] is False
|
||||
# Must not reuse Cloudflare's field name: the register modal's credential Form.Items are named
|
||||
# cred_<key> in a SHARED form and are not cleared when the provider dropdown changes.
|
||||
assert "api_token" not in {f["key"] for f in fields}
|
||||
|
||||
|
||||
def test_godaddy_provider_is_automated():
|
||||
p = get_provider("godaddy", {"api_key": "k", "api_secret": "s"})
|
||||
assert p.automated is True # else the orchestrator takes the manual-confirm branch
|
||||
assert p.name == "godaddy" and 1 <= len(p.name) <= 50 # dns_provider Field(min_length=1, max_length=50)
|
||||
assert p.label == "GoDaddy"
|
||||
|
||||
|
||||
def test_godaddy_missing_credentials_returns_not_ok():
|
||||
# verify_credentials must RETURN {"ok": False}, never raise: the router turns any non-
|
||||
# DnsProviderError into the information-free generic 422 and the user never sees the reason.
|
||||
import asyncio
|
||||
|
||||
for creds in ({}, {"api_secret": "s"}): # blank UI fields arrive as MISSING keys, not ""
|
||||
r = asyncio.run(get_provider("godaddy", creds).verify_credentials())
|
||||
assert r["ok"] is False and r["detail"]
|
||||
# Short-circuits before any request, so this touches no network.
|
||||
|
||||
|
||||
def test_godaddy_auth_header_formats_and_secret_never_leaks():
|
||||
from services.dns_providers.godaddy import GoDaddyDNSProvider, _scrub
|
||||
|
||||
sentinel = "SENTINEL-SECRET-DO-NOT-LEAK"
|
||||
p = GoDaddyDNSProvider({"api_key": "KEY123", "api_secret": sentinel})
|
||||
# Literal prefix, one space, a single colon — no base64, no quoting.
|
||||
assert p._auth_header() == f"sso-key KEY123:{sentinel}"
|
||||
# No secret -> Personal Access Token. This one branch is the whole sso-key-sunset migration.
|
||||
assert GoDaddyDNSProvider({"api_key": "PAT"})._auth_header() == "Bearer PAT"
|
||||
# _scrub removes credential substrings from anything bound for a log or an order event.
|
||||
assert sentinel not in _scrub(f"boom {sentinel} boom", "KEY123", sentinel)
|
||||
assert "KEY123" not in _scrub("boom KEY123", "KEY123", sentinel)
|
||||
assert _scrub("x" * 500, "KEY123") == "x" * 300 # bounded, so a huge body can't flood an event
|
||||
|
||||
# The channel that actually persists text: _http_error composes the message an order event and
|
||||
# letsencrypt_orders.error_detail will carry, so it must scrub its own inputs — a caller that
|
||||
# forgets to pre-scrub must not be able to leak. (Regression guard: scrubbing used to live at
|
||||
# the single call site in _request instead of here.)
|
||||
exc = p._http_error(403, f"DENIED_{sentinel}", f"token {sentinel} rejected", None)
|
||||
assert sentinel not in str(exc) and "***" in str(exc)
|
||||
|
||||
# This module must not log at all — logging is the one channel _scrub cannot reach, since the
|
||||
# arguments would be formatted by the logging framework rather than passed through it.
|
||||
import inspect
|
||||
import re as _re
|
||||
from services.dns_providers import godaddy as gd_mod
|
||||
|
||||
assert not _re.search(r"\blogger\.\w+\(", inspect.getsource(gd_mod)), \
|
||||
"godaddy.py must not log; surface everything through DnsProviderError so it is scrubbed"
|
||||
|
||||
|
||||
def test_godaddy_relative_record_name():
|
||||
# GoDaddy names are RELATIVE to the zone with no trailing dot; the apex is the literal "@".
|
||||
from services.dns_providers.godaddy import _relative_name
|
||||
|
||||
assert _relative_name("_acme-challenge.example.com", "example.com") == "_acme-challenge"
|
||||
assert _relative_name("_acme-challenge.foo.bar.example.com", "example.com") == "_acme-challenge.foo.bar"
|
||||
assert _relative_name("example.com", "example.com") == "@" # never "" — see _rrset_path
|
||||
assert _relative_name("_acme-challenge.example.com.", "example.com") == "_acme-challenge"
|
||||
assert _relative_name("_ACME-Challenge.Example.COM", "example.com") == "_acme-challenge"
|
||||
# Apex and wildcard produce the SAME relative name — which is exactly why the merge below
|
||||
# has to be additive.
|
||||
apex = ACMEService._challenge_dns_name("example.com")
|
||||
wild = ACMEService._challenge_dns_name("*.example.com")
|
||||
assert _relative_name(apex, "example.com") == _relative_name(wild, "example.com") == "_acme-challenge"
|
||||
|
||||
|
||||
def test_godaddy_rrset_merge_is_additive():
|
||||
# THE critical test: GoDaddy's PUT REPLACES an entire RRset, so the merge math is the only thing
|
||||
# keeping a wildcard+apex certificate's two coexisting TXT values alive.
|
||||
from services.dns_providers.godaddy import _live_values, _merge_add, _merge_remove
|
||||
|
||||
def vals(body):
|
||||
return sorted(r["data"] for r in body)
|
||||
|
||||
assert vals(_merge_add([{"data": "valueA", "ttl": 600}], "valueB")) == ["valueA", "valueB"]
|
||||
assert _merge_add([{"data": "valueA"}], "valueA") is None # idempotent; ACME retries land here
|
||||
# Total, not an all()-over-a-computed-list (which passes vacuously on an empty result): the
|
||||
# first publish at a fresh name must emit exactly one element, carrying the 600s TTL floor.
|
||||
assert _merge_add([], "v") == [{"data": "v", "ttl": 600}] # below 600 GoDaddy answers 422
|
||||
# Tombstone rows ({"data": ""}) must never be echoed back — GoDaddy answers 422 INVALID_BODY.
|
||||
assert _live_values([{"data": ""}, {"data": "x"}, {}]) == ["x"]
|
||||
assert vals(_merge_add([{"data": ""}, {"data": "valueA"}], "valueB")) == ["valueA", "valueB"]
|
||||
|
||||
assert vals(_merge_remove([{"data": "valueA"}, {"data": "valueB"}], "valueB")) == ["valueA"]
|
||||
assert _merge_remove([{"data": "valueA"}], "valueZ") is None # already gone — tolerate
|
||||
assert _merge_remove([], "valueZ") is None
|
||||
# [] means "use DELETE": PUT with an empty array is rejected (422, "Records must be specified").
|
||||
assert _merge_remove([{"data": "valueA"}], "valueA") == []
|
||||
assert _merge_remove([{"data": ""}, {"data": "valueA"}], "valueA") == []
|
||||
|
||||
|
||||
def test_godaddy_never_builds_a_zone_wide_txt_path():
|
||||
# A 3-segment path (.../records/TXT) is the endpoint that wipes EVERY TXT in the zone — SPF,
|
||||
# DKIM, DMARC, domain verifications. An empty relative name must never be able to produce it.
|
||||
from services.dns_providers.godaddy import _rrset_path
|
||||
|
||||
p = _rrset_path("example.com", "_acme-challenge")
|
||||
assert p == "/domains/example.com/records/TXT/_acme-challenge"
|
||||
assert p.count("/") == 5 and not p.endswith("/TXT")
|
||||
assert _rrset_path("example.com", "@").endswith("/%40") # apex percent-encoded for proxy safety
|
||||
# "." and ".." survive quote() and are then normalized away by yarl when the URL is built, so
|
||||
# ".../records/TXT/.." would resolve to the whole-zone endpoint. They must be refused too.
|
||||
for bad in [("example.com", ""), ("", "_acme-challenge"), ("example.com", "."),
|
||||
("example.com", ".."), ("example.com", "...")]:
|
||||
raised = False
|
||||
try:
|
||||
_rrset_path(*bad)
|
||||
except DnsProviderError:
|
||||
raised = True
|
||||
assert raised, f"_rrset_path{bad} must refuse to build a zone-wide TXT path"
|
||||
# And the only way to reach those inputs — a malformed domain — really does produce them.
|
||||
from services.dns_providers.godaddy import _relative_name as _rel
|
||||
assert _rel("..example.com", "example.com") == "."
|
||||
|
||||
|
||||
def test_godaddy_credential_encryption_roundtrip():
|
||||
# The two-field credential dict rides the same Fernet blob as Cloudflare's single token.
|
||||
reset_fernet_for_tests()
|
||||
creds = {"api_key": "gd-key-plaintext", "api_secret": "gd-secret-plaintext"}
|
||||
token = encrypt_dns_credentials(creds)
|
||||
assert "gd-key-plaintext" not in token and "gd-secret-plaintext" not in token # ciphertext
|
||||
assert decrypt_dns_credentials(token) == creds
|
||||
# This sorted key list is exactly what GET /dns-credentials exposes as credential_fields_present
|
||||
# — names only, never values.
|
||||
assert sorted(decrypt_dns_credentials(token).keys()) == ["api_key", "api_secret"]
|
||||
|
||||
|
||||
_GD_NS = "/domains/example.com/records/NS"
|
||||
_GD_TXT = "/domains/example.com/records/TXT/_acme-challenge"
|
||||
|
||||
|
||||
def _gd_provider(responses):
|
||||
"""A GoDaddy provider whose _request is replaced by a recorder.
|
||||
|
||||
The pure-merge tests above prove the MATH; this proves the WRITE PATH actually uses it. Without
|
||||
it, replacing the merge with a single-value PUT — the mutation that silently destroys the
|
||||
sibling value of every wildcard+apex certificate — leaves the whole suite green.
|
||||
|
||||
`responses` maps (method, path) -> value to return, or an Exception to raise. Unmapped calls
|
||||
return None, which is how the zone suffix-walk's failed probes are modelled.
|
||||
"""
|
||||
import types
|
||||
from services.dns_providers.godaddy import GoDaddyDNSProvider
|
||||
|
||||
calls = []
|
||||
|
||||
async def _fake_request(self, session, method, path, **kwargs):
|
||||
calls.append((method, path, kwargs.get("json")))
|
||||
result = responses.get((method, path))
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
return result
|
||||
|
||||
p = GoDaddyDNSProvider({"api_key": "k", "api_secret": "s"})
|
||||
p._request = types.MethodType(_fake_request, p)
|
||||
return p, calls
|
||||
|
||||
|
||||
def _assert_never_zone_wide(calls):
|
||||
# A write to .../records or .../records/TXT replaces every TXT (or every record) in the zone.
|
||||
for method, path, _json in calls:
|
||||
if method in ("PUT", "DELETE"):
|
||||
assert not path.endswith("/records"), f"zone-wide write: {method} {path}"
|
||||
assert not path.endswith("/records/TXT"), f"type-wide write: {method} {path}"
|
||||
|
||||
|
||||
def test_godaddy_add_write_path_merges_siblings():
|
||||
import asyncio
|
||||
|
||||
# An existing sibling value at the same name — the apex half of an apex+wildcard certificate.
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [{"data": "valueA", "ttl": 600}],
|
||||
})
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "valueB"))
|
||||
|
||||
writes = [c for c in calls if c[0] in ("PUT", "PATCH", "DELETE")]
|
||||
assert len(writes) == 1 and writes[0][0] == "PUT" and writes[0][1] == _GD_TXT
|
||||
# BOTH values must be in the body: GoDaddy's PUT replaces the whole RRset.
|
||||
assert sorted(r["data"] for r in writes[0][2]) == ["valueA", "valueB"]
|
||||
_assert_never_zone_wide(calls)
|
||||
|
||||
|
||||
def test_godaddy_add_write_path_is_idempotent_and_fails_closed():
|
||||
import asyncio
|
||||
|
||||
# Already published -> no write at all (this is where an ACME retry cycle lands).
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [{"data": "valueB", "ttl": 600}],
|
||||
})
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "valueB"))
|
||||
assert [c for c in calls if c[0] != "GET"] == []
|
||||
|
||||
# Unreadable RRset read (2xx whose body did not parse as a list) must FAIL, never be treated as
|
||||
# an empty RRset — the PUT that follows would replace the sibling values with only ours.
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): None,
|
||||
})
|
||||
raised = False
|
||||
try:
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "valueB"))
|
||||
except DnsProviderError:
|
||||
raised = True
|
||||
assert raised, "an unreadable RRset read must not be coerced into an empty RRset"
|
||||
assert [c for c in calls if c[0] != "GET"] == []
|
||||
|
||||
|
||||
def test_godaddy_remove_write_path_uses_delete_for_the_last_value():
|
||||
import asyncio
|
||||
|
||||
# Two values -> PUT back the survivor only.
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [{"data": "valueA"}, {"data": "valueB"}],
|
||||
})
|
||||
asyncio.run(p.remove_txt_record("_acme-challenge.example.com", "valueB"))
|
||||
writes = [c for c in calls if c[0] != "GET"]
|
||||
assert len(writes) == 1 and writes[0][0] == "PUT"
|
||||
assert [r["data"] for r in writes[0][2]] == ["valueA"]
|
||||
|
||||
# Last value -> DELETE. `PUT []` is rejected by GoDaddy (422 INVALID_BODY), so an empty PUT
|
||||
# body would make every cleanup fail forever.
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [{"data": "valueA"}],
|
||||
})
|
||||
asyncio.run(p.remove_txt_record("_acme-challenge.example.com", "valueA"))
|
||||
writes = [c for c in calls if c[0] != "GET"]
|
||||
assert len(writes) == 1 and writes[0] == ("DELETE", _GD_TXT, None)
|
||||
assert not any(c[0] == "PUT" and c[2] == [] for c in calls)
|
||||
|
||||
# Value already gone -> no write, no error.
|
||||
p, calls = _gd_provider({
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [{"data": "valueA"}],
|
||||
})
|
||||
asyncio.run(p.remove_txt_record("_acme-challenge.example.com", "valueZ"))
|
||||
assert [c for c in calls if c[0] != "GET"] == []
|
||||
_assert_never_zone_wide(calls)
|
||||
|
||||
|
||||
class _FakeGDResponse:
|
||||
"""Minimal stand-in for aiohttp's ClientResponse: status, headers, and json()."""
|
||||
|
||||
_NO_BODY = object()
|
||||
|
||||
def __init__(self, status, body=_NO_BODY, headers=None):
|
||||
self.status = status
|
||||
self._body = body
|
||||
self.headers = headers or {}
|
||||
|
||||
async def json(self, content_type=None):
|
||||
if self._body is _FakeGDResponse._NO_BODY:
|
||||
raise ValueError("no body to decode") # what an empty 204 does
|
||||
return self._body
|
||||
|
||||
|
||||
class _FakeGDSession:
|
||||
def __init__(self, response):
|
||||
self._response = response
|
||||
self.calls = []
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
self.calls.append((method, url, kwargs))
|
||||
response = self._response
|
||||
|
||||
class _Ctx:
|
||||
async def __aenter__(self_inner):
|
||||
return response
|
||||
|
||||
async def __aexit__(self_inner, *exc):
|
||||
return False
|
||||
|
||||
return _Ctx()
|
||||
|
||||
|
||||
def test_godaddy_request_status_handling():
|
||||
import asyncio
|
||||
from services.dns_providers.godaddy import GoDaddyDNSProvider
|
||||
|
||||
p = GoDaddyDNSProvider({"api_key": "KEY123", "api_secret": "SEC456"})
|
||||
|
||||
def call(response):
|
||||
session = _FakeGDSession(response)
|
||||
try:
|
||||
return asyncio.run(p._request(session, "PUT", "/domains/example.com/records/TXT/x",
|
||||
json=[{"data": "v", "ttl": 600}])), None, session
|
||||
except DnsProviderError as exc:
|
||||
return None, str(exc), session
|
||||
|
||||
# 204 with an EMPTY body is the normal answer to every GoDaddy write — it must not raise.
|
||||
body, err, session = call(_FakeGDResponse(204))
|
||||
assert body is None and err is None
|
||||
# Redirects are deliberately not followed (aiohttp would forward the Authorization header), so
|
||||
# a 3xx is a FAILED call. Treating it as success would report a redirected write as a no-op.
|
||||
_kw = session.calls[0][2]
|
||||
assert _kw["allow_redirects"] is False
|
||||
assert _kw["headers"]["Authorization"] == "sso-key KEY123:SEC456"
|
||||
assert _kw["headers"]["Accept"] == "application/json"
|
||||
for status in (301, 302, 307):
|
||||
body, err, _ = call(_FakeGDResponse(status))
|
||||
assert body is None and err and str(status) in err, f"HTTP {status} must not read as success"
|
||||
|
||||
# 200 with a list is passed through verbatim.
|
||||
body, err, _ = call(_FakeGDResponse(200, [{"data": "v"}]))
|
||||
assert err is None and body == [{"data": "v"}]
|
||||
|
||||
# Error mapping: each message must name what the operator has to fix.
|
||||
_, err, _ = call(_FakeGDResponse(401, {"code": "UNABLE_TO_AUTHENTICATE", "message": "nope"}))
|
||||
assert "PRODUCTION" in err and "UNABLE_TO_AUTHENTICATE" in err
|
||||
_, err, _ = call(_FakeGDResponse(403, {"code": "ACCESS_DENIED", "message": "not allowed"}))
|
||||
assert "domains.dns:update" in err
|
||||
# 429: Retry-After wins; the legacy body field is the fallback; absent both -> 60s default.
|
||||
_, err, _ = call(_FakeGDResponse(429, None, {"Retry-After": "17"}))
|
||||
assert "~17s" in err
|
||||
_, err, _ = call(_FakeGDResponse(429, {"retryAfterSec": 42}))
|
||||
assert "~42s" in err
|
||||
_, err, _ = call(_FakeGDResponse(429, {"Retry-After": "not-a-number"}))
|
||||
assert "~60s" in err
|
||||
# A non-dict error body must not crash the error mapper.
|
||||
_, err, _ = call(_FakeGDResponse(500, "<html>gateway</html>"))
|
||||
assert "500" in err
|
||||
|
||||
# A transport failure MID-READ must not be mistaken for "empty body". Only a decode error may
|
||||
# be swallowed: a caller reading an RRset would otherwise see None and could take it for an
|
||||
# empty record set, and the full-RRset PUT that follows would destroy the sibling values.
|
||||
import aiohttp
|
||||
|
||||
class _TruncatedResponse(_FakeGDResponse):
|
||||
async def json(self, content_type=None):
|
||||
raise aiohttp.ClientPayloadError("connection closed mid-body")
|
||||
|
||||
body, err, _ = call(_TruncatedResponse(200))
|
||||
assert body is None and err and "GoDaddy" in err
|
||||
|
||||
|
||||
def test_godaddy_zone_resolution_walks_suffixes_and_caches():
|
||||
import asyncio
|
||||
from services.dns_providers.godaddy import _GoDaddyHTTPError
|
||||
|
||||
# The deepest candidate is not a zone (404 = "not this zone"); the walk must continue to the
|
||||
# registrable domain and then reuse it, so the second challenge at the same name costs no probe.
|
||||
p, calls = _gd_provider({
|
||||
("GET", "/domains/_acme-challenge.example.com/records/NS"):
|
||||
_GoDaddyHTTPError("nope", status=404, code="UNKNOWN_DOMAIN"),
|
||||
("GET", _GD_NS): [{"data": "ns1.domaincontrol.com"}],
|
||||
("GET", _GD_TXT): [],
|
||||
})
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "valueA"))
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "valueB"))
|
||||
probes = [c for c in calls if c[1].endswith("/records/NS")]
|
||||
assert len(probes) == 2, "the resolved zone must be cached for the life of the provider"
|
||||
# Relative name derived from the RESOLVED zone, never from the deepest candidate.
|
||||
assert all(c[1] == _GD_TXT for c in calls if "/records/TXT/" in c[1])
|
||||
|
||||
# A credential/eligibility failure during the walk must surface, not be swallowed as
|
||||
# "no managed domain" — otherwise the operator chases a DNS problem that is really a bad key.
|
||||
p, calls = _gd_provider({
|
||||
("GET", "/domains/_acme-challenge.example.com/records/NS"):
|
||||
_GoDaddyHTTPError("denied", status=403, code="ACCESS_DENIED"),
|
||||
})
|
||||
raised = ""
|
||||
try:
|
||||
asyncio.run(p.add_txt_record("_acme-challenge.example.com", "v"))
|
||||
except DnsProviderError as exc:
|
||||
raised = str(exc)
|
||||
assert "denied" in raised and "No managed GoDaddy domain" not in raised
|
||||
|
||||
|
||||
def test_b64url_decode_padding_roundtrip():
|
||||
# Issue #35 v1.8.2: _b64url_decode must round-trip for EVERY length, including base64url strings
|
||||
# whose length is a multiple of 4 (the case the old padding formula '=' * (4 - len%4) over-padded).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.9.0",
|
||||
"releaseName": "CSR creation — in-app key+CSR generation and signed-certificate import",
|
||||
"releaseDate": "2026-08-04"
|
||||
"version": "1.10.0",
|
||||
"releaseName": "GoDaddy DNS provider for ACME DNS-01",
|
||||
"releaseDate": "2026-08-07"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "haproxy-openmanager-frontend",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"description": "HAProxy Load Balancer Management UI",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
|
||||
Reference in New Issue
Block a user