235 lines
8.1 KiB
Python
Executable File
235 lines
8.1 KiB
Python
Executable File
"""Cloudflare v4 DNS client (A/AAAA records) with zone discovery."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
from dataclasses import dataclass
|
|
|
|
from .config import CloudflareConfig
|
|
from .errors import ApiError, ProxdomainError
|
|
from .http import JsonClient, Transport, UrllibTransport
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DnsRecord:
|
|
id: str
|
|
name: str
|
|
type: str
|
|
content: str
|
|
proxied: bool = False
|
|
ttl: int = 1
|
|
|
|
@classmethod
|
|
def from_api(cls, payload: dict) -> "DnsRecord":
|
|
return cls(
|
|
id=str(payload.get("id") or ""),
|
|
name=str(payload.get("name") or ""),
|
|
type=str(payload.get("type") or ""),
|
|
content=str(payload.get("content") or ""),
|
|
proxied=bool(payload.get("proxied") or False),
|
|
ttl=int(payload.get("ttl") or 1),
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Zone:
|
|
id: str
|
|
name: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class UpsertResult:
|
|
action: str # created | updated | unchanged
|
|
record: DnsRecord
|
|
previous: DnsRecord | None = None
|
|
|
|
@property
|
|
def changed(self) -> bool:
|
|
return self.action != "unchanged"
|
|
|
|
|
|
class CloudflareClient:
|
|
def __init__(
|
|
self,
|
|
config: CloudflareConfig,
|
|
*,
|
|
http: JsonClient | None = None,
|
|
transport: Transport | None = None,
|
|
) -> None:
|
|
self.config = config
|
|
if http is None:
|
|
http = JsonClient(
|
|
config.api_url,
|
|
transport=transport or UrllibTransport(),
|
|
timeout=config.timeout,
|
|
retries=config.retries,
|
|
)
|
|
self.http = http
|
|
self.http.default_headers["Authorization"] = f"Bearer {config.resolve_token()}"
|
|
self._zone_cache: dict[str, Zone | None] = {}
|
|
|
|
# -- token / zones --------------------------------------------------
|
|
def verify_token(self) -> str:
|
|
data = self.http.get("/user/tokens/verify")
|
|
result = data.get("result") if isinstance(data, dict) else None
|
|
return str((result or {}).get("status") or "unknown")
|
|
|
|
def list_zones(self) -> list[Zone]:
|
|
zones: list[Zone] = []
|
|
page = 1
|
|
while page <= 10:
|
|
data = self.http.get("/zones", {"per_page": 50, "page": page})
|
|
rows = _result_list(data)
|
|
zones.extend(Zone(id=str(z["id"]), name=str(z["name"])) for z in rows if z.get("id"))
|
|
info = data.get("result_info") if isinstance(data, dict) else None
|
|
total_pages = int((info or {}).get("total_pages") or 1)
|
|
if page >= total_pages or not rows:
|
|
break
|
|
page += 1
|
|
return zones
|
|
|
|
def find_zone(self, fqdn: str, base_domain: str | None = None) -> Zone:
|
|
candidates = _zone_candidates(fqdn, base_domain)
|
|
for candidate in candidates:
|
|
if candidate in self._zone_cache:
|
|
cached = self._zone_cache[candidate]
|
|
if cached is not None:
|
|
return cached
|
|
continue
|
|
data = self.http.get("/zones", {"name": candidate, "per_page": 50})
|
|
rows = _result_list(data)
|
|
zone = None
|
|
for row in rows:
|
|
if str(row.get("name", "")).lower() == candidate.lower() and row.get("id"):
|
|
zone = Zone(id=str(row["id"]), name=str(row["name"]))
|
|
break
|
|
self._zone_cache[candidate] = zone
|
|
if zone is not None:
|
|
return zone
|
|
raise ProxdomainError(
|
|
"no Cloudflare zone found for "
|
|
f"{fqdn} (tried: {', '.join(candidates)}); "
|
|
"check general.base_domain and that the token can read the zone"
|
|
)
|
|
|
|
# -- records --------------------------------------------------------
|
|
def list_records(
|
|
self, zone_id: str, *, name: str | None = None, rtype: str | None = None
|
|
) -> list[DnsRecord]:
|
|
params = {"per_page": 100}
|
|
if name:
|
|
params["name"] = name
|
|
if rtype:
|
|
params["type"] = rtype
|
|
data = self.http.get(f"/zones/{zone_id}/dns_records", params)
|
|
records = []
|
|
for row in _result_list(data):
|
|
if not isinstance(row, dict) or not row.get("id"):
|
|
continue
|
|
record = DnsRecord.from_api(row)
|
|
if name and record.name.lower() != name.lower():
|
|
continue
|
|
if rtype and record.type.upper() != rtype.upper():
|
|
continue
|
|
records.append(record)
|
|
return records
|
|
|
|
def upsert_address_record(
|
|
self,
|
|
zone_id: str,
|
|
fqdn: str,
|
|
address: str,
|
|
*,
|
|
proxied: bool | None = None,
|
|
ttl: int | None = None,
|
|
comment: str | None = None,
|
|
) -> UpsertResult:
|
|
rtype = _record_type(address)
|
|
proxied = self.config.proxied if proxied is None else proxied
|
|
ttl = self.config.ttl if ttl is None else ttl
|
|
# Cloudflare forces TTL 1 (automatic) on proxied records; compare against
|
|
# that value so a configured 300 does not trigger a PATCH on every run.
|
|
ttl = 1 if proxied else ttl
|
|
comment = self.config.record_comment if comment is None else comment
|
|
|
|
existing = self.list_records(zone_id, name=fqdn, rtype=rtype)
|
|
if existing:
|
|
current = existing[0]
|
|
same_content = current.content == address
|
|
same_proxy = current.proxied == proxied
|
|
same_ttl = current.ttl == ttl
|
|
if same_content and same_proxy and same_ttl:
|
|
return UpsertResult("unchanged", current)
|
|
payload = {
|
|
"type": rtype,
|
|
"name": fqdn,
|
|
"content": address,
|
|
"ttl": ttl,
|
|
"proxied": proxied,
|
|
}
|
|
if comment:
|
|
payload["comment"] = comment
|
|
data = self.http.patch(f"/zones/{zone_id}/dns_records/{current.id}", payload)
|
|
return UpsertResult("updated", _record_from_response(data, current), current)
|
|
|
|
payload = {
|
|
"type": rtype,
|
|
"name": fqdn,
|
|
"content": address,
|
|
"ttl": ttl,
|
|
"proxied": proxied,
|
|
}
|
|
if comment:
|
|
payload["comment"] = comment
|
|
data = self.http.post(f"/zones/{zone_id}/dns_records", payload)
|
|
return UpsertResult("created", _record_from_response(data, None))
|
|
|
|
def delete_record(self, zone_id: str, record_id: str) -> bool:
|
|
try:
|
|
self.http.delete(f"/zones/{zone_id}/dns_records/{record_id}")
|
|
except ApiError as exc:
|
|
if exc.status == 404:
|
|
return False
|
|
raise
|
|
return True
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
def _record_type(address: str) -> str:
|
|
try:
|
|
version = ipaddress.ip_address(address).version
|
|
except ValueError as exc:
|
|
raise ProxdomainError(f"not a valid IP address: {address!r}") from exc
|
|
return "A" if version == 4 else "AAAA"
|
|
|
|
|
|
def _record_from_response(data: object, previous: DnsRecord | None) -> DnsRecord:
|
|
if isinstance(data, dict):
|
|
inner = data.get("result", data)
|
|
if isinstance(inner, dict) and inner.get("id"):
|
|
return DnsRecord.from_api(inner)
|
|
if previous is not None:
|
|
return previous
|
|
raise ProxdomainError("Cloudflare returned an unexpected DNS record payload")
|
|
|
|
|
|
def _result_list(data: object) -> list[dict]:
|
|
if isinstance(data, dict) and isinstance(data.get("result"), list):
|
|
return [row for row in data["result"] if isinstance(row, dict)]
|
|
return []
|
|
|
|
|
|
def _zone_candidates(fqdn: str, base_domain: str | None) -> list[str]:
|
|
fqdn = fqdn.strip().lower().rstrip(".")
|
|
labels = fqdn.split(".")
|
|
suffixes = [".".join(labels[i:]) for i in range(len(labels) - 1)]
|
|
ordered: list[str] = []
|
|
if base_domain:
|
|
base = base_domain.strip().lower().rstrip(".")
|
|
if fqdn == base or fqdn.endswith("." + base):
|
|
ordered.append(base)
|
|
for suffix in reversed(suffixes): # shortest first (closest to the apex)
|
|
if suffix not in ordered:
|
|
ordered.append(suffix)
|
|
return ordered
|