From ee59526f0a95e647639eba3b0f0f89428b694bd1 Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 16:24:15 +0200 Subject: [PATCH 1/7] feat: reconcile Forward Email domain settings and aliases from git New opt-in feature, shaped like `delegation:`/`octodns-gitops-delegate`: a `forward_email:` block in config.yaml claims a domain list, and one `mail/forward-email/.yaml` per claimed domain holds the desired settings, read-only expectations and aliases. Package defaults are the only layer shared across repos (each repo's CI sees only itself). `octodns-gitops-forwardemail`: - dry-run by default, `--doit` writes; `--domain` scopes - never creates or deletes domains; a claimed domain missing from the account is an error - `--prune` (off by default) deletes aliases absent from git inside claimed domains only, after a second listing agrees with the first; an alias with `has_imap` or stored mail blocks the run instead - `--export` writes the files from live state (defaults omitted, regex alias names single-quoted); a fresh export must plan as zero changes - `--drift` checks FE's generated DKIM/return-path/verification/DMARC `rua`/MX records against the repo's zone file plus the read-only expectations; `has_strict_dmarc` is derived from the zone's own `p=` Only the 13 fields Forward Email's update controller reads are declarable as settings; `max_quota_per_alias`/`bounce_webhook` are write-only and ride along with real changes. Alias `max_quota` is compared in bytes (bytes on GET, human string on PUT, blank = reset). Makefile template gains mail-plan, mail-apply, mail-drift, mail-export (DOMAIN=, PRUNE=1). 81 new tests; suite 348 passing. --- README.md | 50 +++ pyproject.toml | 1 + src/octodns_gitops/bootstrap/makefile.py | 31 +- src/octodns_gitops/cli/forward_email.py | 220 ++++++++++++ src/octodns_gitops/forward_email/__init__.py | 1 + src/octodns_gitops/forward_email/api.py | 117 ++++++ src/octodns_gitops/forward_email/config.py | 279 +++++++++++++++ src/octodns_gitops/forward_email/drift.py | 103 ++++++ src/octodns_gitops/forward_email/export.py | 110 ++++++ src/octodns_gitops/forward_email/reconcile.py | 216 +++++++++++ tests/bootstrap/test_makefile.py | 11 +- tests/cli/test_forward_email.py | 337 ++++++++++++++++++ tests/forward_email/__init__.py | 0 tests/forward_email/test_api.py | 94 +++++ tests/forward_email/test_config.py | 228 ++++++++++++ tests/forward_email/test_drift.py | 105 ++++++ tests/forward_email/test_export.py | 123 +++++++ tests/forward_email/test_reconcile.py | 256 +++++++++++++ 18 files changed, 2279 insertions(+), 3 deletions(-) create mode 100644 src/octodns_gitops/cli/forward_email.py create mode 100644 src/octodns_gitops/forward_email/__init__.py create mode 100644 src/octodns_gitops/forward_email/api.py create mode 100644 src/octodns_gitops/forward_email/config.py create mode 100644 src/octodns_gitops/forward_email/drift.py create mode 100644 src/octodns_gitops/forward_email/export.py create mode 100644 src/octodns_gitops/forward_email/reconcile.py create mode 100644 tests/cli/test_forward_email.py create mode 100644 tests/forward_email/__init__.py create mode 100644 tests/forward_email/test_api.py create mode 100644 tests/forward_email/test_config.py create mode 100644 tests/forward_email/test_drift.py create mode 100644 tests/forward_email/test_export.py create mode 100644 tests/forward_email/test_reconcile.py diff --git a/README.md b/README.md index 32f8197..06d7920 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,56 @@ filters: - `octodns-gitops-drift` - Check for drift between live DNS and local zones - `octodns-gitops-report` - Query nameservers and show consistency report - `octodns-gitops-init` - Generate Makefile for dns-zones repositories +- `octodns-gitops-forwardemail` - Reconcile Forward Email domain settings and aliases with per-domain files (see below) + +### Forward Email account settings (opt-in) + +A dns-zones repo can also own the *account* side of its mail domains at [Forward Email](https://forwardemail.net): +domain settings and aliases, kept in `mail/forward-email/.yaml` and reconciled through the REST API. +Opt in with a top-level `forward_email:` block in `config.yaml` (ignored by octoDNS, like `delegation:`): + +```yaml +forward_email: + token: env/FORWARD_EMAIL_API_TOKEN # env/ reference only, never a literal + directory: ./mail/forward-email # default + defaults: # optional repo-level overrides of the package defaults + settings: {} # API-writable domain fields + expect: {} # read-only fields, drift-checked only + alias: {} # alias field defaults + domains: # the ownership boundary: nothing outside it is ever touched + - example.com +``` + +One file per claimed domain; everything equal to the resolved defaults is omitted: + +```yaml +domain: example.com +settings: + ignore_mx_check: true # only fields the API can write +expect: + has_newsletter: true # FE-staff-set fields we want reported on mismatch +aliases: + - name: hello + recipients: [you@example.org] + - name: '/^([\w\-\.]+)$/' # regex names must be single-quoted + recipients: ['$1@example.org'] + is_enabled: false +``` + +Contract: + +- `make mail-plan` is a dry run; `make mail-apply` writes. `DOMAIN=example.com` scopes either. +- Domains are **never created or deleted** from git; a claimed domain missing from the account is an error. +- `PRUNE=1` deletes aliases absent from git, inside claimed domains only, after a second listing + agrees with the first. An alias with `has_imap: true` or stored mail is a mailbox: it is never + pruned and blocks the run until it is added to git or removed in the web UI. +- `make mail-export` writes the files from live state (bootstrap, or re-baseline after a deliberate + web-UI change). A freshly exported file must plan as **zero changes**. +- `make mail-drift` compares FE's generated DNS records (DKIM key, `fe-bounces` CNAME, verification + TXT, the DMARC `rua` address, MX unless `ignore_mx_check`) with the repo's zone file, and reports + read-only expectation mismatches. Exit 1 on any finding. +- `max_quota_per_alias` and `bounce_webhook` cannot be read back from the API: they are sent with + every domain update but never produce a diff on their own. ## Quick Start with mise diff --git a/pyproject.toml b/pyproject.toml index 22149c4..bcab8a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,6 +49,7 @@ octodns-gitops-init = "octodns_gitops.bootstrap.makefile:main" octodns-gitops-delegate = "octodns_gitops.cli.delegate:main" octodns-gitops-dnssec = "octodns_gitops.cli.dnssec:main" octodns-gitops-ovh-token = "octodns_gitops.cli.ovh_token:main" +octodns-gitops-forwardemail = "octodns_gitops.cli.forward_email:main" [tool.hatch.version] # Version is derived from git tags (CalVer YYMM.N, e.g. 2606.1). Untagged diff --git a/src/octodns_gitops/bootstrap/makefile.py b/src/octodns_gitops/bootstrap/makefile.py index a3619e0..a74fad2 100644 --- a/src/octodns_gitops/bootstrap/makefile.py +++ b/src/octodns_gitops/bootstrap/makefile.py @@ -19,7 +19,7 @@ .DEFAULT_GOAL := help -.PHONY: help validate plan apply drift-check report delegate delegate-ns delegate-ds dnssec ovh-token +.PHONY: help validate plan apply drift-check report delegate delegate-ns delegate-ds dnssec ovh-token mail-plan mail-apply mail-drift mail-export help: \t@echo "" @@ -47,6 +47,12 @@ \t@echo " dnssec - Validate DNSSEC delegation (read-only)" \t@echo " ovh-token - Request a scoped OVH consumer key (ENV_PREFIX=OVH_...)" \t@echo "" +\t@echo "Forward Email account settings (opt-in domains under 'forward_email:' in config.yaml):" +\t@echo " mail-plan - DRY-RUN: diff mail/forward-email/.yaml against the account" +\t@echo " mail-apply - APPLY settings and alias changes (PRUNE=1 also deletes aliases absent from git)" +\t@echo " mail-drift - Check FE-generated DNS records and read-only expectations against the repo" +\t@echo " mail-export - Write per-domain files from live state (bootstrap / re-baseline)" +\t@echo "" \t@echo "Options:" \t@echo " ZONE=example.com. - Process only this zone (works with plan, apply, drift-check, report, delegate*, dnssec)" \t@echo " FORCE=1 - Override 30% safety threshold for apply" @@ -54,6 +60,8 @@ \t@echo " SCOPE= - dnssec scope: delegation (default) | all-signed-targets" \t@echo " ENV_PREFIX= - ovh-token credential env prefix (e.g. OVH_AUTOPS)" \t@echo " ALLOW_MANUAL_PENDING=1 - delegate-ns/-ds: treat manual (Gandi) zones as informational" +\t@echo " DOMAIN=example.com - mail-*: process only this Forward Email domain (no trailing dot)" +\t@echo " PRUNE=1 - mail-plan/-apply: also delete aliases absent from git (never mailboxes)" \t@echo " DEBUG=1 - Enable debug output" \t@echo " QUIET= - Disable quiet mode (unset QUIET)" \t@echo " LOGGING_CONFIG= - Override logging config file" @@ -135,6 +143,27 @@ # Request a least-privilege OVH consumer key (ENV_PREFIX=OVH_AUTOPS) ovh-token: \t@octodns-gitops-ovh-token $(if $(ENV_PREFIX),--env-prefix $(ENV_PREFIX),) + +# Forward Email - DRY-RUN diff of account settings and aliases (DOMAIN=, PRUNE=1) +mail-plan: +\t@octodns-gitops-forwardemail --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(PRUNE),--prune,) + +# Forward Email - APPLY settings and alias changes (never creates or deletes domains) +mail-apply: +\t@echo "" +\t@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +\t@echo " APPLYING FORWARD EMAIL ACCOUNT CHANGES" +\t@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +\t@echo "" +\t@octodns-gitops-forwardemail --doit --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(PRUNE),--prune,) + +# Forward Email - FE-generated DNS records and read-only expectations vs the repo +mail-drift: +\t@octodns-gitops-forwardemail --drift --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) + +# Forward Email - write mail/forward-email/.yaml from live state +mail-export: +\t@octodns-gitops-forwardemail --export --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) """ diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py new file mode 100644 index 0000000..b25ccea --- /dev/null +++ b/src/octodns_gitops/cli/forward_email.py @@ -0,0 +1,220 @@ +"""Reconcile Forward Email domain settings and aliases with per-domain files in git. + +Opt-in only: acts solely on domains listed under `forward_email:` in config.yaml. +`--dry-run` (default) reads the account and prints the diff; `--doit` writes it. +Domains are never created or deleted — a claimed domain missing from the account is +an error. `--prune` (off by default) deletes aliases absent from git, except mailboxes +(`has_imap` or stored mail), which block the run instead. + +Modes: + plan / apply diff desired state against the account (default) + --export write `/.yaml` from live state (bootstrap / re-baseline) + --drift compare FE's generated DNS records and read-only expectations with the repo +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path +from typing import TextIO + +import yaml + +from octodns_gitops.forward_email.api import ForwardEmailApiError, ForwardEmailClient +from octodns_gitops.forward_email.config import ( + ForwardEmailConfig, + ForwardEmailConfigError, + load_domain_file, + load_forward_email, +) +from octodns_gitops.forward_email.drift import check_zone +from octodns_gitops.forward_email.export import export_domain +from octodns_gitops.forward_email.reconcile import DomainPlan, plan_domain + + +def zone_directory(config_path: str) -> Path | None: + """The YamlProvider's `directory`, resolved relative to config.yaml.""" + cfg_file = Path(config_path) + with open(cfg_file) as f: + cfg = yaml.safe_load(f) or {} + for prov in (cfg.get("providers") or {}).values(): + if isinstance(prov, dict) and str(prov.get("class", "")).endswith("YamlProvider"): + d = Path(prov.get("directory", "./zones")) + return d if d.is_absolute() else cfg_file.resolve().parent / d + return None + + +def _print_plan(plan: DomainPlan, out: TextIO) -> None: + n = len(plan.settings) + len(plan.aliases) + head = f"{n} change(s)" if n else "no changes" + out.write(f"{plan.domain:<28} {head}\n") + if plan.settings: + parts = [f"{c.field} {c.live!r} -> {c.desired!r}" for c in plan.settings] + extra = ", ".join(f"{k}={v!r}" for k, v in plan.write_only.items()) + out.write(f" settings: {'; '.join(parts)}") + out.write(f" (+ write-only, unverifiable: {extra})\n" if extra else "\n") + for chg in plan.aliases: + detail = "" if chg.action == "create" else f" [{', '.join(chg.changes)}]" + out.write(f" alias {chg.action:<6} {chg.name}{detail}\n") + if plan.unmanaged: + out.write(f" unmanaged (not in git, not pruned): {', '.join(plan.unmanaged)}\n") + out.writelines( + f" expect: {m.field} is {m.live!r}, expected {m.desired!r} (read-only, not written)\n" + for m in plan.expect_mismatch + ) + out.writelines(f" ERROR: {e}\n" for e in plan.errors) + + +def _apply(plan: DomainPlan, client, out: TextIO) -> bool: + """Perform the writes for one domain. Returns False if the prune guard aborted.""" + body = plan.settings_body() + if body: + client.update_domain(plan.domain, body) + out.write(f" applied settings: {sorted(body)}\n") + deletes = [c for c in plan.aliases if c.action == "delete"] + for chg in plan.aliases: + if chg.action == "create": + client.create_alias(plan.domain, chg.body) + elif chg.action == "update": + client.update_alias(plan.domain, chg.alias_id, chg.body) + else: + continue + out.write(f" applied alias {chg.action} {chg.name}\n") + if not deletes: + return True + # A0: never prune from a single listing — re-fetch and require the same id set. + before = plan.live_alias_ids + after = {a.get("id") for a in client.list_aliases(plan.domain)} + if before != after: + out.write( + f" ERROR: alias list for {plan.domain} changed between listings " + f"({len(before)} -> {len(after)} ids); prune aborted, re-run\n" + ) + return False + for chg in deletes: + client.delete_alias(plan.domain, chg.alias_id) + out.write(f" applied alias delete {chg.name}\n") + return True + + +def run( + cfg: ForwardEmailConfig, + client, + *, + domains: list[str] | None, + doit: bool, + prune: bool, + mode: str, + zone_dir: Path | None, + out: TextIO, +) -> int: + scope = list(cfg.domains) + if domains: + unclaimed = [d for d in domains if d not in cfg.domains] + if unclaimed: + out.write(f"not claimed under forward_email.domains: {', '.join(unclaimed)}\n") + return 2 + scope = [d for d in scope if d in domains] + + if mode == "plan": + out.write("APPLYING changes (--doit)\n" if doit else "DRY-RUN (default): no changes\n") + live_domains = {d["name"].lower(): d for d in client.list_domains()} + + rc = 0 + for domain in scope: + if domain not in live_domains: + out.write(f"{domain:<28} ERROR not in the account (domains are never created from git)\n") + rc = 1 + continue + try: + live = client.get_domain(domain) + if mode == "export": + aliases = client.list_aliases(domain) + cfg.directory.mkdir(parents=True, exist_ok=True) + path = cfg.directory / f"{domain}.yaml" + path.write_text(export_domain(cfg, live, aliases)) + out.write(f"{domain:<28} wrote {path} ({len(aliases)} aliases)\n") + continue + + path = cfg.directory / f"{domain}.yaml" + desired = load_domain_file(path, domain) + + if mode == "drift": + findings = [] + plan = plan_domain(desired, cfg, live, [], prune=False) + findings += [(m.field, f"{m.field} is {m.live!r}, expected {m.desired!r}") for m in plan.expect_mismatch] + zone_file = (zone_dir / f"{domain}.yaml") if zone_dir else None + if zone_file is None or not zone_file.exists(): + out.write(f"{domain:<28} no zone file in this repo; DNS records not checked\n") + else: + with open(zone_file) as f: + zone = yaml.safe_load(f) or {} + settings = {**cfg.settings, **desired.settings} + for fnd in check_zone(live, zone, expect_mx=not settings.get("ignore_mx_check")): + findings.append((fnd.field, fnd.message)) + if findings: + rc = 1 + out.write(f"{domain:<28} {len(findings)} finding(s)\n") + out.writelines(f" {field}: {msg}\n" for field, msg in findings) + elif zone_file is not None and zone_file.exists(): + out.write(f"{domain:<28} clean\n") + continue + + aliases = client.list_aliases(domain) + plan = plan_domain(desired, cfg, live, aliases, prune=prune) + plan.live_alias_ids = {a.get("id") for a in aliases} + _print_plan(plan, out) + if plan.errors: + rc = 1 + continue + if doit and not plan.is_empty() and not _apply(plan, client, out): + rc = 1 + except (ForwardEmailConfigError, ForwardEmailApiError) as e: + out.write(f"{domain:<28} ERROR {e}\n") + rc = 1 + return rc + + +def main() -> int: + p = argparse.ArgumentParser(description="Reconcile Forward Email settings and aliases (opt-in)") + p.add_argument("--config", default="config.yaml") + p.add_argument("--domain", action="append", help="Limit to this domain (repeatable)") + p.add_argument("--doit", action="store_true", help="Perform writes (default dry-run)") + p.add_argument("--dry-run", action="store_true", help="Preview only (the default; accepted for symmetry)") + p.add_argument("--prune", action="store_true", help="Delete aliases absent from git (never mailboxes)") + g = p.add_mutually_exclusive_group() + g.add_argument("--export", action="store_true", help="Write per-domain files from live state") + g.add_argument("--drift", action="store_true", help="Check FE DNS records and expectations against the repo") + args = p.parse_args() + + try: + cfg = load_forward_email(args.config) + except ForwardEmailConfigError as e: + print(f"config error: {e}", file=sys.stderr) + return 2 + if cfg is None: + print("Forward Email not configured (no forward_email: block in config.yaml).") + return 0 + token = os.environ.get(cfg.token_env) + if not token: + print(f"missing env var {cfg.token_env} (forward_email.token)", file=sys.stderr) + return 2 + + mode = "export" if args.export else "drift" if args.drift else "plan" + client = ForwardEmailClient(token) + return run( + cfg, + client, + domains=[d.lower().rstrip(".") for d in args.domain] if args.domain else None, + doit=args.doit and mode == "plan", + prune=args.prune, + mode=mode, + zone_dir=zone_directory(args.config) if mode == "drift" else None, + out=sys.stdout, + ) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/octodns_gitops/forward_email/__init__.py b/src/octodns_gitops/forward_email/__init__.py new file mode 100644 index 0000000..2a1b8e8 --- /dev/null +++ b/src/octodns_gitops/forward_email/__init__.py @@ -0,0 +1 @@ +"""Forward Email account settings as GitOps: opt-in per repo, per-domain desired state.""" diff --git a/src/octodns_gitops/forward_email/api.py b/src/octodns_gitops/forward_email/api.py new file mode 100644 index 0000000..cc1afb6 --- /dev/null +++ b/src/octodns_gitops/forward_email/api.py @@ -0,0 +1,117 @@ +"""Minimal Forward Email REST client (stdlib only, injectable transport). + +Listing safety: every list call pages explicitly with `page`/`limit` until a page comes +back shorter than `limit`. No total, header count or `count` field is ever trusted — a +truncated listing is what makes a prune delete live aliases. +""" + +from __future__ import annotations + +import base64 +import json +import urllib.error +import urllib.parse +import urllib.request +from collections.abc import Callable + +BASE_URL = "https://api.forwardemail.net" + +# transport(method, url, headers, body_dict_or_None) -> (status, decoded_json_or_None) +Transport = Callable[[str, str, dict, dict | None], tuple[int, object]] + + +class ForwardEmailApiError(RuntimeError): + """Non-2xx response from the API.""" + + def __init__(self, status: int, message: str, method: str, url: str): + super().__init__(f"{method} {url} -> {status}: {message}") + self.status = status + + +def urllib_transport(method: str, url: str, headers: dict, body: dict | None) -> tuple[int, object]: + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=60) as resp: + raw = resp.read() + status = resp.status + except urllib.error.HTTPError as e: + raw = e.read() + status = e.code + if not raw: + return status, None + try: + return status, json.loads(raw) + except json.JSONDecodeError: + return status, {"message": raw.decode(errors="replace")[:200]} + + +class ForwardEmailClient: + def __init__( + self, + token: str, + transport: Transport = urllib_transport, + base_url: str = BASE_URL, + page_size: int = 100, + ): + self._transport = transport + self._base = base_url.rstrip("/") + self._page_size = page_size + cred = base64.b64encode(f"{token}:".encode()).decode() + self._headers = {"Authorization": f"Basic {cred}", "Accept": "application/json"} + + # -- plumbing ----------------------------------------------------------------- + + def _call(self, method: str, path: str, body: dict | None = None, params: dict | None = None): + url = f"{self._base}{path}" + if params: + url += "?" + urllib.parse.urlencode(params) + headers = dict(self._headers) + if body is not None: + headers["Content-Type"] = "application/json" + status, payload = self._transport(method, url, headers, body) + if not 200 <= status < 300: + msg = payload.get("message") if isinstance(payload, dict) else str(payload) + raise ForwardEmailApiError(status, msg or "", method, url) + return payload + + def _paged(self, path: str) -> list[dict]: + out: list[dict] = [] + page = 1 + while True: + chunk = self._call("GET", path, params={"page": page, "limit": self._page_size}) + if not isinstance(chunk, list): + raise ForwardEmailApiError(200, f"expected a list from {path}", "GET", path) + out.extend(chunk) + if len(chunk) < self._page_size: + return out + page += 1 + + @staticmethod + def _d(domain: str) -> str: + return urllib.parse.quote(domain, safe="") + + # -- reads -------------------------------------------------------------------- + + def list_domains(self) -> list[dict]: + return self._paged("/v1/domains") + + def get_domain(self, domain: str) -> dict: + return self._call("GET", f"/v1/domains/{self._d(domain)}") + + def list_aliases(self, domain: str) -> list[dict]: + return self._paged(f"/v1/domains/{self._d(domain)}/aliases") + + # -- writes ------------------------------------------------------------------- + + def update_domain(self, domain: str, body: dict) -> dict: + return self._call("PUT", f"/v1/domains/{self._d(domain)}", body=body) + + def create_alias(self, domain: str, body: dict) -> dict: + return self._call("POST", f"/v1/domains/{self._d(domain)}/aliases", body=body) + + def update_alias(self, domain: str, alias_id: str, body: dict) -> dict: + return self._call("PUT", f"/v1/domains/{self._d(domain)}/aliases/{alias_id}", body=body) + + def delete_alias(self, domain: str, alias_id: str) -> None: + self._call("DELETE", f"/v1/domains/{self._d(domain)}/aliases/{alias_id}") diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py new file mode 100644 index 0000000..d77446b --- /dev/null +++ b/src/octodns_gitops/forward_email/config.py @@ -0,0 +1,279 @@ +"""Parse the opt-in `forward_email:` block and the per-domain desired-state files. + +Three layers, most general first: + +1. Package defaults (`DEFAULT_SETTINGS`, `DEFAULT_EXPECT`, `DEFAULT_ALIAS`) — the only + layer shared across repos, since each dns-zones repo (and its CI) can only see itself. +2. The `forward_email:` block in the repo's octoDNS `config.yaml` (octoDNS ignores it, + exactly like `delegation:`): API token env ref, the desired-state directory, repo-level + default overrides, and the opt-in domain list. **The domain list is the ownership + boundary** — the reconciler never touches a domain that is not listed. +3. One YAML file per claimed domain under the directory: `settings:` (API-writable domain + fields only), `expect:` (read-only fields we want drift-checked), `aliases:`. + +Field sets below come from Forward Email's server code (`update-domain.js` controller, +`domains.js` / `aliases.js` models), not from its API docs, which omit several. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path + +import yaml + +# Domain fields the update controller actually reads — the only ones git can enforce. +SETTINGS_FIELDS: frozenset[str] = frozenset( + { + "smtp_port", + "retention_days", + "bounce_webhook", + "max_quota_per_alias", + "alias_default_smtp_limit", + "has_adult_content_protection", + "has_phishing_protection", + "has_executable_protection", + "has_virus_protection", + "has_recipient_verification", + "ignore_mx_check", + "allow_subdomain_forwarding", + "has_delivery_logs", + "require_tls_inbound", + } +) + +# Accepted by PUT but absent from GET: can be sent, never verified. +WRITE_ONLY_SETTINGS: frozenset[str] = frozenset({"bounce_webhook", "max_quota_per_alias"}) + +# Read-only domain fields worth declaring so drift can be reported. `has_strict_dmarc` +# is deliberately absent: it is derived from DNS and tracked against the zone file. +EXPECT_FIELDS: frozenset[str] = frozenset( + {"has_smtp", "has_newsletter", "max_recipients_per_alias", "plan"} +) + +# Alias fields the alias create/update endpoints accept. +ALIAS_FIELDS: frozenset[str] = frozenset( + { + "name", + "recipients", + "description", + "labels", + "is_enabled", + "error_code_if_disabled", + "has_imap", + "has_pgp", + "public_key", + "has_recipient_verification", + "max_quota", + "vacation_responder", + } +) + +# Decided 2026-08-30 (see the audit plan). `smtp_port` is a *string* on the API. +DEFAULT_SETTINGS: dict = { + "smtp_port": "25", + "retention_days": 30, + "max_quota_per_alias": "1 GB", + "alias_default_smtp_limit": 0, + "has_adult_content_protection": True, + "has_phishing_protection": True, + "has_executable_protection": True, + "has_virus_protection": True, + "has_recipient_verification": False, + "ignore_mx_check": False, + "allow_subdomain_forwarding": False, + "has_delivery_logs": True, + "require_tls_inbound": True, +} + +DEFAULT_EXPECT: dict = { + "has_smtp": True, + "has_newsletter": False, + "max_recipients_per_alias": 10, + "plan": "team", +} + +DEFAULT_ALIAS: dict = { + "is_enabled": True, + "error_code_if_disabled": 250, + "has_imap": False, + "has_pgp": False, + "has_recipient_verification": False, + "description": None, + "labels": [], +} + +DEFAULT_DIRECTORY = "mail/forward-email" +DEFAULT_TOKEN_ENV = "FORWARD_EMAIL_API_TOKEN" + + +class ForwardEmailConfigError(ValueError): + """Raised when the block or a domain file is invalid.""" + + +@dataclass(frozen=True) +class ForwardEmailConfig: + """Resolved repo-level configuration (package defaults merged with repo overrides).""" + + token_env: str + directory: Path + domains: list[str] + settings: dict + expect: dict + alias: dict + + +@dataclass(frozen=True) +class DesiredAlias: + name: str + recipients: list[str] + description: str | None = None + labels: list[str] = field(default_factory=list) + is_enabled: bool | None = None + error_code_if_disabled: int | None = None + has_imap: bool | None = None + has_pgp: bool | None = None + public_key: str | None = None + has_recipient_verification: bool | None = None + max_quota: str | None = None + vacation_responder: dict | None = None + + +@dataclass(frozen=True) +class DesiredDomain: + domain: str + settings: dict + expect: dict + aliases: list[DesiredAlias] + + +def _load_yaml(path: Path) -> dict: + if not path.exists(): + raise ForwardEmailConfigError(f"file not found: {path}") + with open(path) as f: + data = yaml.safe_load(f) or {} + if not isinstance(data, dict): + raise ForwardEmailConfigError(f"{path}: expected a mapping at top level") + return data + + +def _check_keys(where: str, given: dict, allowed: frozenset[str]) -> None: + unknown = sorted(set(given) - allowed) + if unknown: + raise ForwardEmailConfigError(f"{where}: unknown or read-only field(s): {', '.join(unknown)}") + + +def _normalize_domain(name: str) -> str: + return str(name).strip().rstrip(".").lower() + + +def load_forward_email(config_path: str) -> ForwardEmailConfig | None: + """Parse the `forward_email:` block. Returns None when the repo has not opted in.""" + cfg_file = Path(config_path) + cfg = _load_yaml(cfg_file) + block = cfg.get("forward_email") + if not block: + return None + if not isinstance(block, dict): + raise ForwardEmailConfigError("forward_email: expected a mapping") + + token = block.get("token", f"env/{DEFAULT_TOKEN_ENV}") + if not isinstance(token, str) or not token.startswith("env/") or len(token) <= 4: + raise ForwardEmailConfigError( + "forward_email.token must be an env/VAR reference (never a literal secret)" + ) + token_env = token[len("env/") :] + + directory = Path(block.get("directory", DEFAULT_DIRECTORY)) + if not directory.is_absolute(): + directory = cfg_file.resolve().parent / directory + + raw_domains = block.get("domains") or [] + if not isinstance(raw_domains, list) or not raw_domains: + raise ForwardEmailConfigError("forward_email.domains must be a non-empty list") + domains: list[str] = [] + for d in raw_domains: + n = _normalize_domain(d) + if n in domains: + raise ForwardEmailConfigError(f"forward_email.domains: duplicate entry {n!r}") + domains.append(n) + + defaults = block.get("defaults") or {} + if not isinstance(defaults, dict): + raise ForwardEmailConfigError("forward_email.defaults: expected a mapping") + settings_over = defaults.get("settings") or {} + expect_over = defaults.get("expect") or {} + alias_over = defaults.get("alias") or {} + _check_keys("forward_email.defaults.settings", settings_over, SETTINGS_FIELDS) + _check_keys("forward_email.defaults.expect", expect_over, EXPECT_FIELDS) + _check_keys("forward_email.defaults.alias", alias_over, ALIAS_FIELDS - {"name", "recipients"}) + + return ForwardEmailConfig( + token_env=token_env, + directory=directory, + domains=domains, + settings={**DEFAULT_SETTINGS, **settings_over}, + expect={**DEFAULT_EXPECT, **expect_over}, + alias={**DEFAULT_ALIAS, **alias_over}, + ) + + +def _as_list(value) -> list[str]: + if value is None: + return [] + if isinstance(value, str): + return [value] + if isinstance(value, list): + return [str(v) for v in value] + raise ForwardEmailConfigError(f"expected a string or list, got {type(value).__name__}") + + +def load_domain_file(path: Path, domain: str) -> DesiredDomain: + """Parse one per-domain desired-state file for `domain` (bare, lowercase).""" + data = _load_yaml(Path(path)) + declared = data.get("domain") + if declared is not None and _normalize_domain(declared) != domain: + raise ForwardEmailConfigError( + f"{path}: domain key {declared!r} does not match file domain {domain!r}" + ) + _check_keys(f"{path}", data, frozenset({"domain", "settings", "expect", "aliases"})) + + settings = data.get("settings") or {} + expect = data.get("expect") or {} + _check_keys(f"{path}: settings", settings, SETTINGS_FIELDS) + _check_keys(f"{path}: expect", expect, EXPECT_FIELDS) + + raw_aliases = data.get("aliases") + if raw_aliases is None: + raw_aliases = [] + if not isinstance(raw_aliases, list): + raise ForwardEmailConfigError(f"{path}: aliases must be a list") + + aliases: list[DesiredAlias] = [] + seen: set[str] = set() + for i, raw in enumerate(raw_aliases): + if not isinstance(raw, dict) or "name" not in raw: + raise ForwardEmailConfigError(f"{path}: aliases[{i}] needs a name") + _check_keys(f"{path}: alias {raw['name']!r}", raw, ALIAS_FIELDS) + name = str(raw["name"]) + if name in seen: + raise ForwardEmailConfigError(f"{path}: duplicate alias {name!r}") + seen.add(name) + aliases.append( + DesiredAlias( + name=name, + recipients=_as_list(raw.get("recipients")), + description=raw.get("description"), + labels=_as_list(raw.get("labels")), + is_enabled=raw.get("is_enabled"), + error_code_if_disabled=raw.get("error_code_if_disabled"), + has_imap=raw.get("has_imap"), + has_pgp=raw.get("has_pgp"), + public_key=raw.get("public_key"), + has_recipient_verification=raw.get("has_recipient_verification"), + max_quota=None if raw.get("max_quota") is None else str(raw["max_quota"]), + vacation_responder=raw.get("vacation_responder"), + ) + ) + + return DesiredDomain(domain=domain, settings=dict(settings), expect=dict(expect), aliases=aliases) diff --git a/src/octodns_gitops/forward_email/drift.py b/src/octodns_gitops/forward_email/drift.py new file mode 100644 index 0000000..5c6f6ec --- /dev/null +++ b/src/octodns_gitops/forward_email/drift.py @@ -0,0 +1,103 @@ +"""Compare Forward Email's server-generated DNS records with the repo's octoDNS zone file. + +`smtp_dns_records` (DKIM key, return-path CNAME, suggested DMARC) and `verification_record` +are *inputs* to the zone file, so a mismatch means the zone file is stale, not the account. +DMARC is special: FE suggests `p=reject`, the repo publishes its own ramped policy — only the +FE `rua` address must be present. `has_strict_dmarc` is derived by FE from what it sees in +DNS, so the expectation is derived from the zone file's own `p=` value. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +FE_MX = {"mx1.forwardemail.net", "mx2.forwardemail.net"} + + +@dataclass(frozen=True) +class DriftFinding: + field: str + message: str + + +def _records(zone: dict, name: str, rtype: str) -> list[dict]: + entry = zone.get(name) + if entry is None: + return [] + entries = entry if isinstance(entry, list) else [entry] + return [r for r in entries if r.get("type") == rtype] + + +def _values(zone: dict, name: str, rtype: str) -> list: + out = [] + for r in _records(zone, name, rtype): + if "values" in r: + out.extend(r["values"]) + elif "value" in r: + out.append(r["value"]) + return out + + +def _unescape_txt(v: str) -> str: + return re.sub(r"\s+", " ", v.replace("\\;", ";")).strip() + + +def _dmarc_tags(v: str) -> dict: + tags = {} + for part in _unescape_txt(v).split(";"): + if "=" in part: + k, val = part.split("=", 1) + tags[k.strip().lower()] = val.strip() + return tags + + +def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftFinding]: + findings: list[DriftFinding] = [] + recs = live_domain.get("smtp_dns_records") or {} + + dkim = recs.get("dkim") + if dkim: + got = [_unescape_txt(v) for v in _values(zone, dkim["name"], "TXT")] + if _unescape_txt(dkim["value"]) not in got: + findings.append( + DriftFinding("dkim", f"{dkim['name']} TXT: zone has {got or 'nothing'}, FE issues a different key") + ) + + rp = recs.get("return_path") + if rp: + got = [v.rstrip(".") for v in _values(zone, rp["name"], "CNAME")] + if rp["value"].rstrip(".") not in got: + findings.append(DriftFinding("return_path", f"{rp['name']} CNAME: expected {rp['value']}, zone has {got}")) + + token = live_domain.get("verification_record") + if token: + want = f"forward-email-site-verification={token}" + if want not in [_unescape_txt(v) for v in _values(zone, "", "TXT")]: + findings.append(DriftFinding("verification", f"apex TXT {want} missing")) + + dmarc = recs.get("dmarc") + zone_dmarc = _values(zone, "_dmarc", "TXT") + if dmarc: + fe_rua = _dmarc_tags(dmarc["value"]).get("rua", "") + published = [_dmarc_tags(v) for v in zone_dmarc] + if not any(fe_rua and fe_rua in t.get("rua", "") for t in published): + findings.append(DriftFinding("dmarc", f"_dmarc TXT does not report to FE ({fe_rua or 'no rua'})")) + + if "has_strict_dmarc" in live_domain and zone_dmarc: + strict = any(_dmarc_tags(v).get("p", "").lower() == "reject" for v in zone_dmarc) + if bool(live_domain["has_strict_dmarc"]) != strict: + findings.append( + DriftFinding( + "has_strict_dmarc", + f"FE reports has_strict_dmarc={live_domain['has_strict_dmarc']}, zone publishes " + f"p={'reject' if strict else 'non-reject'} (FE re-derives this on its next verification)", + ) + ) + + if expect_mx: + got = {v["exchange"].rstrip(".").lower() for v in _values(zone, "", "MX") if isinstance(v, dict)} + if not FE_MX <= got: + findings.append(DriftFinding("mx", f"apex MX {sorted(got) or 'missing'} does not include {sorted(FE_MX)}")) + + return findings diff --git a/src/octodns_gitops/forward_email/export.py b/src/octodns_gitops/forward_email/export.py new file mode 100644 index 0000000..0295b46 --- /dev/null +++ b/src/octodns_gitops/forward_email/export.py @@ -0,0 +1,110 @@ +"""Render live API state as a per-domain desired-state file. + +Hand-rolled emitter rather than `yaml.dump`: key order, quoting and the omission of +default-valued fields are the contract. Regex alias names (`/^([\\w\\-\\.]+)$/`) are +single-quoted — a double-quoted YAML scalar would read `\\w` as an escape sequence. +""" + +from __future__ import annotations + +import re + +from .config import ( + EXPECT_FIELDS, + SETTINGS_FIELDS, + WRITE_ONLY_SETTINGS, + ForwardEmailConfig, +) +from .reconcile import _ALIAS_SIMPLE, _vacation_enabled, parse_quota + +_PLAIN_OK = re.compile(r"^[A-Za-z0-9$_][A-Za-z0-9$_@.+\- ]*$") +_YAML_WORDS = {"true", "false", "null", "yes", "no", "on", "off", "~"} +_QUOTA_UNITS = (("TB", 1024**4), ("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)) + + +def _scalar(v) -> str: + if v is None: + return "null" + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, (int, float)): + return str(v) + s = str(v) + plain = ( + bool(_PLAIN_OK.match(s)) + and s == s.strip() + and s.lower() not in _YAML_WORDS + and not re.fullmatch(r"[\d.]+", s) + ) + if plain: + return s + return "'" + s.replace("'", "''") + "'" + + +def human_quota(nbytes: int) -> str: + for unit, size in _QUOTA_UNITS: + if nbytes % size == 0: + return f"{nbytes // size} {unit}" + return f"{nbytes} B" + + +def _list(lines: list[str], key: str, values: list, indent: str) -> None: + if not values: + lines.append(f"{indent}{key}: []") + return + lines.append(f"{indent}{key}:") + lines.extend(f"{indent} - {_scalar(v)}" for v in values) + + +def _alias_lines(live: dict, defaults: dict, domain_quota: int) -> list[str]: + ind = " " + out = [f" - name: {_scalar(live['name'])}"] + _list(out, "recipients", live.get("recipients") or [], ind) + if live.get("description"): + out.append(f"{ind}description: {_scalar(live['description'])}") + for f in _ALIAS_SIMPLE: + if live.get(f, defaults[f]) != defaults[f]: + out.append(f"{ind}{f}: {_scalar(live[f])}") + if live.get("public_key"): + out.append(f"{ind}public_key: {_scalar(live['public_key'])}") + if live.get("max_quota") is not None and int(live["max_quota"]) != domain_quota: + out.append(f"{ind}max_quota: {human_quota(int(live['max_quota']))}") + vac = live.get("vacation_responder") + if _vacation_enabled(vac): + out.append(f"{ind}vacation_responder:") + for k in ("is_enabled", "subject", "message"): + if k in vac: + out.append(f"{ind} {k}: {_scalar(vac[k])}") + return out + + +def export_domain(cfg: ForwardEmailConfig, live_domain: dict, live_aliases: list[dict]) -> str: + """Return the YAML text for `live_domain`, omitting everything equal to the resolved defaults.""" + lines = [f"domain: {_scalar(live_domain['name'])}"] + + settings = { + f: live_domain[f] + for f in sorted(SETTINGS_FIELDS - WRITE_ONLY_SETTINGS) + if f in live_domain and live_domain[f] != cfg.settings.get(f) + } + if settings: + lines.append("settings:") + lines.extend(f" {k}: {_scalar(v)}" for k, v in settings.items()) + + expect = { + f: live_domain[f] + for f in sorted(EXPECT_FIELDS) + if f in live_domain and live_domain[f] != cfg.expect.get(f) + } + if expect: + lines.append("expect:") + lines.extend(f" {k}: {_scalar(v)}" for k, v in expect.items()) + + domain_quota = parse_quota(cfg.settings.get("max_quota_per_alias") or 0) + if not live_aliases: + lines.append("aliases: []") + else: + lines.append("aliases:") + for a in sorted(live_aliases, key=lambda a: a["name"]): + lines.extend(_alias_lines(a, cfg.alias, domain_quota)) + return "\n".join(lines) + "\n" diff --git a/src/octodns_gitops/forward_email/reconcile.py b/src/octodns_gitops/forward_email/reconcile.py new file mode 100644 index 0000000..83a9c06 --- /dev/null +++ b/src/octodns_gitops/forward_email/reconcile.py @@ -0,0 +1,216 @@ +"""Diff desired state (git) against live state (API) for one domain. + +Pure functions: no I/O. The CLI fetches, calls `plan_domain`, prints, and applies. + +Rules that are easy to get wrong, all decided in the 2026-08-30 audit: + +- Settings equal to the resolved default are still *enforced* — the default is desired state, + not "don't care". Only the file omits them. +- Write-only settings (`WRITE_ONLY_SETTINGS`) cannot be read back, so they never create a diff + on their own; they ride along in every domain PUT that a verifiable change triggers. +- Alias `max_quota` is bytes on GET and a human string on PUT; absent on GET means "domain + default". A live value differing from the desired one is reset with a blank PUT. +- `labels` is server-applied (`catch-all`) and never compared. +- A prune never deletes an alias with `has_imap` or stored mail: that is a mailbox. Such an + alias missing from git is an error that blocks the run. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +from .config import ( + EXPECT_FIELDS, + SETTINGS_FIELDS, + WRITE_ONLY_SETTINGS, + DesiredAlias, + DesiredDomain, + ForwardEmailConfig, +) + +_UNITS = {"B": 1, "KB": 1024, "MB": 1024**2, "GB": 1024**3, "TB": 1024**4} +_QUOTA_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([KMGT]?B)\s*$", re.IGNORECASE) + + +def parse_quota(value: str | int) -> int: + """'1 GB' -> bytes, 1024-based (matches the `bytes` package Forward Email uses).""" + if isinstance(value, int): + return value + m = _QUOTA_RE.match(str(value)) + if not m: + raise ValueError(f"unparseable quota {value!r} (expected e.g. '1 GB')") + return int(float(m.group(1)) * _UNITS[m.group(2).upper()]) + + +@dataclass(frozen=True) +class SettingChange: + field: str + live: object + desired: object + + +@dataclass(frozen=True) +class AliasChange: + action: str # create | update | delete + name: str + alias_id: str | None + body: dict + changes: list[str] = field(default_factory=list) + + +@dataclass +class DomainPlan: + domain: str + settings: list[SettingChange] = field(default_factory=list) + write_only: dict = field(default_factory=dict) + aliases: list[AliasChange] = field(default_factory=list) + unmanaged: list[str] = field(default_factory=list) + expect_mismatch: list[SettingChange] = field(default_factory=list) + errors: list[str] = field(default_factory=list) + # ids seen in the listing the plan was built from; the apply path re-lists before a prune + live_alias_ids: set = field(default_factory=set) + + def is_empty(self) -> bool: + """Nothing to write and nothing wrong. `unmanaged` alone is informational.""" + return not (self.settings or self.aliases or self.expect_mismatch or self.errors) + + def settings_body(self) -> dict: + if not self.settings: + return {} + body = {c.field: c.desired for c in self.settings} + body.update(self.write_only) + return body + + +# Alias fields compared field-by-field (everything else needs special handling). +_ALIAS_SIMPLE = ("is_enabled", "error_code_if_disabled", "has_imap", "has_pgp", "has_recipient_verification") + + +def _resolve_alias(desired: DesiredAlias, defaults: dict) -> dict: + """Desired alias with repo/package defaults filled in for undeclared fields.""" + out = {"name": desired.name, "recipients": list(desired.recipients)} + for f in _ALIAS_SIMPLE: + v = getattr(desired, f) + out[f] = defaults[f] if v is None else v + out["description"] = desired.description if desired.description is not None else defaults["description"] + out["public_key"] = desired.public_key + out["max_quota"] = desired.max_quota + out["vacation_responder"] = desired.vacation_responder + return out + + +def _norm_desc(v) -> str: + return "" if v is None else str(v) + + +def _vacation_enabled(v) -> bool: + return bool(v) and bool(v.get("is_enabled")) + + +def _alias_body(resolved: dict, defaults: dict) -> dict: + """Create body: the fields that differ from the defaults, plus name/recipients.""" + body = {"name": resolved["name"], "recipients": resolved["recipients"]} + for f in _ALIAS_SIMPLE: + if resolved[f] != defaults[f]: + body[f] = resolved[f] + if _norm_desc(resolved["description"]) != _norm_desc(defaults["description"]): + body["description"] = resolved["description"] + if resolved["public_key"]: + body["public_key"] = resolved["public_key"] + if resolved["max_quota"] is not None: + body["max_quota"] = resolved["max_quota"] + if _vacation_enabled(resolved["vacation_responder"]): + body["vacation_responder"] = resolved["vacation_responder"] + return body + + +def _diff_alias(resolved: dict, live: dict, defaults: dict, domain_quota: int) -> AliasChange | None: + changes: list[str] = [] + body = _alias_body(resolved, defaults) + + if sorted(resolved["recipients"]) != sorted(live.get("recipients") or []): + changes.append("recipients") + for f in _ALIAS_SIMPLE: + if resolved[f] != live.get(f, defaults[f]): + changes.append(f) + body[f] = resolved[f] # an update must carry the value even when it is the default + if _norm_desc(resolved["description"]) != _norm_desc(live.get("description")): + changes.append("description") + body["description"] = _norm_desc(resolved["description"]) + if (resolved["public_key"] or "") != (live.get("public_key") or ""): + changes.append("public_key") + body["public_key"] = resolved["public_key"] or "" + + # Quota: compare in bytes; None desired means "domain default". + desired_bytes = parse_quota(resolved["max_quota"]) if resolved["max_quota"] else domain_quota + live_quota = live.get("max_quota") + live_bytes = domain_quota if live_quota is None else int(live_quota) + if desired_bytes != live_bytes: + changes.append("max_quota") + body["max_quota"] = resolved["max_quota"] or "" + + want_vac = resolved["vacation_responder"] + if _vacation_enabled(want_vac) != _vacation_enabled(live.get("vacation_responder")) or ( + _vacation_enabled(want_vac) and want_vac != live.get("vacation_responder") + ): + changes.append("vacation_responder") + body["vacation_responder"] = want_vac or {"is_enabled": False} + + if not changes: + return None + return AliasChange("update", resolved["name"], live.get("id"), body, changes) + + +def plan_domain( + desired: DesiredDomain, + cfg: ForwardEmailConfig, + live_domain: dict, + live_aliases: list[dict], + *, + prune: bool, +) -> DomainPlan: + plan = DomainPlan(desired.domain) + settings = {**cfg.settings, **desired.settings} + expect = {**cfg.expect, **desired.expect} + + for f in sorted(SETTINGS_FIELDS & set(settings)): + if f in WRITE_ONLY_SETTINGS: + plan.write_only[f] = settings[f] + elif live_domain.get(f) != settings[f]: + plan.settings.append(SettingChange(f, live_domain.get(f), settings[f])) + + for f in sorted(EXPECT_FIELDS & set(expect)): + if live_domain.get(f) != expect[f]: + plan.expect_mismatch.append(SettingChange(f, live_domain.get(f), expect[f])) + + domain_quota = parse_quota(settings.get("max_quota_per_alias") or 0) + live_by_name = {a["name"]: a for a in live_aliases} + + for want in desired.aliases: + resolved = _resolve_alias(want, cfg.alias) + live = live_by_name.get(want.name) + if live is None: + plan.aliases.append(AliasChange("create", want.name, None, _alias_body(resolved, cfg.alias), ["new"])) + continue + chg = _diff_alias(resolved, live, cfg.alias, domain_quota) + if chg: + plan.aliases.append(chg) + + wanted = {a.name for a in desired.aliases} + for live in live_aliases: + if live["name"] in wanted: + continue + plan.unmanaged.append(live["name"]) + if not prune: + continue + if live.get("has_imap") or (live.get("storage_used") or 0) > 0: + plan.errors.append( + f"refusing to prune {live['name']}@{desired.domain}: it is a mailbox " + f"(has_imap={live.get('has_imap')}, storage_used={live.get('storage_used')}); " + "add it to git or delete it in the web UI" + ) + continue + plan.aliases.append(AliasChange("delete", live["name"], live.get("id"), {}, ["prune"])) + + return plan diff --git a/tests/bootstrap/test_makefile.py b/tests/bootstrap/test_makefile.py index 96a9352..beb6970 100644 --- a/tests/bootstrap/test_makefile.py +++ b/tests/bootstrap/test_makefile.py @@ -1,10 +1,9 @@ """Tests for bootstrap/makefile.py""" -import pytest from io import StringIO from unittest.mock import patch -from octodns_gitops.bootstrap.makefile import main, MAKEFILE_TEMPLATE +from octodns_gitops.bootstrap.makefile import MAKEFILE_TEMPLATE, main class TestMain: @@ -46,6 +45,14 @@ def test_makefile_supports_zone_filter(self): assert "ZONE=" in MAKEFILE_TEMPLATE assert "--zone $(ZONE)" in MAKEFILE_TEMPLATE + def test_makefile_contains_forward_email_targets(self): + """mail-* targets wrap octodns-gitops-forwardemail; apply is the only --doit.""" + for target in ("mail-plan:", "mail-apply:", "mail-drift:", "mail-export:"): + assert target in MAKEFILE_TEMPLATE + assert MAKEFILE_TEMPLATE.count("octodns-gitops-forwardemail --doit") == 1 + assert "--domain $(DOMAIN)" in MAKEFILE_TEMPLATE + assert "$(if $(PRUNE),--prune,)" in MAKEFILE_TEMPLATE + def test_makefile_supports_force_flag(self): """The Makefile should support FORCE=1 for apply.""" assert "FORCE=" in MAKEFILE_TEMPLATE diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py new file mode 100644 index 0000000..e0773eb --- /dev/null +++ b/tests/cli/test_forward_email.py @@ -0,0 +1,337 @@ +"""Tests for cli/forward_email.py — plan/apply/export/drift against a fake API client.""" + +import copy +import io +import textwrap + +import pytest +from octodns_gitops.cli.forward_email import main, run, zone_directory +from octodns_gitops.forward_email.config import ( + DEFAULT_ALIAS, + DEFAULT_EXPECT, + DEFAULT_SETTINGS, + ForwardEmailConfig, +) + +GIB = 1024**3 +DKIM = "v=DKIM1; k=rsa; p=MIIBIjANBg;" + + +def _live_domain(name, **over): + d = {k: v for k, v in DEFAULT_SETTINGS.items() if k != "max_quota_per_alias"} + d.update(DEFAULT_EXPECT) + d.update( + { + "name": name, + "id": f"dom-{name}", + "has_strict_dmarc": False, + "verification_record": "TOKEN", + "smtp_dns_records": { + "dkim": {"name": "fe-1._domainkey", "value": DKIM}, + "return_path": {"name": "fe-bounces", "value": "forwardemail.net"}, + "dmarc": {"name": "_dmarc", "value": "v=DMARC1; p=reject; rua=mailto:dmarc-1@forwardemail.net;"}, + }, + } + ) + d.update(over) + return d + + +def _live_alias(name, **over): + a = { + "id": f"id-{name}", + "name": name, + "recipients": ["serge@ginsys.eu"], + "is_enabled": True, + "error_code_if_disabled": 250, + "has_imap": False, + "has_pgp": False, + "has_recipient_verification": False, + "labels": [], + "storage_used": 0, + "vacation_responder": {"is_enabled": False}, + } + a.update(over) + return a + + +class FakeClient: + def __init__(self, domains, aliases): + self.domains = {d["name"]: d for d in domains} + self.aliases = {k: list(v) for k, v in aliases.items()} + self.calls = [] + # Set to simulate a concurrent change between the first and second listing. + self.mutate_on_relist = None + + def list_domains(self): + return list(self.domains.values()) + + def get_domain(self, name): + return copy.deepcopy(self.domains[name]) + + def list_aliases(self, domain): + self.calls.append(("list_aliases", domain)) + if self.mutate_on_relist and self.calls.count(("list_aliases", domain)) == 2: + self.mutate_on_relist(self) + return copy.deepcopy(self.aliases.get(domain, [])) + + def update_domain(self, name, body): + self.calls.append(("update_domain", name, body)) + return {} + + def create_alias(self, domain, body): + self.calls.append(("create_alias", domain, body)) + return {} + + def update_alias(self, domain, alias_id, body): + self.calls.append(("update_alias", domain, alias_id, body)) + return {} + + def delete_alias(self, domain, alias_id): + self.calls.append(("delete_alias", domain, alias_id)) + + def writes(self): + return [c for c in self.calls if c[0] != "list_aliases"] + + +def _cfg(tmp_path, domains=("x.be",)): + return ForwardEmailConfig( + token_env="T", + directory=tmp_path / "mail", + domains=list(domains), + settings=dict(DEFAULT_SETTINGS), + expect=dict(DEFAULT_EXPECT), + alias=dict(DEFAULT_ALIAS), + ) + + +def _write_domain_file(tmp_path, domain, body): + (tmp_path / "mail").mkdir(exist_ok=True) + (tmp_path / "mail" / f"{domain}.yaml").write_text(textwrap.dedent(body)) + + +def _run(cfg, client, **kw): + out = io.StringIO() + kw.setdefault("domains", None) + kw.setdefault("doit", False) + kw.setdefault("prune", False) + kw.setdefault("mode", "plan") + kw.setdefault("zone_dir", None) + rc = run(cfg, client, out=out, **kw) + return rc, out.getvalue() + + +class TestPlan: + def test_zero_diff_exits_0_and_writes_nothing(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases:\n - {name: a, recipients: [serge@ginsys.eu]}\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("a")]}) + rc, out = _run(_cfg(tmp_path), client) + assert rc == 0 + assert "no changes" in out + assert client.writes() == [] + + def test_changes_are_printed_but_not_applied_without_doit(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases:\n - {name: a, recipients: [serge@ginsys.eu]}\n") + client = FakeClient([_live_domain("x.be", retention_days=0)], {"x.be": [_live_alias("a")]}) + rc, out = _run(_cfg(tmp_path), client) + assert rc == 0 + assert "retention_days" in out and "0 -> 30" in out + assert "DRY-RUN" in out + assert client.writes() == [] + + def test_claimed_domain_missing_from_account_is_an_error_never_a_create(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([], {}) + rc, out = _run(_cfg(tmp_path), client) + assert rc == 1 + assert "x.be" in out and "not in the account" in out + assert client.writes() == [] + + def test_missing_domain_file_is_an_error(self, tmp_path): + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client) + assert rc == 1 + assert "x.be.yaml" in out + + def test_domain_filter_limits_scope(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path, ["x.be", "y.be"]), client, domains=["x.be"]) + assert rc == 0 + assert "y.be" not in out + + def test_unclaimed_domain_filter_is_rejected(self, tmp_path): + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, domains=["other.be"]) + assert rc == 2 + assert "other.be" in out + + +class TestApply: + def test_doit_sends_settings_and_alias_writes(self, tmp_path): + _write_domain_file( + tmp_path, + "x.be", + """ + aliases: + - {name: a, recipients: [new@y.z]} + - {name: b, recipients: [serge@ginsys.eu]} + """, + ) + client = FakeClient([_live_domain("x.be", retention_days=0)], {"x.be": [_live_alias("a")]}) + rc, _out = _run(_cfg(tmp_path), client, doit=True) + assert rc == 0 + assert ("update_domain", "x.be", {"retention_days": 30, "max_quota_per_alias": "1 GB"}) in client.calls + assert ("update_alias", "x.be", "id-a", {"name": "a", "recipients": ["new@y.z"]}) in client.calls + assert ("create_alias", "x.be", {"name": "b", "recipients": ["serge@ginsys.eu"]}) in client.calls + assert not any(c[0] == "delete_alias" for c in client.calls) + + def test_prune_deletes_after_a_second_listing_agrees(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) + rc, _out = _run(_cfg(tmp_path), client, doit=True, prune=True) + assert rc == 0 + assert client.calls.count(("list_aliases", "x.be")) == 2 + assert ("delete_alias", "x.be", "id-stray") in client.calls + + def test_prune_aborts_when_the_second_listing_differs(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) + client.mutate_on_relist = lambda c: c.aliases["x.be"].append(_live_alias("late")) + rc, out = _run(_cfg(tmp_path), client, doit=True, prune=True) + assert rc == 1 + assert "changed between listings" in out + assert not any(c[0] == "delete_alias" for c in client.calls) + + def test_mailbox_guard_blocks_the_whole_domain_apply(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be", retention_days=0)], {"x.be": [_live_alias("box", has_imap=True)]}) + rc, out = _run(_cfg(tmp_path), client, doit=True, prune=True) + assert rc == 1 + assert "mailbox" in out + assert client.writes() == [] + + def test_unmanaged_alias_without_prune_is_reported_only(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) + rc, out = _run(_cfg(tmp_path), client, doit=True) + assert rc == 0 + assert "unmanaged" in out and "stray" in out + assert client.writes() == [] + + +class TestExport: + def test_export_writes_one_file_per_claimed_domain(self, tmp_path): + client = FakeClient( + [_live_domain("x.be", retention_days=0), _live_domain("y.be")], + {"x.be": [_live_alias("a")], "y.be": []}, + ) + rc, _out = _run(_cfg(tmp_path, ["x.be", "y.be"]), client, mode="export") + assert rc == 0 + x = (tmp_path / "mail" / "x.be.yaml").read_text() + assert x.startswith("domain: x.be\nsettings:\n retention_days: 0\n") + assert (tmp_path / "mail" / "y.be.yaml").read_text() == "domain: y.be\naliases: []\n" + assert client.writes() == [] + + +class TestDrift: + ZONE = textwrap.dedent( + """ + '': + - type: MX + values: + - {exchange: mx1.forwardemail.net., preference: 10} + - {exchange: mx2.forwardemail.net., preference: 10} + - type: TXT + values: + - forward-email-site-verification=TOKEN + _dmarc: + type: TXT + value: v=DMARC1\\; p=quarantine\\; rua=mailto:dmarc-1@forwardemail.net\\; + fe-1._domainkey: + type: TXT + value: v=DKIM1\\; k=rsa\\; p=MIIBIjANBg\\; + fe-bounces: + type: CNAME + value: forwardemail.net. + """ + ) + + def _zones(self, tmp_path, text=None): + zd = tmp_path / "zones" + zd.mkdir() + (zd / "x.be.yaml").write_text(text or self.ZONE) + return zd + + def test_clean_zone_and_matching_expectations_exit_0(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=self._zones(tmp_path)) + assert rc == 0 + assert "clean" in out + + def test_stale_dkim_in_zone_file_is_reported(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + zd = self._zones(tmp_path, self.ZONE.replace("p=MIIBIjANBg", "p=OLD")) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=zd) + assert rc == 1 + assert "dkim" in out + + def test_expectation_mismatch_is_drift(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be", has_smtp=False)], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=self._zones(tmp_path)) + assert rc == 1 + assert "has_smtp" in out + + def test_domain_without_zone_file_is_informational(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + zd = tmp_path / "zones" + zd.mkdir() + rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=zd) + assert rc == 0 + assert "no zone file" in out + + +class TestConfigPlumbing: + def test_zone_directory_comes_from_the_yaml_provider(self, tmp_path): + cfg = tmp_path / "config.yaml" + cfg.write_text( + textwrap.dedent( + """ + providers: + zones: + class: octodns.provider.yaml.YamlProvider + directory: ./zones + other: + class: octodns_hetzner.HetznerProvider + """ + ) + ) + assert zone_directory(str(cfg)) == tmp_path / "zones" + + def test_main_without_opt_in_block_is_a_noop(self, tmp_path, monkeypatch, capsys): + cfg = tmp_path / "config.yaml" + cfg.write_text("providers: {}\n") + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg)]) + assert main() == 0 + assert "not configured" in capsys.readouterr().out + + def test_main_refuses_without_token_env(self, tmp_path, monkeypatch, capsys): + cfg = tmp_path / "config.yaml" + cfg.write_text("forward_email:\n token: env/FE_TEST_TOKEN\n domains: [x.be]\n") + monkeypatch.delenv("FE_TEST_TOKEN", raising=False) + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg)]) + assert main() == 2 + assert "FE_TEST_TOKEN" in capsys.readouterr().err + + +def _refuse_network(*_args): + raise AssertionError("test reached the real transport") + + +@pytest.fixture(autouse=True) +def _no_network(monkeypatch): + monkeypatch.setattr("octodns_gitops.forward_email.api.urllib_transport", _refuse_network) diff --git a/tests/forward_email/__init__.py b/tests/forward_email/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/forward_email/test_api.py b/tests/forward_email/test_api.py new file mode 100644 index 0000000..2888605 --- /dev/null +++ b/tests/forward_email/test_api.py @@ -0,0 +1,94 @@ +"""Tests for forward_email/api.py — paging, auth, and write verbs against a fake transport.""" + +import base64 + +import pytest +from octodns_gitops.forward_email.api import ForwardEmailApiError, ForwardEmailClient + + +class FakeTransport: + """Records calls; answers from a (method, path) -> list of responses table.""" + + def __init__(self, table): + self.table = table + self.calls = [] + + def __call__(self, method, url, headers, body): + self.calls.append((method, url, headers, body)) + key = (method, url.split("?")[0]) + responses = self.table[key] + status, payload = responses.pop(0) if isinstance(responses, list) else responses + return status, payload + + +def _client(table): + t = FakeTransport(table) + return ForwardEmailClient(token="tok", transport=t, page_size=2), t + + +class TestAuth: + def test_basic_auth_with_token_as_username(self): + c, t = _client({("GET", "https://api.forwardemail.net/v1/domains"): [(200, [])]}) + c.list_domains() + auth = t.calls[0][2]["Authorization"] + assert auth == "Basic " + base64.b64encode(b"tok:").decode() + + +class TestPaging: + def test_list_domains_pages_until_short_page(self): + pages = [(200, [{"name": "a.be"}, {"name": "b.be"}]), (200, [{"name": "c.be"}])] + c, t = _client({("GET", "https://api.forwardemail.net/v1/domains"): pages}) + names = [d["name"] for d in c.list_domains()] + assert names == ["a.be", "b.be", "c.be"] + assert [u for _, u, _, _ in t.calls] == [ + "https://api.forwardemail.net/v1/domains?page=1&limit=2", + "https://api.forwardemail.net/v1/domains?page=2&limit=2", + ] + + def test_full_last_page_fetches_one_more(self): + # Never trust a total: an exact multiple of page_size needs an extra empty fetch. + pages = [(200, [{"id": 1}, {"id": 2}]), (200, [])] + c, t = _client({("GET", "https://api.forwardemail.net/v1/domains/x.be/aliases"): pages}) + assert len(c.list_aliases("x.be")) == 2 + assert len(t.calls) == 2 + + +class TestErrors: + def test_non_2xx_raises_with_status_and_message(self): + c, _ = _client( + {("GET", "https://api.forwardemail.net/v1/domains/x.be"): [(404, {"message": "Not Found"})]} + ) + with pytest.raises(ForwardEmailApiError, match="404.*Not Found"): + c.get_domain("x.be") + + +class TestWrites: + def test_update_domain_puts_json(self): + c, t = _client({("PUT", "https://api.forwardemail.net/v1/domains/x.be"): [(200, {"name": "x.be"})]}) + c.update_domain("x.be", {"retention_days": 30, "smtp_port": "25"}) + method, _url, headers, body = t.calls[0] + assert (method, headers["Content-Type"]) == ("PUT", "application/json") + assert body == {"retention_days": 30, "smtp_port": "25"} + + def test_alias_create_update_delete_paths(self): + base = "https://api.forwardemail.net/v1/domains/x.be/aliases" + c, t = _client( + { + ("POST", base): [(200, {"id": "new"})], + ("PUT", base + "/id1"): [(200, {"id": "id1"})], + ("DELETE", base + "/id2"): [(200, {})], + } + ) + c.create_alias("x.be", {"name": "a", "recipients": ["x@y.z"]}) + c.update_alias("x.be", "id1", {"is_enabled": False}) + c.delete_alias("x.be", "id2") + assert [(m, u) for m, u, _, _ in t.calls] == [ + ("POST", base), + ("PUT", base + "/id1"), + ("DELETE", base + "/id2"), + ] + + def test_domain_names_are_url_escaped(self): + c, t = _client({("GET", "https://api.forwardemail.net/v1/domains/office.ginsys.net"): [(200, {})]}) + c.get_domain("office.ginsys.net") + assert t.calls[0][1].endswith("/v1/domains/office.ginsys.net") diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py new file mode 100644 index 0000000..8333303 --- /dev/null +++ b/tests/forward_email/test_config.py @@ -0,0 +1,228 @@ +"""Tests for forward_email/config.py (opt-in block + per-domain desired-state files).""" + +import textwrap + +import pytest +from octodns_gitops.forward_email.config import ( + DEFAULT_ALIAS, + DEFAULT_EXPECT, + DEFAULT_SETTINGS, + ForwardEmailConfigError, + load_domain_file, + load_forward_email, +) + + +def _write(tmp_path, name, body): + p = tmp_path / name + p.write_text(textwrap.dedent(body)) + return p + + +class TestPackageDefaults: + def test_smtp_port_is_a_string(self): + # The API stores "25" as a string; an int would produce a permanent diff. + assert DEFAULT_SETTINGS["smtp_port"] == "25" + + def test_decided_domain_defaults(self): + assert DEFAULT_SETTINGS["retention_days"] == 30 + assert DEFAULT_SETTINGS["require_tls_inbound"] is True + assert DEFAULT_SETTINGS["ignore_mx_check"] is False + assert DEFAULT_SETTINGS["max_quota_per_alias"] == "1 GB" + + def test_decided_expectations(self): + assert DEFAULT_EXPECT == { + "has_smtp": True, + "has_newsletter": False, + "max_recipients_per_alias": 10, + "plan": "team", + } + + def test_alias_defaults(self): + assert DEFAULT_ALIAS["error_code_if_disabled"] == 250 + assert DEFAULT_ALIAS["has_recipient_verification"] is False + + +class TestLoadForwardEmail: + def test_absent_block_returns_none(self, tmp_path): + cfg = _write(tmp_path, "config.yaml", "providers: {}\nzones: {}\n") + assert load_forward_email(str(cfg)) is None + + def test_parses_block_with_defaults_and_domains(self, tmp_path): + cfg = _write( + tmp_path, + "config.yaml", + """ + providers: {} + zones: {} + forward_email: + token: env/FORWARD_EMAIL_API_TOKEN + directory: ./mail/forward-email + defaults: + settings: + retention_days: 0 + domains: + - autops.be + - autops.eu + """, + ) + fe = load_forward_email(str(cfg)) + assert fe.token_env == "FORWARD_EMAIL_API_TOKEN" + assert fe.directory == tmp_path / "mail" / "forward-email" + assert fe.domains == ["autops.be", "autops.eu"] + # repo default overrides the package default; everything else stays + assert fe.settings["retention_days"] == 0 + assert fe.settings["require_tls_inbound"] is True + assert fe.expect == DEFAULT_EXPECT + assert fe.alias == DEFAULT_ALIAS + + def test_directory_defaults_relative_to_config(self, tmp_path): + cfg = _write( + tmp_path, + "config.yaml", + """ + forward_email: + domains: [autops.be] + """, + ) + fe = load_forward_email(str(cfg)) + assert fe.directory == tmp_path / "mail" / "forward-email" + assert fe.token_env == "FORWARD_EMAIL_API_TOKEN" + + def test_token_must_be_env_ref(self, tmp_path): + cfg = _write( + tmp_path, + "config.yaml", + """ + forward_email: + token: literal-secret + domains: [autops.be] + """, + ) + with pytest.raises(ForwardEmailConfigError, match="env/"): + load_forward_email(str(cfg)) + + def test_domains_required_and_normalized(self, tmp_path): + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: []\n") + with pytest.raises(ForwardEmailConfigError, match="domains"): + load_forward_email(str(cfg)) + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [Autops.BE., autops.be]\n") + with pytest.raises(ForwardEmailConfigError, match="duplicate"): + load_forward_email(str(cfg)) + + def test_unknown_setting_in_defaults_rejected(self, tmp_path): + # Read-only fields (has_strict_dmarc) must never be declared as settings. + cfg = _write( + tmp_path, + "config.yaml", + """ + forward_email: + defaults: + settings: + has_strict_dmarc: true + domains: [autops.be] + """, + ) + with pytest.raises(ForwardEmailConfigError, match="has_strict_dmarc"): + load_forward_email(str(cfg)) + + +class TestLoadDomainFile: + def test_minimal_file(self, tmp_path): + p = _write( + tmp_path, + "waarschoot.org.yaml", + """ + aliases: + - name: serge + recipients: [serge@ginsys.eu] + - name: wordpress + recipients: serge@ginsys.eu + """, + ) + d = load_domain_file(p, "waarschoot.org") + assert d.domain == "waarschoot.org" + assert d.settings == {} + assert d.expect == {} + assert [a.name for a in d.aliases] == ["serge", "wordpress"] + # scalar recipient normalized to a list + assert d.aliases[1].recipients == ["serge@ginsys.eu"] + + def test_domain_key_must_match_filename(self, tmp_path): + p = _write(tmp_path, "a.be.yaml", "domain: b.be\naliases: []\n") + with pytest.raises(ForwardEmailConfigError, match="b.be"): + load_domain_file(p, "a.be") + + def test_regex_and_catchall_alias_names_accepted(self, tmp_path): + p = _write( + tmp_path, + "k8s.be.yaml", + r""" + aliases: + - name: "*" + recipients: [serge@ginsys.eu] + # single quotes: a double-quoted YAML scalar would parse "\w" as an escape + - name: '/^([\w\-\.]+)$/' + recipients: ["$1@autops.eu"] + """, + ) + d = load_domain_file(p, "k8s.be") + assert d.aliases[0].name == "*" + assert d.aliases[1].name == r"/^([\w\-\.]+)$/" + + def test_alias_fields(self, tmp_path): + p = _write( + tmp_path, + "ginsys.org.yaml", + """ + settings: + ignore_mx_check: true + expect: + has_smtp: false + aliases: + - name: box + recipients: [] + description: an imap box + is_enabled: false + has_imap: true + has_recipient_verification: true + max_quota: 10 GB + error_code_if_disabled: 550 + """, + ) + d = load_domain_file(p, "ginsys.org") + a = d.aliases[0] + assert a.recipients == [] + assert a.description == "an imap box" + assert a.is_enabled is False + assert a.has_imap is True + assert a.has_recipient_verification is True + assert a.max_quota == "10 GB" + assert a.error_code_if_disabled == 550 + assert d.settings == {"ignore_mx_check": True} + assert d.expect == {"has_smtp": False} + + def test_duplicate_alias_name_rejected(self, tmp_path): + p = _write( + tmp_path, + "x.be.yaml", + """ + aliases: + - {name: a, recipients: [x@y.z]} + - {name: a, recipients: [x@y.z]} + """, + ) + with pytest.raises(ForwardEmailConfigError, match="duplicate alias"): + load_domain_file(p, "x.be") + + def test_unknown_alias_key_rejected(self, tmp_path): + p = _write( + tmp_path, + "x.be.yaml", + """ + aliases: + - {name: a, recipients: [x@y.z], storage_used: 5} + """, + ) + with pytest.raises(ForwardEmailConfigError, match="storage_used"): + load_domain_file(p, "x.be") diff --git a/tests/forward_email/test_drift.py b/tests/forward_email/test_drift.py new file mode 100644 index 0000000..a69afb2 --- /dev/null +++ b/tests/forward_email/test_drift.py @@ -0,0 +1,105 @@ +"""Tests for forward_email/drift.py — FE server-generated records vs the octoDNS zone file.""" + +import copy + +from octodns_gitops.forward_email.drift import check_zone + +DKIM = "v=DKIM1; k=rsa; p=MIIBIjANBg;" +LIVE = { + "name": "autops.eu", + "verification_record": "WPoBifGj1Z", + "has_strict_dmarc": False, + "smtp_dns_records": { + "dkim": {"name": "fe-53661bcfc9._domainkey", "value": DKIM}, + "return_path": {"name": "fe-bounces", "value": "forwardemail.net"}, + "dmarc": { + "name": "_dmarc", + "value": "v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-6a61b3b09bc@forwardemail.net;", + }, + }, +} +ZONE = { + "": [ + {"type": "A", "value": "91.98.1.229"}, + { + "type": "MX", + "values": [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + ], + }, + { + "type": "TXT", + "values": [ + "forward-email-site-verification=WPoBifGj1Z", + "v=spf1 include:spf.forwardemail.net ~all", + ], + }, + ], + "_dmarc": { + "type": "TXT", + "value": r"v=DMARC1\; p=quarantine\; pct=25\; rua=mailto:dmarc-6a61b3b09bc@forwardemail.net,mailto:dmarc-report@ginsys.net\;", + }, + "fe-53661bcfc9._domainkey": {"type": "TXT", "value": DKIM.replace(";", r"\;")}, + "fe-bounces": {"type": "CNAME", "value": "forwardemail.net."}, +} + + +def _zone(**edits): + z = copy.deepcopy(ZONE) + for name, rec in edits.items(): + if rec is None: + z.pop(name, None) + else: + z[name] = rec + return z + + +def _fields(findings): + return sorted(f.field for f in findings) + + +class TestClean: + def test_matching_zone_has_no_findings(self): + assert check_zone(LIVE, ZONE, expect_mx=True) == [] + + +class TestFindings: + def test_dkim_value_mismatch(self): + z = _zone(**{"fe-53661bcfc9._domainkey": {"type": "TXT", "value": r"v=DKIM1\; p=OLD\;"}}) + (f,) = check_zone(LIVE, z, expect_mx=True) + assert f.field == "dkim" + assert "fe-53661bcfc9._domainkey" in f.message + + def test_dkim_record_missing(self): + z = _zone(**{"fe-53661bcfc9._domainkey": None}) + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["dkim"] + + def test_return_path_cname_missing(self): + z = _zone(**{"fe-bounces": None}) + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["return_path"] + + def test_verification_txt_missing_from_apex(self): + z = _zone() + z[""][2]["values"] = ["v=spf1 include:spf.forwardemail.net ~all"] + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["verification"] + + def test_dmarc_rua_must_include_fe_address(self): + z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=none\; rua=mailto:x@y.z\;"}) + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["dmarc"] + + def test_dmarc_policy_may_differ_from_fe_suggestion(self): + # FE suggests p=reject; the ramp deliberately publishes quarantine. Not a finding. + assert check_zone(LIVE, ZONE, expect_mx=True) == [] + + def test_strict_dmarc_expectation_derived_from_zone_policy(self): + live = dict(LIVE, has_strict_dmarc=True) # FE thinks reject, zone says quarantine + assert _fields(check_zone(live, ZONE, expect_mx=True)) == ["has_strict_dmarc"] + z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=reject\; rua=mailto:dmarc-6a61b3b09bc@forwardemail.net\;"}) + assert check_zone(live, z, expect_mx=True) == [] + + def test_mx_checked_unless_domain_ignores_it(self): + z = _zone() + z[""][1]["values"] = [{"exchange": "aspmx.l.google.com.", "preference": 1}] + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["mx"] + assert check_zone(LIVE, z, expect_mx=False) == [] diff --git a/tests/forward_email/test_export.py b/tests/forward_email/test_export.py new file mode 100644 index 0000000..2ef4cb2 --- /dev/null +++ b/tests/forward_email/test_export.py @@ -0,0 +1,123 @@ +"""Tests for forward_email/export.py — live state to a per-domain file that round-trips.""" + +import textwrap + +from octodns_gitops.forward_email.config import ( + DEFAULT_ALIAS, + DEFAULT_EXPECT, + DEFAULT_SETTINGS, + ForwardEmailConfig, + load_domain_file, +) +from octodns_gitops.forward_email.export import export_domain +from octodns_gitops.forward_email.reconcile import plan_domain + +GIB = 1024**3 + + +def _cfg(): + return ForwardEmailConfig( + token_env="T", + directory=None, + domains=["x.be"], + settings=dict(DEFAULT_SETTINGS), + expect=dict(DEFAULT_EXPECT), + alias=dict(DEFAULT_ALIAS), + ) + + +def _live_domain(**over): + d = {k: v for k, v in DEFAULT_SETTINGS.items() if k != "max_quota_per_alias"} + d.update(DEFAULT_EXPECT) + d.update({"name": "x.be", "id": "dom1", "has_strict_dmarc": False, "has_catchall": True}) + d.update(over) + return d + + +def _live_alias(name, **over): + a = { + "id": f"id-{name}", + "name": name, + "recipients": ["serge@ginsys.eu"], + "is_enabled": True, + "error_code_if_disabled": 250, + "has_imap": False, + "has_pgp": False, + "has_recipient_verification": False, + "labels": [], + "storage_used": 0, + "vacation_responder": {"is_enabled": False}, + } + a.update(over) + return a + + +class TestExport: + def test_all_defaults_yields_minimal_file(self): + text = export_domain(_cfg(), _live_domain(), [_live_alias("a")]) + assert text == textwrap.dedent( + """\ + domain: x.be + aliases: + - name: a + recipients: + - serge@ginsys.eu + """ + ) + + def test_diverging_settings_and_expectations_are_written(self): + text = export_domain(_cfg(), _live_domain(retention_days=0, has_smtp=False), []) + assert "settings:\n retention_days: 0\n" in text + assert "expect:\n has_smtp: false\n" in text + # derived fields never leak into the file + assert "has_catchall" not in text + assert "has_strict_dmarc" not in text + + def test_regex_name_is_single_quoted(self): + text = export_domain(_cfg(), _live_domain(), [_live_alias(r"/^([\w\-\.]+)$/", recipients=["$1@y.z"])]) + assert r"- name: '/^([\w\-\.]+)$/'" in text + assert "recipients:\n - $1@y.z" in text + + def test_catchall_name_is_quoted(self): + text = export_domain(_cfg(), _live_domain(), [_live_alias("*")]) + assert "- name: '*'" in text + + def test_non_default_alias_fields_are_written_and_quota_as_human_string(self): + alias = _live_alias( + "box", + recipients=[], + description="an imap box", + is_enabled=False, + error_code_if_disabled=550, + has_imap=True, + max_quota=10 * GIB, + storage_used=549_000, + labels=["catch-all"], + vacation_responder={"is_enabled": True, "subject": "away", "message": "back soon"}, + ) + text = export_domain(_cfg(), _live_domain(), [alias]) + assert "recipients: []" in text + assert "description: an imap box" in text + assert "is_enabled: false" in text + assert "error_code_if_disabled: 550" in text + assert "has_imap: true" in text + assert "max_quota: 10 GB" in text + assert "vacation_responder:\n is_enabled: true\n subject: away\n" in text + assert "storage_used" not in text + assert "labels" not in text + assert "has_pgp" not in text + + def test_export_then_plan_is_a_zero_diff(self, tmp_path): + # The A4 acceptance test in miniature. + live_dom = _live_domain(retention_days=0, ignore_mx_check=True, has_newsletter=True) + live_aliases = [ + _live_alias("a"), + _live_alias("*", labels=["catch-all"]), + _live_alias(r"/^(.*)$/", is_enabled=False, recipients=["$1@y.z"]), + _live_alias("box", has_imap=True, max_quota=10 * GIB, storage_used=5), + ] + p = tmp_path / "x.be.yaml" + p.write_text(export_domain(_cfg(), live_dom, live_aliases)) + desired = load_domain_file(p, "x.be") + plan = plan_domain(desired, _cfg(), live_dom, live_aliases, prune=True) + assert plan.is_empty(), (plan.settings, plan.aliases, plan.expect_mismatch, plan.errors) diff --git a/tests/forward_email/test_reconcile.py b/tests/forward_email/test_reconcile.py new file mode 100644 index 0000000..02db23d --- /dev/null +++ b/tests/forward_email/test_reconcile.py @@ -0,0 +1,256 @@ +"""Tests for forward_email/reconcile.py — desired vs live diff, prune guard, quota handling.""" + +import pytest +from octodns_gitops.forward_email.config import ( + DEFAULT_ALIAS, + DEFAULT_EXPECT, + DEFAULT_SETTINGS, + DesiredAlias, + DesiredDomain, + ForwardEmailConfig, +) +from octodns_gitops.forward_email.reconcile import parse_quota, plan_domain + +GIB = 1024**3 + + +def _cfg(**over): + return ForwardEmailConfig( + token_env="T", + directory=None, + domains=["x.be"], + settings={**DEFAULT_SETTINGS, **over.get("settings", {})}, + expect={**DEFAULT_EXPECT, **over.get("expect", {})}, + alias={**DEFAULT_ALIAS, **over.get("alias", {})}, + ) + + +def _live_domain(**over): + """A GET /v1/domains/:d body already matching every package default.""" + d = {k: v for k, v in DEFAULT_SETTINGS.items() if k != "max_quota_per_alias"} + d.update(DEFAULT_EXPECT) + d.update({"name": "x.be", "id": "dom1", "has_strict_dmarc": False}) + d.update(over) + return d + + +def _live_alias(name, **over): + a = { + "id": f"id-{name}", + "name": name, + "recipients": ["serge@ginsys.eu"], + "is_enabled": True, + "error_code_if_disabled": 250, + "has_imap": False, + "has_pgp": False, + "has_recipient_verification": False, + "labels": [], + "storage_used": 0, + "vacation_responder": {"is_enabled": False}, + } + a.update(over) + return a + + +def _desired(aliases=(), settings=None, expect=None): + return DesiredDomain("x.be", settings or {}, expect or {}, list(aliases)) + + +class TestParseQuota: + @pytest.mark.parametrize( + ("text", "expected"), + [("1 GB", GIB), ("10 GB", 10 * GIB), ("512 MB", 512 * 1024**2), ("1GB", GIB), (GIB, GIB)], + ) + def test_human_strings_are_1024_based(self, text, expected): + assert parse_quota(text) == expected + + +class TestZeroDiff: + def test_defaults_everywhere_is_an_empty_plan(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("a")], + prune=False, + ) + assert plan.is_empty() + assert plan.errors == [] + + +class TestSettings: + def test_diverging_setting_is_reported_with_both_values(self): + plan = plan_domain(_desired(), _cfg(), _live_domain(retention_days=0), [], prune=False) + assert [(c.field, c.live, c.desired) for c in plan.settings] == [("retention_days", 0, 30)] + + def test_per_domain_override_beats_repo_default(self): + plan = plan_domain( + _desired(settings={"ignore_mx_check": True}), + _cfg(), + _live_domain(ignore_mx_check=True), + [], + prune=False, + ) + assert plan.settings == [] + + def test_write_only_fields_ride_along_only_with_a_real_change(self): + # max_quota_per_alias cannot be read back, so it never creates a diff on its own … + quiet = plan_domain(_desired(), _cfg(), _live_domain(), [], prune=False) + assert quiet.is_empty() + # … but is part of the PUT body whenever one is sent. + noisy = plan_domain(_desired(), _cfg(), _live_domain(retention_days=0), [], prune=False) + assert noisy.settings_body() == {"retention_days": 30, "max_quota_per_alias": "1 GB"} + + +class TestAliases: + def test_missing_alias_is_created_with_defaults_omitted(self): + plan = plan_domain( + _desired([DesiredAlias("new", ["a@b.c"], description="hi")]), + _cfg(), + _live_domain(), + [], + prune=False, + ) + (chg,) = plan.aliases + assert chg.action == "create" + assert chg.body == {"name": "new", "recipients": ["a@b.c"], "description": "hi"} + + def test_changed_recipients_is_an_update_naming_the_field(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["x@y.z", "serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("a")], + prune=False, + ) + (chg,) = plan.aliases + assert (chg.action, chg.alias_id) == ("update", "id-a") + assert chg.changes == ["recipients"] + assert chg.body["recipients"] == ["x@y.z", "serge@ginsys.eu"] + + def test_recipient_order_does_not_matter(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["b@b.b", "a@a.a"])]), + _cfg(), + _live_domain(), + [_live_alias("a", recipients=["a@a.a", "b@b.b"])], + prune=False, + ) + assert plan.aliases == [] + + def test_server_applied_labels_are_ignored(self): + plan = plan_domain( + _desired([DesiredAlias("*", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("*", labels=["catch-all"])], + prune=False, + ) + assert plan.aliases == [] + + def test_disabled_alias_uses_repo_default_error_code(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"], is_enabled=False)]), + _cfg(), + _live_domain(), + [_live_alias("a", is_enabled=False, error_code_if_disabled=550)], + prune=False, + ) + (chg,) = plan.aliases + assert chg.changes == ["error_code_if_disabled"] + assert chg.body["error_code_if_disabled"] == 250 + + +class TestQuota: + def test_absent_live_quota_means_domain_default(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("a")], + prune=False, + ) + assert plan.aliases == [] + + def test_live_quota_differing_from_domain_default_is_reset_with_blank(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("a", max_quota=10 * GIB)], + prune=False, + ) + (chg,) = plan.aliases + assert chg.changes == ["max_quota"] + assert chg.body["max_quota"] == "" + + def test_live_quota_equal_to_domain_default_is_not_a_diff(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("a", max_quota=GIB)], + prune=False, + ) + assert plan.aliases == [] + + def test_explicit_alias_quota_is_compared_in_bytes_and_sent_as_string(self): + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"], max_quota="10 GB")]), + _cfg(), + _live_domain(), + [_live_alias("a", max_quota=10 * GIB), _live_alias("b")], + prune=False, + ) + assert [c.name for c in plan.aliases] == [] + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"], max_quota="10 GB")]), + _cfg(), + _live_domain(), + [_live_alias("a")], + prune=False, + ) + (chg,) = plan.aliases + assert chg.body["max_quota"] == "10 GB" + + +class TestPrune: + def test_unmanaged_alias_is_listed_but_not_deleted_without_prune(self): + plan = plan_domain(_desired(), _cfg(), _live_domain(), [_live_alias("stray")], prune=False) + assert plan.unmanaged == ["stray"] + assert plan.aliases == [] + assert plan.is_empty() + + def test_prune_deletes_unmanaged_alias(self): + plan = plan_domain(_desired(), _cfg(), _live_domain(), [_live_alias("stray")], prune=True) + (chg,) = plan.aliases + assert (chg.action, chg.name, chg.alias_id) == ("delete", "stray", "id-stray") + + @pytest.mark.parametrize("guard", [{"has_imap": True}, {"storage_used": 1}]) + def test_prune_never_touches_a_mailbox(self, guard): + plan = plan_domain( + _desired(), _cfg(), _live_domain(), [_live_alias("box", **guard)], prune=True + ) + assert plan.aliases == [] + assert len(plan.errors) == 1 + assert "box" in plan.errors[0] + + +class TestExpectations: + def test_read_only_mismatch_is_reported_not_written(self): + plan = plan_domain(_desired(), _cfg(), _live_domain(has_smtp=False), [], prune=False) + assert plan.settings == [] + assert [(m.field, m.live, m.desired) for m in plan.expect_mismatch] == [ + ("has_smtp", False, True) + ] + assert not plan.is_empty() + + def test_per_domain_expectation_override(self): + plan = plan_domain( + _desired(expect={"has_newsletter": True}), + _cfg(), + _live_domain(has_newsletter=True), + [], + prune=False, + ) + assert plan.expect_mismatch == [] From 552754841c0aa5295908cc0e0e0d67a0be59bf63 Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 16:42:58 +0200 Subject: [PATCH 2/7] fix(forward-email): harden writes, validation and drift after review + live dry run Codex review of ginsys/octodns-gitops#1 (6 findings, all confirmed) plus a read-only run against the real account (24 domains: export -> plan is a zero diff on every domain; drift clean on 23, traceback on 1): - prune relist: besides the id set, every planned delete must keep its name and stay a non-mailbox on the second listing - alias create/update bodies carry every resolved flag explicitly, so a repo default such as `is_enabled: false` reaches the API; per-alias-only fields (max_quota, public_key, vacation_responder) are rejected as repo defaults instead of silently ignored - scalar type validation for settings, expectations and alias fields (strict bool; `"false"` or `retention_days: forever` never reach a PUT); `domains:` entries and recipients/labels must be strings - export: digit-leading strings (dates, "25", 1e3) are quoted; strings with newlines are emitted as JSON so YAML reads them back unchanged - drift: a `value:` holding a list (vanginderachter.name apex TXT) no longer raises; a missing smtp_dns_records key is reported as unverifiable rather than clean - CLI: any exception while listing domains or handling one domain is reported with rc 1 instead of a traceback; the run continues Suite 368 passing. --- src/octodns_gitops/cli/forward_email.py | 28 ++++- src/octodns_gitops/forward_email/config.py | 102 +++++++++++++++--- src/octodns_gitops/forward_email/drift.py | 16 ++- src/octodns_gitops/forward_email/export.py | 16 +-- src/octodns_gitops/forward_email/reconcile.py | 10 +- tests/cli/test_forward_email.py | 51 ++++++++- tests/forward_email/test_config.py | 37 +++++++ tests/forward_email/test_drift.py | 12 +++ tests/forward_email/test_export.py | 16 +++ tests/forward_email/test_reconcile.py | 26 ++++- 10 files changed, 277 insertions(+), 37 deletions(-) diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index b25ccea..f4ab21f 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -84,15 +84,26 @@ def _apply(plan: DomainPlan, client, out: TextIO) -> bool: out.write(f" applied alias {chg.action} {chg.name}\n") if not deletes: return True - # A0: never prune from a single listing — re-fetch and require the same id set. + # A0: never prune from a single listing — re-fetch and require the same id set, and for + # every planned delete the same name and still no mailbox (a mailbox may appear under an + # unchanged id between the two listings). before = plan.live_alias_ids - after = {a.get("id") for a in client.list_aliases(plan.domain)} - if before != after: + relisted = {a.get("id"): a for a in client.list_aliases(plan.domain)} + if before != set(relisted): out.write( f" ERROR: alias list for {plan.domain} changed between listings " - f"({len(before)} -> {len(after)} ids); prune aborted, re-run\n" + f"({len(before)} -> {len(relisted)} ids); prune aborted, re-run\n" ) return False + for chg in deletes: + now = relisted[chg.alias_id] + if now.get("name") != chg.name or now.get("has_imap") or (now.get("storage_used") or 0) > 0: + out.write( + f" ERROR: alias {chg.name} ({chg.alias_id}) changed between listings " + f"(now name={now.get('name')!r}, has_imap={now.get('has_imap')}, " + f"storage_used={now.get('storage_used')}); prune aborted, re-run\n" + ) + return False for chg in deletes: client.delete_alias(plan.domain, chg.alias_id) out.write(f" applied alias delete {chg.name}\n") @@ -120,7 +131,11 @@ def run( if mode == "plan": out.write("APPLYING changes (--doit)\n" if doit else "DRY-RUN (default): no changes\n") - live_domains = {d["name"].lower(): d for d in client.list_domains()} + try: + live_domains = {d["name"].lower(): d for d in client.list_domains()} + except Exception as e: # noqa: BLE001 - any failure here means nothing can be judged + out.write(f"ERROR listing domains: {type(e).__name__}: {e}\n") + return 1 rc = 0 for domain in scope: @@ -174,6 +189,9 @@ def run( except (ForwardEmailConfigError, ForwardEmailApiError) as e: out.write(f"{domain:<28} ERROR {e}\n") rc = 1 + except Exception as e: # noqa: BLE001 - one domain's failure must not abort the others + out.write(f"{domain:<28} ERROR {type(e).__name__}: {e}\n") + rc = 1 return rc diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index d77446b..82ed329 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -69,6 +69,61 @@ } ) +# Scalar types per field. `bool` is checked strictly (it is an `int` subclass in Python), and a +# string where a bool/int belongs is rejected: `"false"` would reach the API verbatim. +_BOOL_SETTINGS = { + "has_adult_content_protection", + "has_phishing_protection", + "has_executable_protection", + "has_virus_protection", + "has_recipient_verification", + "ignore_mx_check", + "allow_subdomain_forwarding", + "has_delivery_logs", + "require_tls_inbound", +} +SETTINGS_TYPES: dict[str, type] = { + "smtp_port": str, + "retention_days": int, + "bounce_webhook": str, + "max_quota_per_alias": str, + "alias_default_smtp_limit": int, + **dict.fromkeys(_BOOL_SETTINGS, bool), +} +EXPECT_TYPES: dict[str, type] = { + "has_smtp": bool, + "has_newsletter": bool, + "max_recipients_per_alias": int, + "plan": str, +} +ALIAS_TYPES: dict[str, type] = { + "name": str, + "recipients": (str, list), + "description": str, + "labels": (str, list), + "is_enabled": bool, + "error_code_if_disabled": int, + "has_imap": bool, + "has_pgp": bool, + "public_key": str, + "has_recipient_verification": bool, + "max_quota": str, + "vacation_responder": dict, +} +# Alias fields a repo may default. Per-alias-only fields (quota, key, responder) are excluded: +# a default there would silently be ignored by the reconciler. +ALIAS_DEFAULTABLE: frozenset[str] = frozenset( + { + "is_enabled", + "error_code_if_disabled", + "has_imap", + "has_pgp", + "has_recipient_verification", + "description", + "labels", + } +) + # Decided 2026-08-30 (see the audit plan). `smtp_port` is a *string* on the API. DEFAULT_SETTINGS: dict = { "smtp_port": "25", @@ -163,8 +218,24 @@ def _check_keys(where: str, given: dict, allowed: frozenset[str]) -> None: raise ForwardEmailConfigError(f"{where}: unknown or read-only field(s): {', '.join(unknown)}") -def _normalize_domain(name: str) -> str: - return str(name).strip().rstrip(".").lower() +def _check_types(where: str, given: dict, types: dict) -> None: + for k, v in given.items(): + want = types.get(k) + if want is None: + continue + if want is bool: + ok = isinstance(v, bool) + else: + ok = isinstance(v, want) and not isinstance(v, bool) + if not ok: + names = "/".join(t.__name__ for t in (want if isinstance(want, tuple) else (want,))) + raise ForwardEmailConfigError(f"{where}: {k} must be {names}, got {type(v).__name__} ({v!r})") + + +def _normalize_domain(name) -> str: + if not isinstance(name, str) or not name.strip(): + raise ForwardEmailConfigError(f"forward_email.domains: entries must be non-empty strings, got {name!r}") + return name.strip().rstrip(".").lower() def load_forward_email(config_path: str) -> ForwardEmailConfig | None: @@ -206,7 +277,10 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: alias_over = defaults.get("alias") or {} _check_keys("forward_email.defaults.settings", settings_over, SETTINGS_FIELDS) _check_keys("forward_email.defaults.expect", expect_over, EXPECT_FIELDS) - _check_keys("forward_email.defaults.alias", alias_over, ALIAS_FIELDS - {"name", "recipients"}) + _check_keys("forward_email.defaults.alias", alias_over, ALIAS_DEFAULTABLE) + _check_types("forward_email.defaults.settings", settings_over, SETTINGS_TYPES) + _check_types("forward_email.defaults.expect", expect_over, EXPECT_TYPES) + _check_types("forward_email.defaults.alias", alias_over, ALIAS_TYPES) return ForwardEmailConfig( token_env=token_env, @@ -218,14 +292,14 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: ) -def _as_list(value) -> list[str]: +def _as_list(where: str, value) -> list[str]: if value is None: return [] if isinstance(value, str): return [value] - if isinstance(value, list): - return [str(v) for v in value] - raise ForwardEmailConfigError(f"expected a string or list, got {type(value).__name__}") + if isinstance(value, list) and all(isinstance(v, str) for v in value): + return list(value) + raise ForwardEmailConfigError(f"{where}: expected a string or a list of strings, got {value!r}") def load_domain_file(path: Path, domain: str) -> DesiredDomain: @@ -242,6 +316,8 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: expect = data.get("expect") or {} _check_keys(f"{path}: settings", settings, SETTINGS_FIELDS) _check_keys(f"{path}: expect", expect, EXPECT_FIELDS) + _check_types(f"{path}: settings", settings, SETTINGS_TYPES) + _check_types(f"{path}: expect", expect, EXPECT_TYPES) raw_aliases = data.get("aliases") if raw_aliases is None: @@ -254,24 +330,26 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: for i, raw in enumerate(raw_aliases): if not isinstance(raw, dict) or "name" not in raw: raise ForwardEmailConfigError(f"{path}: aliases[{i}] needs a name") - _check_keys(f"{path}: alias {raw['name']!r}", raw, ALIAS_FIELDS) - name = str(raw["name"]) + where = f"{path}: alias {raw['name']!r}" + _check_keys(where, raw, ALIAS_FIELDS) + _check_types(where, raw, ALIAS_TYPES) + name = raw["name"] if name in seen: raise ForwardEmailConfigError(f"{path}: duplicate alias {name!r}") seen.add(name) aliases.append( DesiredAlias( name=name, - recipients=_as_list(raw.get("recipients")), + recipients=_as_list(f"{where}: recipients", raw.get("recipients")), description=raw.get("description"), - labels=_as_list(raw.get("labels")), + labels=_as_list(f"{where}: labels", raw.get("labels")), is_enabled=raw.get("is_enabled"), error_code_if_disabled=raw.get("error_code_if_disabled"), has_imap=raw.get("has_imap"), has_pgp=raw.get("has_pgp"), public_key=raw.get("public_key"), has_recipient_verification=raw.get("has_recipient_verification"), - max_quota=None if raw.get("max_quota") is None else str(raw["max_quota"]), + max_quota=raw.get("max_quota"), vacation_responder=raw.get("vacation_responder"), ) ) diff --git a/src/octodns_gitops/forward_email/drift.py b/src/octodns_gitops/forward_email/drift.py index 5c6f6ec..13c194c 100644 --- a/src/octodns_gitops/forward_email/drift.py +++ b/src/octodns_gitops/forward_email/drift.py @@ -30,12 +30,14 @@ def _records(zone: dict, name: str, rtype: str) -> list[dict]: def _values(zone: dict, name: str, rtype: str) -> list: + """All values of `name`/`rtype`; `value:` may itself hold a list in hand-written zone files.""" out = [] for r in _records(zone, name, rtype): - if "values" in r: - out.extend(r["values"]) - elif "value" in r: - out.append(r["value"]) + for key in ("values", "value"): + v = r.get(key) + if v is None: + continue + out.extend(v if isinstance(v, list) else [v]) return out @@ -55,6 +57,12 @@ def _dmarc_tags(v: str) -> dict: def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftFinding]: findings: list[DriftFinding] = [] recs = live_domain.get("smtp_dns_records") or {} + # A key FE did not return is unverifiable, never "clean". + findings.extend( + DriftFinding(k, f"Forward Email returned no smtp_dns_records.{k}; cannot verify the zone file") + for k in ("dkim", "return_path", "dmarc") + if not recs.get(k) + ) dkim = recs.get("dkim") if dkim: diff --git a/src/octodns_gitops/forward_email/export.py b/src/octodns_gitops/forward_email/export.py index 0295b46..3c73c61 100644 --- a/src/octodns_gitops/forward_email/export.py +++ b/src/octodns_gitops/forward_email/export.py @@ -7,6 +7,7 @@ from __future__ import annotations +import json import re from .config import ( @@ -17,7 +18,9 @@ ) from .reconcile import _ALIAS_SIMPLE, _vacation_enabled, parse_quota -_PLAIN_OK = re.compile(r"^[A-Za-z0-9$_][A-Za-z0-9$_@.+\- ]*$") +# Plain scalars must start with a letter, `_` or `$` (`$1@…` recipients): anything starting +# with a digit — dates, `1e3`, `"25"` — is quoted so YAML cannot retype it. +_PLAIN_OK = re.compile(r"^[A-Za-z$_][A-Za-z0-9$_@.+\- ]*$") _YAML_WORDS = {"true", "false", "null", "yes", "no", "on", "off", "~"} _QUOTA_UNITS = (("TB", 1024**4), ("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)) @@ -30,14 +33,11 @@ def _scalar(v) -> str: if isinstance(v, (int, float)): return str(v) s = str(v) - plain = ( - bool(_PLAIN_OK.match(s)) - and s == s.strip() - and s.lower() not in _YAML_WORDS - and not re.fullmatch(r"[\d.]+", s) - ) - if plain: + if bool(_PLAIN_OK.match(s)) and s == s.strip() and s.lower() not in _YAML_WORDS: return s + if "\n" in s or "\r" in s or "\t" in s: + # A single-quoted YAML scalar folds newlines; a JSON string is a valid double-quoted one. + return json.dumps(s, ensure_ascii=False) return "'" + s.replace("'", "''") + "'" diff --git a/src/octodns_gitops/forward_email/reconcile.py b/src/octodns_gitops/forward_email/reconcile.py index 83a9c06..b04f1ab 100644 --- a/src/octodns_gitops/forward_email/reconcile.py +++ b/src/octodns_gitops/forward_email/reconcile.py @@ -109,11 +109,14 @@ def _vacation_enabled(v) -> bool: def _alias_body(resolved: dict, defaults: dict) -> dict: - """Create body: the fields that differ from the defaults, plus name/recipients.""" + """Write body: name/recipients plus every resolved flag, explicitly. + + The server's own defaults are not ours (a repo may default `is_enabled: false`), so a + create never leaves a flag for the server to choose. + """ body = {"name": resolved["name"], "recipients": resolved["recipients"]} for f in _ALIAS_SIMPLE: - if resolved[f] != defaults[f]: - body[f] = resolved[f] + body[f] = resolved[f] if _norm_desc(resolved["description"]) != _norm_desc(defaults["description"]): body["description"] = resolved["description"] if resolved["public_key"]: @@ -134,7 +137,6 @@ def _diff_alias(resolved: dict, live: dict, defaults: dict, domain_quota: int) - for f in _ALIAS_SIMPLE: if resolved[f] != live.get(f, defaults[f]): changes.append(f) - body[f] = resolved[f] # an update must carry the value even when it is the default if _norm_desc(resolved["description"]) != _norm_desc(live.get("description")): changes.append("description") body["description"] = _norm_desc(resolved["description"]) diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py index e0773eb..c93a13f 100644 --- a/tests/cli/test_forward_email.py +++ b/tests/cli/test_forward_email.py @@ -182,8 +182,10 @@ def test_doit_sends_settings_and_alias_writes(self, tmp_path): rc, _out = _run(_cfg(tmp_path), client, doit=True) assert rc == 0 assert ("update_domain", "x.be", {"retention_days": 30, "max_quota_per_alias": "1 GB"}) in client.calls - assert ("update_alias", "x.be", "id-a", {"name": "a", "recipients": ["new@y.z"]}) in client.calls - assert ("create_alias", "x.be", {"name": "b", "recipients": ["serge@ginsys.eu"]}) in client.calls + updates = {c[2]: c[3] for c in client.calls if c[0] == "update_alias"} + assert updates["id-a"]["recipients"] == ["new@y.z"] + creates = [c[2] for c in client.calls if c[0] == "create_alias"] + assert [(c["name"], c["recipients"]) for c in creates] == [("b", ["serge@ginsys.eu"])] assert not any(c[0] == "delete_alias" for c in client.calls) def test_prune_deletes_after_a_second_listing_agrees(self, tmp_path): @@ -203,6 +205,24 @@ def test_prune_aborts_when_the_second_listing_differs(self, tmp_path): assert "changed between listings" in out assert not any(c[0] == "delete_alias" for c in client.calls) + @pytest.mark.parametrize( + "mutation", + [ + lambda a: a.update(has_imap=True), + lambda a: a.update(storage_used=1), + lambda a: a.update(name="renamed"), + ], + ids=["became-mailbox", "gained-mail", "renamed"], + ) + def test_prune_aborts_when_a_planned_alias_changed_under_the_same_id(self, tmp_path, mutation): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) + client.mutate_on_relist = lambda c: mutation(c.aliases["x.be"][0]) + rc, out = _run(_cfg(tmp_path), client, doit=True, prune=True) + assert rc == 1 + assert "changed between listings" in out + assert not any(c[0] == "delete_alias" for c in client.calls) + def test_mailbox_guard_blocks_the_whole_domain_apply(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be", retention_days=0)], {"x.be": [_live_alias("box", has_imap=True)]}) @@ -220,6 +240,33 @@ def test_unmanaged_alias_without_prune_is_reported_only(self, tmp_path): assert client.writes() == [] +class TestUnexpectedErrors: + def test_transport_failure_listing_domains_is_rc_1_not_a_traceback(self, tmp_path): + class Broken(FakeClient): + def list_domains(self): + raise OSError("connection refused") + + rc, out = _run(_cfg(tmp_path), Broken([], {})) + assert rc == 1 + assert "connection refused" in out + + def test_per_domain_unexpected_error_is_reported_and_the_run_continues(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + _write_domain_file(tmp_path, "y.be", "aliases: []\n") + + class Broken(FakeClient): + def list_aliases(self, domain): + if domain == "x.be": + raise KeyError("id") + return super().list_aliases(domain) + + client = Broken([_live_domain("x.be"), _live_domain("y.be")], {"y.be": []}) + rc, out = _run(_cfg(tmp_path, ["x.be", "y.be"]), client) + assert rc == 1 + assert "x.be" in out and "KeyError" in out + assert "y.be no changes" in out + + class TestExport: def test_export_writes_one_file_per_claimed_domain(self, tmp_path): client = FakeClient( diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index 8333303..491ee2c 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -127,6 +127,43 @@ def test_unknown_setting_in_defaults_rejected(self, tmp_path): load_forward_email(str(cfg)) +class TestTypeValidation: + @pytest.mark.parametrize( + "block", + [ + "defaults:\n settings:\n retention_days: forever\n", + "defaults:\n settings:\n require_tls_inbound: 'true'\n", + "defaults:\n settings:\n smtp_port: 25\n", # int would diff forever + "defaults:\n alias:\n is_enabled: 'false'\n", + "defaults:\n alias:\n max_quota: 1 GB\n", # only per-alias, never a default + ], + ) + def test_wrong_scalar_types_in_defaults_rejected(self, tmp_path, block): + cfg = _write(tmp_path, "config.yaml", f"forward_email:\n domains: [x.be]\n {block}") + with pytest.raises(ForwardEmailConfigError): + load_forward_email(str(cfg)) + + def test_domains_must_be_strings(self, tmp_path): + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [123]\n") + with pytest.raises(ForwardEmailConfigError, match="string"): + load_forward_email(str(cfg)) + + @pytest.mark.parametrize( + ("body", "needle"), + [ + ("settings:\n retention_days: forever\naliases: []\n", "retention_days"), + ("aliases:\n - {name: a, recipients: [x@y.z], is_enabled: 'false'}\n", "is_enabled"), + ("aliases:\n - {name: a, recipients: [x@y.z], error_code_if_disabled: '250'}\n", "error_code"), + ("aliases:\n - {name: a, recipients: [1]}\n", "recipients"), + ("aliases:\n - {name: a, recipients: [x@y.z], vacation_responder: yes}\n", "vacation_responder"), + ], + ) + def test_wrong_scalar_types_in_domain_file_rejected(self, tmp_path, body, needle): + p = _write(tmp_path, "x.be.yaml", body) + with pytest.raises(ForwardEmailConfigError, match=needle): + load_domain_file(p, "x.be") + + class TestLoadDomainFile: def test_minimal_file(self, tmp_path): p = _write( diff --git a/tests/forward_email/test_drift.py b/tests/forward_email/test_drift.py index a69afb2..1f2d1a1 100644 --- a/tests/forward_email/test_drift.py +++ b/tests/forward_email/test_drift.py @@ -98,6 +98,18 @@ def test_strict_dmarc_expectation_derived_from_zone_policy(self): z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=reject\; rua=mailto:dmarc-6a61b3b09bc@forwardemail.net\;"}) assert check_zone(live, z, expect_mx=True) == [] + def test_apex_txt_value_may_be_a_list(self): + # vanginderachter.name.yaml (live, 2026-08-30) writes `value: [a, b]` instead of `values:`. + z = _zone() + z[""][2] = {"type": "TXT", "value": ["forward-email-site-verification=WPoBifGj1Z", "v=spf1 -all"]} + assert check_zone(LIVE, z, expect_mx=True) == [] + + def test_missing_generated_records_on_the_fe_side_are_unverifiable_not_clean(self): + live = dict(LIVE, smtp_dns_records={}) + assert _fields(check_zone(live, ZONE, expect_mx=True)) == ["dkim", "dmarc", "return_path"] + live = {k: v for k, v in LIVE.items() if k != "smtp_dns_records"} + assert _fields(check_zone(live, ZONE, expect_mx=True)) == ["dkim", "dmarc", "return_path"] + def test_mx_checked_unless_domain_ignores_it(self): z = _zone() z[""][1]["values"] = [{"exchange": "aspmx.l.google.com.", "preference": 1}] diff --git a/tests/forward_email/test_export.py b/tests/forward_email/test_export.py index 2ef4cb2..73bbf6f 100644 --- a/tests/forward_email/test_export.py +++ b/tests/forward_email/test_export.py @@ -107,6 +107,22 @@ def test_non_default_alias_fields_are_written_and_quota_as_human_string(self): assert "labels" not in text assert "has_pgp" not in text + def test_date_like_and_multiline_strings_survive_yaml_round_trip(self, tmp_path): + aliases = [ + _live_alias("a", description="2026-08-30"), + _live_alias("b", description="1e3"), + _live_alias( + "c", + vacation_responder={"is_enabled": True, "subject": "away", "message": "line1\nline2"}, + ), + ] + p = tmp_path / "x.be.yaml" + p.write_text(export_domain(_cfg(), _live_domain(), aliases)) + d = load_domain_file(p, "x.be") + assert d.aliases[0].description == "2026-08-30" + assert d.aliases[1].description == "1e3" + assert d.aliases[2].vacation_responder["message"] == "line1\nline2" + def test_export_then_plan_is_a_zero_diff(self, tmp_path): # The A4 acceptance test in miniature. live_dom = _live_domain(retention_days=0, ignore_mx_check=True, has_newsletter=True) diff --git a/tests/forward_email/test_reconcile.py b/tests/forward_email/test_reconcile.py index 02db23d..792839d 100644 --- a/tests/forward_email/test_reconcile.py +++ b/tests/forward_email/test_reconcile.py @@ -103,7 +103,8 @@ def test_write_only_fields_ride_along_only_with_a_real_change(self): class TestAliases: - def test_missing_alias_is_created_with_defaults_omitted(self): + def test_missing_alias_is_created_with_every_resolved_flag_explicit(self): + # The server's own defaults are not ours: a create must pin every flag we resolve. plan = plan_domain( _desired([DesiredAlias("new", ["a@b.c"], description="hi")]), _cfg(), @@ -113,7 +114,28 @@ def test_missing_alias_is_created_with_defaults_omitted(self): ) (chg,) = plan.aliases assert chg.action == "create" - assert chg.body == {"name": "new", "recipients": ["a@b.c"], "description": "hi"} + assert chg.body == { + "name": "new", + "recipients": ["a@b.c"], + "description": "hi", + "is_enabled": True, + "error_code_if_disabled": 250, + "has_imap": False, + "has_pgp": False, + "has_recipient_verification": False, + } + + def test_repo_alias_default_override_reaches_the_create_body(self): + plan = plan_domain( + _desired([DesiredAlias("new", ["a@b.c"])]), + _cfg(alias={"is_enabled": False, "error_code_if_disabled": 550}), + _live_domain(), + [], + prune=False, + ) + (chg,) = plan.aliases + assert chg.body["is_enabled"] is False + assert chg.body["error_code_if_disabled"] == 550 def test_changed_recipients_is_an_update_naming_the_field(self): plan = plan_domain( From d4732574e05ac8debe00b30e755ab49f352a9f0f Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 17:07:54 +0200 Subject: [PATCH 3/7] fix(forward-email): address the ten Codex review threads on #1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `--doit` and `--dry-run` are mutually exclusive (argparse rejects both, exit 2) - `--export` over an existing file preserves its write-only `bounce_webhook` / `max_quota_per_alias`; the API cannot return them and the next domain PUT would otherwise send the repo default. Alias quotas are exported against that preserved per-domain default, or an omitted alias quota reloads as a reset - apply order: settings PUT, prune re-list, creates/updates, deletes — a create changed the id set, so a create+delete plan always aborted half-applied - alias create sends a non-empty resolved description (a repo default was dropped) - export writes `description: ''` when the live value is blank under a non-empty repo default, so the export still plans as zero diff - `labels` is server-managed: rejected in alias entries and `defaults.alias` with a dedicated error instead of being accepted and never reconciled - drift: a missing/empty `verification_record` is an "unverifiable" finding, mirroring the `smtp_dns_records` handling - `forward_email: {}` / bare key / list is a config error, not an opt-out; the same for a non-mapping `settings:` / `expect:` / `defaults*:` section, which used to collapse to "nothing declared" and enforce the package defaults - unreadable or malformed YAML and a non-string `directory` surface as config errors (rc 2 / per-domain rc 1) instead of tracebacks - DMARC `rua` compared as complete URIs (case-insensitive mailto, `!size` stripped) instead of substring - export emits every key of an enabled vacation_responder, nested values as JSON flow style; known keys first, then sorted --- README.md | 3 +- src/octodns_gitops/cli/forward_email.py | 74 ++++++++++++------ src/octodns_gitops/forward_email/config.py | 76 +++++++++++++------ src/octodns_gitops/forward_email/drift.py | 30 ++++++-- src/octodns_gitops/forward_email/export.py | 41 ++++++---- src/octodns_gitops/forward_email/reconcile.py | 14 ++-- tests/cli/test_forward_email.py | 52 +++++++++++++ tests/forward_email/test_config.py | 47 ++++++++++++ tests/forward_email/test_drift.py | 16 ++++ tests/forward_email/test_export.py | 36 +++++++++ tests/forward_email/test_reconcile.py | 12 +++ 11 files changed, 326 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 06d7920..be9a2b9 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,8 @@ Contract: agrees with the first. An alias with `has_imap: true` or stored mail is a mailbox: it is never pruned and blocks the run until it is added to git or removed in the web UI. - `make mail-export` writes the files from live state (bootstrap, or re-baseline after a deliberate - web-UI change). A freshly exported file must plan as **zero changes**. + web-UI change). A freshly exported file must plan as **zero changes**. Write-only settings already + declared in the file being overwritten are preserved, since the API cannot return them. - `make mail-drift` compares FE's generated DNS records (DKIM key, `fe-bounces` CNAME, verification TXT, the DMARC `rua` address, MX unless `ignore_mx_check`) with the repo's zone file, and reports read-only expectation mismatches. Exit 1 on any finding. diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index f4ab21f..1e74d25 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -24,6 +24,7 @@ from octodns_gitops.forward_email.api import ForwardEmailApiError, ForwardEmailClient from octodns_gitops.forward_email.config import ( + WRITE_ONLY_SETTINGS, ForwardEmailConfig, ForwardEmailConfigError, load_domain_file, @@ -67,26 +68,10 @@ def _print_plan(plan: DomainPlan, out: TextIO) -> None: out.writelines(f" ERROR: {e}\n" for e in plan.errors) -def _apply(plan: DomainPlan, client, out: TextIO) -> bool: - """Perform the writes for one domain. Returns False if the prune guard aborted.""" - body = plan.settings_body() - if body: - client.update_domain(plan.domain, body) - out.write(f" applied settings: {sorted(body)}\n") - deletes = [c for c in plan.aliases if c.action == "delete"] - for chg in plan.aliases: - if chg.action == "create": - client.create_alias(plan.domain, chg.body) - elif chg.action == "update": - client.update_alias(plan.domain, chg.alias_id, chg.body) - else: - continue - out.write(f" applied alias {chg.action} {chg.name}\n") - if not deletes: - return True - # A0: never prune from a single listing — re-fetch and require the same id set, and for - # every planned delete the same name and still no mailbox (a mailbox may appear under an - # unchanged id between the two listings). +def _prune_still_safe(plan: DomainPlan, deletes: list, client, out: TextIO) -> bool: + """A0: never prune from a single listing — re-fetch and require the same id set, and for + every planned delete the same name and still no mailbox (a mailbox may appear under an + unchanged id between the two listings).""" before = plan.live_alias_ids relisted = {a.get("id"): a for a in client.list_aliases(plan.domain)} if before != set(relisted): @@ -104,12 +89,51 @@ def _apply(plan: DomainPlan, client, out: TextIO) -> bool: f"storage_used={now.get('storage_used')}); prune aborted, re-run\n" ) return False + return True + + +def _apply(plan: DomainPlan, client, out: TextIO) -> bool: + """Perform the writes for one domain. Returns False if the prune guard aborted. + + Order: settings PUT, prune re-list, creates/updates, deletes. The re-list must precede + our own creates — they change the id set, so a create+delete plan would otherwise always + abort half-applied. + """ + body = plan.settings_body() + if body: + client.update_domain(plan.domain, body) + out.write(f" applied settings: {sorted(body)}\n") + deletes = [c for c in plan.aliases if c.action == "delete"] + if deletes and not _prune_still_safe(plan, deletes, client, out): + return False + for chg in plan.aliases: + if chg.action == "create": + client.create_alias(plan.domain, chg.body) + elif chg.action == "update": + client.update_alias(plan.domain, chg.alias_id, chg.body) + else: + continue + out.write(f" applied alias {chg.action} {chg.name}\n") for chg in deletes: client.delete_alias(plan.domain, chg.alias_id) out.write(f" applied alias delete {chg.name}\n") return True +def _preserved_write_only(path: Path) -> dict: + """Write-only settings declared in the existing per-domain file: the API cannot return them, + so an export that overwrote the file would drop them and the next domain PUT would send the + repo default instead.""" + if not path.exists(): + return {} + with open(path) as f: + existing = yaml.safe_load(f) or {} + settings = existing.get("settings") if isinstance(existing, dict) else None + if not isinstance(settings, dict): + return {} + return {k: v for k, v in settings.items() if k in WRITE_ONLY_SETTINGS} + + def run( cfg: ForwardEmailConfig, client, @@ -149,8 +173,11 @@ def run( aliases = client.list_aliases(domain) cfg.directory.mkdir(parents=True, exist_ok=True) path = cfg.directory / f"{domain}.yaml" - path.write_text(export_domain(cfg, live, aliases)) + write_only = _preserved_write_only(path) + path.write_text(export_domain(cfg, live, aliases, write_only=write_only)) out.write(f"{domain:<28} wrote {path} ({len(aliases)} aliases)\n") + if write_only: + out.write(f" preserved write-only settings from the previous file: {sorted(write_only)}\n") continue path = cfg.directory / f"{domain}.yaml" @@ -199,8 +226,9 @@ def main() -> int: p = argparse.ArgumentParser(description="Reconcile Forward Email settings and aliases (opt-in)") p.add_argument("--config", default="config.yaml") p.add_argument("--domain", action="append", help="Limit to this domain (repeatable)") - p.add_argument("--doit", action="store_true", help="Perform writes (default dry-run)") - p.add_argument("--dry-run", action="store_true", help="Preview only (the default; accepted for symmetry)") + w = p.add_mutually_exclusive_group() + w.add_argument("--doit", action="store_true", help="Perform writes (default dry-run)") + w.add_argument("--dry-run", action="store_true", help="Preview only (the default; accepted for symmetry)") p.add_argument("--prune", action="store_true", help="Delete aliases absent from git (never mailboxes)") g = p.add_mutually_exclusive_group() g.add_argument("--export", action="store_true", help="Write per-domain files from live state") diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index 82ed329..4ce1a73 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -17,7 +17,7 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path import yaml @@ -51,13 +51,14 @@ {"has_smtp", "has_newsletter", "max_recipients_per_alias", "plan"} ) -# Alias fields the alias create/update endpoints accept. +# Alias fields the alias create/update endpoints accept. `labels` is deliberately absent: the +# server applies it (`catch-all`), so declaring it would plan as clean and do nothing. +SERVER_MANAGED_ALIAS_FIELDS: frozenset[str] = frozenset({"labels"}) ALIAS_FIELDS: frozenset[str] = frozenset( { "name", "recipients", "description", - "labels", "is_enabled", "error_code_if_disabled", "has_imap", @@ -100,7 +101,6 @@ "name": str, "recipients": (str, list), "description": str, - "labels": (str, list), "is_enabled": bool, "error_code_if_disabled": int, "has_imap": bool, @@ -120,7 +120,6 @@ "has_pgp", "has_recipient_verification", "description", - "labels", } ) @@ -155,7 +154,6 @@ "has_pgp": False, "has_recipient_verification": False, "description": None, - "labels": [], } DEFAULT_DIRECTORY = "mail/forward-email" @@ -183,7 +181,6 @@ class DesiredAlias: name: str recipients: list[str] description: str | None = None - labels: list[str] = field(default_factory=list) is_enabled: bool | None = None error_code_if_disabled: int | None = None has_imap: bool | None = None @@ -205,19 +202,45 @@ class DesiredDomain: def _load_yaml(path: Path) -> dict: if not path.exists(): raise ForwardEmailConfigError(f"file not found: {path}") - with open(path) as f: - data = yaml.safe_load(f) or {} + try: + with open(path) as f: + data = yaml.safe_load(f) or {} + except (OSError, yaml.YAMLError) as e: + raise ForwardEmailConfigError(f"{path}: {type(e).__name__}: {e}") from e if not isinstance(data, dict): raise ForwardEmailConfigError(f"{path}: expected a mapping at top level") return data +def _section(where: str, container: dict, key: str) -> dict: + """An optional mapping-valued key. Absent or `null` is an empty mapping; anything else that is + not a mapping (`[]`, `false`, a scalar) is an error — never silently "nothing declared", since + the package defaults would then be enforced from a file the author got wrong.""" + value = container.get(key) + if value is None: + return {} + if not isinstance(value, dict): + raise ForwardEmailConfigError(f"{where}: expected a mapping, got {type(value).__name__} ({value!r})") + return value + + def _check_keys(where: str, given: dict, allowed: frozenset[str]) -> None: unknown = sorted(set(given) - allowed) if unknown: raise ForwardEmailConfigError(f"{where}: unknown or read-only field(s): {', '.join(unknown)}") +def _check_alias_keys(where: str, given: dict, allowed: frozenset[str]) -> None: + """Like `_check_keys`, but a server-managed field gets its own message: accepting it would + plan as clean while doing nothing, and "unknown" would send the reader looking for a typo.""" + managed = sorted(set(given) & SERVER_MANAGED_ALIAS_FIELDS) + if managed: + raise ForwardEmailConfigError( + f"{where}: {', '.join(managed)} is server-managed by Forward Email and cannot be declared" + ) + _check_keys(where, given, allowed) + + def _check_types(where: str, given: dict, types: dict) -> None: for k, v in given.items(): want = types.get(k) @@ -242,11 +265,14 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: """Parse the `forward_email:` block. Returns None when the repo has not opted in.""" cfg_file = Path(config_path) cfg = _load_yaml(cfg_file) - block = cfg.get("forward_email") - if not block: + if "forward_email" not in cfg: return None - if not isinstance(block, dict): - raise ForwardEmailConfigError("forward_email: expected a mapping") + # The key itself is the opt-in: a present-but-empty block is a broken config, never an opt-out. + block = cfg["forward_email"] + if not isinstance(block, dict) or not block: + raise ForwardEmailConfigError( + "forward_email: expected a non-empty mapping (remove the key entirely to opt out)" + ) token = block.get("token", f"env/{DEFAULT_TOKEN_ENV}") if not isinstance(token, str) or not token.startswith("env/") or len(token) <= 4: @@ -255,7 +281,10 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: ) token_env = token[len("env/") :] - directory = Path(block.get("directory", DEFAULT_DIRECTORY)) + raw_directory = block.get("directory", DEFAULT_DIRECTORY) + if not isinstance(raw_directory, str) or not raw_directory.strip(): + raise ForwardEmailConfigError(f"forward_email.directory must be a non-empty string, got {raw_directory!r}") + directory = Path(raw_directory) if not directory.is_absolute(): directory = cfg_file.resolve().parent / directory @@ -269,15 +298,13 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: raise ForwardEmailConfigError(f"forward_email.domains: duplicate entry {n!r}") domains.append(n) - defaults = block.get("defaults") or {} - if not isinstance(defaults, dict): - raise ForwardEmailConfigError("forward_email.defaults: expected a mapping") - settings_over = defaults.get("settings") or {} - expect_over = defaults.get("expect") or {} - alias_over = defaults.get("alias") or {} + defaults = _section("forward_email.defaults", block, "defaults") + settings_over = _section("forward_email.defaults.settings", defaults, "settings") + expect_over = _section("forward_email.defaults.expect", defaults, "expect") + alias_over = _section("forward_email.defaults.alias", defaults, "alias") _check_keys("forward_email.defaults.settings", settings_over, SETTINGS_FIELDS) _check_keys("forward_email.defaults.expect", expect_over, EXPECT_FIELDS) - _check_keys("forward_email.defaults.alias", alias_over, ALIAS_DEFAULTABLE) + _check_alias_keys("forward_email.defaults.alias", alias_over, ALIAS_DEFAULTABLE) _check_types("forward_email.defaults.settings", settings_over, SETTINGS_TYPES) _check_types("forward_email.defaults.expect", expect_over, EXPECT_TYPES) _check_types("forward_email.defaults.alias", alias_over, ALIAS_TYPES) @@ -312,8 +339,8 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: ) _check_keys(f"{path}", data, frozenset({"domain", "settings", "expect", "aliases"})) - settings = data.get("settings") or {} - expect = data.get("expect") or {} + settings = _section(f"{path}: settings", data, "settings") + expect = _section(f"{path}: expect", data, "expect") _check_keys(f"{path}: settings", settings, SETTINGS_FIELDS) _check_keys(f"{path}: expect", expect, EXPECT_FIELDS) _check_types(f"{path}: settings", settings, SETTINGS_TYPES) @@ -331,7 +358,7 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: if not isinstance(raw, dict) or "name" not in raw: raise ForwardEmailConfigError(f"{path}: aliases[{i}] needs a name") where = f"{path}: alias {raw['name']!r}" - _check_keys(where, raw, ALIAS_FIELDS) + _check_alias_keys(where, raw, ALIAS_FIELDS) _check_types(where, raw, ALIAS_TYPES) name = raw["name"] if name in seen: @@ -342,7 +369,6 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: name=name, recipients=_as_list(f"{where}: recipients", raw.get("recipients")), description=raw.get("description"), - labels=_as_list(f"{where}: labels", raw.get("labels")), is_enabled=raw.get("is_enabled"), error_code_if_disabled=raw.get("error_code_if_disabled"), has_imap=raw.get("has_imap"), diff --git a/src/octodns_gitops/forward_email/drift.py b/src/octodns_gitops/forward_email/drift.py index 13c194c..5f78197 100644 --- a/src/octodns_gitops/forward_email/drift.py +++ b/src/octodns_gitops/forward_email/drift.py @@ -54,6 +54,20 @@ def _dmarc_tags(v: str) -> dict: return tags +def _rua_uris(tag: str) -> set[str]: + """The complete URIs of a `rua=` tag, compared exactly — never as substrings, which would + accept `mailto:x@forwardemail.net.example.org`. Mail addresses compare case-insensitively + and without an RFC 7489 `!size` suffix.""" + out = set() + for uri in tag.split(","): + uri = uri.strip() + if uri.lower().startswith("mailto:"): + uri = uri.split("!", 1)[0].lower() + if uri: + out.add(uri) + return out + + def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftFinding]: findings: list[DriftFinding] = [] recs = live_domain.get("smtp_dns_records") or {} @@ -79,7 +93,11 @@ def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftF findings.append(DriftFinding("return_path", f"{rp['name']} CNAME: expected {rp['value']}, zone has {got}")) token = live_domain.get("verification_record") - if token: + if not token: + findings.append( + DriftFinding("verification", "Forward Email returned no verification_record; cannot verify the apex TXT") + ) + else: want = f"forward-email-site-verification={token}" if want not in [_unescape_txt(v) for v in _values(zone, "", "TXT")]: findings.append(DriftFinding("verification", f"apex TXT {want} missing")) @@ -87,10 +105,12 @@ def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftF dmarc = recs.get("dmarc") zone_dmarc = _values(zone, "_dmarc", "TXT") if dmarc: - fe_rua = _dmarc_tags(dmarc["value"]).get("rua", "") - published = [_dmarc_tags(v) for v in zone_dmarc] - if not any(fe_rua and fe_rua in t.get("rua", "") for t in published): - findings.append(DriftFinding("dmarc", f"_dmarc TXT does not report to FE ({fe_rua or 'no rua'})")) + fe_rua = _rua_uris(_dmarc_tags(dmarc["value"]).get("rua", "")) + published = [_rua_uris(_dmarc_tags(v).get("rua", "")) for v in zone_dmarc] + if not fe_rua or not any(fe_rua <= p for p in published): + findings.append( + DriftFinding("dmarc", f"_dmarc TXT does not report to FE ({', '.join(sorted(fe_rua)) or 'no rua'})") + ) if "has_strict_dmarc" in live_domain and zone_dmarc: strict = any(_dmarc_tags(v).get("p", "").lower() == "reject" for v in zone_dmarc) diff --git a/src/octodns_gitops/forward_email/export.py b/src/octodns_gitops/forward_email/export.py index 3c73c61..13d4598 100644 --- a/src/octodns_gitops/forward_email/export.py +++ b/src/octodns_gitops/forward_email/export.py @@ -16,7 +16,7 @@ WRITE_ONLY_SETTINGS, ForwardEmailConfig, ) -from .reconcile import _ALIAS_SIMPLE, _vacation_enabled, parse_quota +from .reconcile import _ALIAS_SIMPLE, _norm_desc, _vacation_enabled, parse_quota # Plain scalars must start with a letter, `_` or `$` (`$1@…` recipients): anything starting # with a digit — dates, `1e3`, `"25"` — is quoted so YAML cannot retype it. @@ -32,6 +32,9 @@ def _scalar(v) -> str: return "true" if v else "false" if isinstance(v, (int, float)): return str(v) + if isinstance(v, (dict, list)): + # JSON is valid YAML flow style; keeps nested values typed on reload. + return json.dumps(v, ensure_ascii=False) s = str(v) if bool(_PLAIN_OK.match(s)) and s == s.strip() and s.lower() not in _YAML_WORDS: return s @@ -60,8 +63,11 @@ def _alias_lines(live: dict, defaults: dict, domain_quota: int) -> list[str]: ind = " " out = [f" - name: {_scalar(live['name'])}"] _list(out, "recipients", live.get("recipients") or [], ind) - if live.get("description"): - out.append(f"{ind}description: {_scalar(live['description'])}") + # Written whenever it differs from the resolved default — including a blank live value + # under a non-empty repo default, or reloading would inherit the default and plan an update. + desc = _norm_desc(live.get("description")) + if desc != _norm_desc(defaults["description"]): + out.append(f"{ind}description: {_scalar(desc)}") for f in _ALIAS_SIMPLE: if live.get(f, defaults[f]) != defaults[f]: out.append(f"{ind}{f}: {_scalar(live[f])}") @@ -71,22 +77,27 @@ def _alias_lines(live: dict, defaults: dict, domain_quota: int) -> list[str]: out.append(f"{ind}max_quota: {human_quota(int(live['max_quota']))}") vac = live.get("vacation_responder") if _vacation_enabled(vac): + # Every live key, or the reconciler (which compares the whole mapping) plans an update. out.append(f"{ind}vacation_responder:") - for k in ("is_enabled", "subject", "message"): - if k in vac: - out.append(f"{ind} {k}: {_scalar(vac[k])}") + known = ("is_enabled", "subject", "message") + keys = [k for k in known if k in vac] + sorted(k for k in vac if k not in known) + out.extend(f"{ind} {k}: {_scalar(vac[k])}" for k in keys) return out -def export_domain(cfg: ForwardEmailConfig, live_domain: dict, live_aliases: list[dict]) -> str: - """Return the YAML text for `live_domain`, omitting everything equal to the resolved defaults.""" +def export_domain( + cfg: ForwardEmailConfig, live_domain: dict, live_aliases: list[dict], *, write_only: dict | None = None +) -> str: + """Return the YAML text for `live_domain`, omitting everything equal to the resolved defaults. + + `write_only` carries `WRITE_ONLY_SETTINGS` values the API cannot return (taken from the file + being overwritten); they are emitted like any other non-default setting. + """ lines = [f"domain: {_scalar(live_domain['name'])}"] - settings = { - f: live_domain[f] - for f in sorted(SETTINGS_FIELDS - WRITE_ONLY_SETTINGS) - if f in live_domain and live_domain[f] != cfg.settings.get(f) - } + readable = {f: live_domain[f] for f in SETTINGS_FIELDS - WRITE_ONLY_SETTINGS if f in live_domain} + preserved = {f: v for f, v in (write_only or {}).items() if f in WRITE_ONLY_SETTINGS} + settings = {f: v for f, v in sorted({**readable, **preserved}.items()) if v != cfg.settings.get(f)} if settings: lines.append("settings:") lines.extend(f" {k}: {_scalar(v)}" for k, v in settings.items()) @@ -100,7 +111,9 @@ def export_domain(cfg: ForwardEmailConfig, live_domain: dict, live_aliases: list lines.append("expect:") lines.extend(f" {k}: {_scalar(v)}" for k, v in expect.items()) - domain_quota = parse_quota(cfg.settings.get("max_quota_per_alias") or 0) + # Alias quotas resolve against the per-domain default the reloaded file will carry — a + # preserved `max_quota_per_alias` included — or an omitted alias quota reloads as a reset. + domain_quota = parse_quota({**cfg.settings, **preserved}.get("max_quota_per_alias") or 0) if not live_aliases: lines.append("aliases: []") else: diff --git a/src/octodns_gitops/forward_email/reconcile.py b/src/octodns_gitops/forward_email/reconcile.py index b04f1ab..4baeccf 100644 --- a/src/octodns_gitops/forward_email/reconcile.py +++ b/src/octodns_gitops/forward_email/reconcile.py @@ -10,7 +10,7 @@ on their own; they ride along in every domain PUT that a verifiable change triggers. - Alias `max_quota` is bytes on GET and a human string on PUT; absent on GET means "domain default". A live value differing from the desired one is reset with a blank PUT. -- `labels` is server-applied (`catch-all`) and never compared. +- `labels` is server-applied (`catch-all`): never compared here, rejected by the config loader. - A prune never deletes an alias with `has_imap` or stored mail: that is a mailbox. Such an alias missing from git is an error that blocks the run. """ @@ -108,16 +108,16 @@ def _vacation_enabled(v) -> bool: return bool(v) and bool(v.get("is_enabled")) -def _alias_body(resolved: dict, defaults: dict) -> dict: +def _alias_body(resolved: dict) -> dict: """Write body: name/recipients plus every resolved flag, explicitly. - The server's own defaults are not ours (a repo may default `is_enabled: false`), so a - create never leaves a flag for the server to choose. + The server's own defaults are not ours (a repo may default `is_enabled: false`, or a + non-empty description), so a create never leaves a flag for the server to choose. """ body = {"name": resolved["name"], "recipients": resolved["recipients"]} for f in _ALIAS_SIMPLE: body[f] = resolved[f] - if _norm_desc(resolved["description"]) != _norm_desc(defaults["description"]): + if _norm_desc(resolved["description"]): body["description"] = resolved["description"] if resolved["public_key"]: body["public_key"] = resolved["public_key"] @@ -130,7 +130,7 @@ def _alias_body(resolved: dict, defaults: dict) -> dict: def _diff_alias(resolved: dict, live: dict, defaults: dict, domain_quota: int) -> AliasChange | None: changes: list[str] = [] - body = _alias_body(resolved, defaults) + body = _alias_body(resolved) if sorted(resolved["recipients"]) != sorted(live.get("recipients") or []): changes.append("recipients") @@ -193,7 +193,7 @@ def plan_domain( resolved = _resolve_alias(want, cfg.alias) live = live_by_name.get(want.name) if live is None: - plan.aliases.append(AliasChange("create", want.name, None, _alias_body(resolved, cfg.alias), ["new"])) + plan.aliases.append(AliasChange("create", want.name, None, _alias_body(resolved), ["new"])) continue chg = _diff_alias(resolved, live, cfg.alias, domain_quota) if chg: diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py index c93a13f..6425772 100644 --- a/tests/cli/test_forward_email.py +++ b/tests/cli/test_forward_email.py @@ -81,6 +81,8 @@ def update_domain(self, name, body): def create_alias(self, domain, body): self.calls.append(("create_alias", domain, body)) + # A real create changes the id set the prune guard re-lists. + self.aliases.setdefault(domain, []).append(_live_alias(**body)) return {} def update_alias(self, domain, alias_id, body): @@ -89,6 +91,7 @@ def update_alias(self, domain, alias_id, body): def delete_alias(self, domain, alias_id): self.calls.append(("delete_alias", domain, alias_id)) + self.aliases[domain] = [a for a in self.aliases.get(domain, []) if a["id"] != alias_id] def writes(self): return [c for c in self.calls if c[0] != "list_aliases"] @@ -196,6 +199,15 @@ def test_prune_deletes_after_a_second_listing_agrees(self, tmp_path): assert client.calls.count(("list_aliases", "x.be")) == 2 assert ("delete_alias", "x.be", "id-stray") in client.calls + def test_create_and_prune_in_one_plan_relists_before_creating(self, tmp_path): + # A create changes the id set; re-listing after it would always abort the prune. + _write_domain_file(tmp_path, "x.be", "aliases:\n - {name: b, recipients: [serge@ginsys.eu]}\n") + client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) + rc, out = _run(_cfg(tmp_path), client, doit=True, prune=True) + assert rc == 0, out + assert [c[0] for c in client.calls] == ["list_aliases", "list_aliases", "create_alias", "delete_alias"] + assert ("delete_alias", "x.be", "id-stray") in client.calls + def test_prune_aborts_when_the_second_listing_differs(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be")], {"x.be": [_live_alias("stray")]}) @@ -280,6 +292,29 @@ def test_export_writes_one_file_per_claimed_domain(self, tmp_path): assert (tmp_path / "mail" / "y.be.yaml").read_text() == "domain: y.be\naliases: []\n" assert client.writes() == [] + def test_export_preserves_write_only_settings_from_the_existing_file(self, tmp_path): + # bounce_webhook / max_quota_per_alias cannot be read back; an overwrite would drop them + # and the next unrelated domain PUT would silently send the repo default instead. + _write_domain_file( + tmp_path, + "x.be", + """ + settings: + bounce_webhook: https://hooks.example/fe + max_quota_per_alias: 10 GB + retention_days: 5 + aliases: [] + """, + ) + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, mode="export") + assert rc == 0 + text = (tmp_path / "mail" / "x.be.yaml").read_text() + assert "bounce_webhook: 'https://hooks.example/fe'" in text + assert "max_quota_per_alias: '10 GB'" in text + assert "retention_days" not in text # readable fields come from live state, not the old file + assert "preserved write-only" in out and "bounce_webhook" in out + class TestDrift: ZONE = textwrap.dedent( @@ -366,6 +401,23 @@ def test_main_without_opt_in_block_is_a_noop(self, tmp_path, monkeypatch, capsys assert main() == 0 assert "not configured" in capsys.readouterr().out + def test_main_rejects_doit_together_with_dry_run(self, tmp_path, monkeypatch, capsys): + cfg = tmp_path / "config.yaml" + cfg.write_text("forward_email:\n domains: [x.be]\n") + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg), "--doit", "--dry-run", "--prune"]) + with pytest.raises(SystemExit) as e: + main() + assert e.value.code == 2 + assert "not allowed with" in capsys.readouterr().err + + @pytest.mark.parametrize("text", ["forward_email: [\n", "forward_email:\n domains: [x.be]\n directory: 5\n"]) + def test_main_reports_malformed_config_as_rc_2_not_a_traceback(self, tmp_path, monkeypatch, capsys, text): + cfg = tmp_path / "config.yaml" + cfg.write_text(text) + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg)]) + assert main() == 2 + assert "config error" in capsys.readouterr().err + def test_main_refuses_without_token_env(self, tmp_path, monkeypatch, capsys): cfg = tmp_path / "config.yaml" cfg.write_text("forward_email:\n token: env/FE_TEST_TOKEN\n domains: [x.be]\n") diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index 491ee2c..42b5706 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -48,6 +48,13 @@ def test_absent_block_returns_none(self, tmp_path): cfg = _write(tmp_path, "config.yaml", "providers: {}\nzones: {}\n") assert load_forward_email(str(cfg)) is None + @pytest.mark.parametrize("block", ["forward_email: {}\n", "forward_email:\n", "forward_email: []\n"]) + def test_present_but_empty_block_is_an_error_not_an_opt_out(self, tmp_path, block): + # The key is the opt-in; an emptied block must not silently disable every mail command. + cfg = _write(tmp_path, "config.yaml", f"providers: {{}}\n{block}") + with pytest.raises(ForwardEmailConfigError, match="forward_email"): + load_forward_email(str(cfg)) + def test_parses_block_with_defaults_and_domains(self, tmp_path): cfg = _write( tmp_path, @@ -143,6 +150,37 @@ def test_wrong_scalar_types_in_defaults_rejected(self, tmp_path, block): with pytest.raises(ForwardEmailConfigError): load_forward_email(str(cfg)) + @pytest.mark.parametrize( + "block", + [ + "defaults: []\n", + "defaults:\n settings: []\n", + "defaults:\n expect: false\n", + "defaults:\n alias: []\n", + "directory: 5\n", + ], + ) + def test_non_mapping_sections_in_the_block_are_rejected_not_treated_as_absent(self, tmp_path, block): + # `settings: []` used to become `{}` and the package defaults were then enforced. + cfg = _write(tmp_path, "config.yaml", f"forward_email:\n domains: [x.be]\n {block}") + with pytest.raises(ForwardEmailConfigError): + load_forward_email(str(cfg)) + + @pytest.mark.parametrize("body", ["settings: []\naliases: []\n", "settings: false\n", "expect: x\n"]) + def test_non_mapping_sections_in_the_domain_file_are_rejected(self, tmp_path, body): + p = _write(tmp_path, "x.be.yaml", body) + with pytest.raises(ForwardEmailConfigError, match="mapping"): + load_domain_file(p, "x.be") + + def test_unreadable_or_malformed_yaml_is_a_config_error(self, tmp_path): + p = _write(tmp_path, "x.be.yaml", "aliases: [\n") + with pytest.raises(ForwardEmailConfigError, match="x.be.yaml"): + load_domain_file(p, "x.be") + d = tmp_path / "dir.yaml" + d.mkdir() + with pytest.raises(ForwardEmailConfigError, match="dir.yaml"): + load_domain_file(d, "x.be") + def test_domains_must_be_strings(self, tmp_path): cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [123]\n") with pytest.raises(ForwardEmailConfigError, match="string"): @@ -252,6 +290,15 @@ def test_duplicate_alias_name_rejected(self, tmp_path): with pytest.raises(ForwardEmailConfigError, match="duplicate alias"): load_domain_file(p, "x.be") + def test_labels_are_server_managed_and_rejected(self, tmp_path): + # Accepted-but-never-reconciled would plan as clean while doing nothing. + p = _write(tmp_path, "x.be.yaml", "aliases:\n - {name: a, recipients: [x@y.z], labels: [vip]}\n") + with pytest.raises(ForwardEmailConfigError, match="server-managed"): + load_domain_file(p, "x.be") + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [x.be]\n defaults:\n alias:\n labels: [vip]\n") + with pytest.raises(ForwardEmailConfigError, match="server-managed"): + load_forward_email(str(cfg)) + def test_unknown_alias_key_rejected(self, tmp_path): p = _write( tmp_path, diff --git a/tests/forward_email/test_drift.py b/tests/forward_email/test_drift.py index 1f2d1a1..a26d31b 100644 --- a/tests/forward_email/test_drift.py +++ b/tests/forward_email/test_drift.py @@ -2,6 +2,7 @@ import copy +import pytest from octodns_gitops.forward_email.drift import check_zone DKIM = "v=DKIM1; k=rsa; p=MIIBIjANBg;" @@ -88,6 +89,21 @@ def test_dmarc_rua_must_include_fe_address(self): z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=none\; rua=mailto:x@y.z\;"}) assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["dmarc"] + def test_dmarc_rua_is_matched_as_a_whole_uri_not_a_substring(self): + z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=none\; rua=mailto:dmarc-6a61b3b09bc@forwardemail.net.example.org\;"}) + assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["dmarc"] + z = _zone(_dmarc={"type": "TXT", "value": r"v=DMARC1\; p=none\; rua=mailto:x@y.z, mailto:DMARC-6a61b3b09bc@ForwardEmail.net!10m\;"}) + assert check_zone(LIVE, z, expect_mx=True) == [] + + @pytest.mark.parametrize("token", [None, ""]) + def test_missing_verification_record_is_unverifiable_not_clean(self, token): + live = {k: v for k, v in LIVE.items() if k != "verification_record"} + if token is not None: + live["verification_record"] = token + (f,) = check_zone(live, ZONE, expect_mx=True) + assert f.field == "verification" + assert "cannot verify" in f.message + def test_dmarc_policy_may_differ_from_fe_suggestion(self): # FE suggests p=reject; the ramp deliberately publishes quarantine. Not a finding. assert check_zone(LIVE, ZONE, expect_mx=True) == [] diff --git a/tests/forward_email/test_export.py b/tests/forward_email/test_export.py index 73bbf6f..6c74df2 100644 --- a/tests/forward_email/test_export.py +++ b/tests/forward_email/test_export.py @@ -123,6 +123,42 @@ def test_date_like_and_multiline_strings_survive_yaml_round_trip(self, tmp_path) assert d.aliases[1].description == "1e3" assert d.aliases[2].vacation_responder["message"] == "line1\nline2" + def test_blank_live_description_under_a_non_empty_default_is_written_explicitly(self, tmp_path): + cfg = _cfg() + cfg.alias["description"] = "managed in git" + live_aliases = [_live_alias("a", description=""), _live_alias("b", description=None), _live_alias("c")] + text = export_domain(cfg, _live_domain(), live_aliases) + assert text.count("description: ''") == 3 + p = tmp_path / "x.be.yaml" + p.write_text(text) + plan = plan_domain(load_domain_file(p, "x.be"), cfg, _live_domain(), live_aliases, prune=True) + assert plan.is_empty(), plan.aliases + + def test_every_vacation_responder_key_is_exported(self, tmp_path): + vac = {"is_enabled": True, "subject": "away", "message": "back", "end_date": "2026-09-01", "extra": {"k": 1}} + live_aliases = [_live_alias("a", vacation_responder=dict(vac))] + text = export_domain(_cfg(), _live_domain(), live_aliases) + assert "vacation_responder:\n is_enabled: true\n subject: away\n message: back\n" in text + assert "end_date: '2026-09-01'" in text + p = tmp_path / "x.be.yaml" + p.write_text(text) + desired = load_domain_file(p, "x.be") + assert desired.aliases[0].vacation_responder == vac + assert plan_domain(desired, _cfg(), _live_domain(), live_aliases, prune=True).is_empty() + + def test_alias_quotas_are_compared_against_the_preserved_per_domain_default(self, tmp_path): + # A preserved `max_quota_per_alias: 10 GB` is what the reloaded file resolves aliases against; + # comparing exports against the repo default instead turned a live 1 GiB alias into a reset. + live_aliases = [_live_alias("a", max_quota=GIB), _live_alias("b", max_quota=10 * GIB), _live_alias("c")] + text = export_domain(_cfg(), _live_domain(), live_aliases, write_only={"max_quota_per_alias": "10 GB"}) + assert "max_quota_per_alias: '10 GB'" in text + assert " - name: a\n recipients:\n - serge@ginsys.eu\n max_quota: 1 GB\n" in text + assert text.count("max_quota:") == 1 + p = tmp_path / "x.be.yaml" + p.write_text(text) + plan = plan_domain(load_domain_file(p, "x.be"), _cfg(), _live_domain(), live_aliases, prune=True) + assert plan.is_empty(), plan.aliases + def test_export_then_plan_is_a_zero_diff(self, tmp_path): # The A4 acceptance test in miniature. live_dom = _live_domain(retention_days=0, ignore_mx_check=True, has_newsletter=True) diff --git a/tests/forward_email/test_reconcile.py b/tests/forward_email/test_reconcile.py index 792839d..10e4c71 100644 --- a/tests/forward_email/test_reconcile.py +++ b/tests/forward_email/test_reconcile.py @@ -137,6 +137,18 @@ def test_repo_alias_default_override_reaches_the_create_body(self): assert chg.body["is_enabled"] is False assert chg.body["error_code_if_disabled"] == 550 + def test_repo_default_description_reaches_the_create_body(self): + # The server's default is an empty description, not the repo's. + plan = plan_domain( + _desired([DesiredAlias("new", ["a@b.c"])]), + _cfg(alias={"description": "managed in git"}), + _live_domain(), + [], + prune=False, + ) + (chg,) = plan.aliases + assert chg.body["description"] == "managed in git" + def test_changed_recipients_is_an_update_naming_the_field(self): plan = plan_domain( _desired([DesiredAlias("a", ["x@y.z", "serge@ginsys.eu"])]), From f76b8ee93d262aa4eb3605046e0e321f93f2f0c8 Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 17:26:17 +0200 Subject: [PATCH 4/7] fix(forward-email): reject unknown keys in the forward_email block and its defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A misspelled `defualts:` (or `defaults: {setings: ...}`) was silently ignored, so the package defaults were enforced instead of the operator's override — e.g. a declared `retention_days: 0` became a PUT of 30. The per-domain file already rejected unknown top-level keys; the config block and its `defaults:` sub-block now do the same, through the existing `_check_keys`. Also documents the CLI exit codes in the module docstring (0 clean, 1 any per-domain error or finding, 2 an invalid invocation); the split was only implicit in the tests. Round-2 Codex lens on #1, full-scope confirm: one blocking finding fixed (this), one rejected (per-domain config errors keep rc 1 — nothing documents rc 2 for them and the suite asserts 1). --- src/octodns_gitops/cli/forward_email.py | 4 ++++ src/octodns_gitops/forward_email/config.py | 8 ++++++++ tests/forward_email/test_config.py | 15 +++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index 1e74d25..18f2052 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -10,6 +10,10 @@ plan / apply diff desired state against the account (default) --export write `/.yaml` from live state (bootstrap / re-baseline) --drift compare FE's generated DNS records and read-only expectations with the repo + +Exit codes: 0 nothing wrong; 1 a finding, a refused prune, or any per-domain error (a bad +per-domain file included — the other domains still run); 2 the invocation itself is invalid +(the `forward_email:` block, a missing token, an unclaimed `--domain`). """ from __future__ import annotations diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index 4ce1a73..d588822 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -159,6 +159,11 @@ DEFAULT_DIRECTORY = "mail/forward-email" DEFAULT_TOKEN_ENV = "FORWARD_EMAIL_API_TOKEN" +# Keys of the `forward_email:` block and of its `defaults:` sub-block. Checked like every other +# mapping here: an unknown key is an error, never something silently ignored. +BLOCK_FIELDS: frozenset[str] = frozenset({"token", "directory", "domains", "defaults"}) +DEFAULTS_FIELDS: frozenset[str] = frozenset({"settings", "expect", "alias"}) + class ForwardEmailConfigError(ValueError): """Raised when the block or a domain file is invalid.""" @@ -273,6 +278,8 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: raise ForwardEmailConfigError( "forward_email: expected a non-empty mapping (remove the key entirely to opt out)" ) + # A misspelled key (`defualts:`) must not silently fall back to the package defaults. + _check_keys("forward_email", block, BLOCK_FIELDS) token = block.get("token", f"env/{DEFAULT_TOKEN_ENV}") if not isinstance(token, str) or not token.startswith("env/") or len(token) <= 4: @@ -299,6 +306,7 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: domains.append(n) defaults = _section("forward_email.defaults", block, "defaults") + _check_keys("forward_email.defaults", defaults, DEFAULTS_FIELDS) settings_over = _section("forward_email.defaults.settings", defaults, "settings") expect_over = _section("forward_email.defaults.expect", defaults, "expect") alias_over = _section("forward_email.defaults.alias", defaults, "alias") diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index 42b5706..0719c59 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -133,6 +133,21 @@ def test_unknown_setting_in_defaults_rejected(self, tmp_path): with pytest.raises(ForwardEmailConfigError, match="has_strict_dmarc"): load_forward_email(str(cfg)) + @pytest.mark.parametrize( + "block, needle", + [ + ("defualts:\n settings:\n retention_days: 0\n", "defualts"), + ("defaults:\n setings:\n retention_days: 0\n", "setings"), + ("tokn: env/X\n", "tokn"), + ], + ) + def test_unknown_keys_in_the_block_are_rejected_not_ignored(self, tmp_path, block, needle): + # A misspelled `defaults` would silently enforce the package defaults instead of the + # operator's override — the same present-but-wrong class as an empty block. + cfg = _write(tmp_path, "config.yaml", f"forward_email:\n domains: [x.be]\n {block}") + with pytest.raises(ForwardEmailConfigError, match=needle): + load_forward_email(str(cfg)) + class TestTypeValidation: @pytest.mark.parametrize( From ec06620126654634ab2181203bd618c2eb93c775 Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 17:38:18 +0200 Subject: [PATCH 5/7] fix(forward-email): strict responder schema, per-domain zone dir, exact MX, explicit aliases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four review threads on the round-1 push (GitHub Codex review at d473257): - vacation_responder was only checked as a mapping, so `is_enabled: "false"` (a truthy string) enabled the responder on the API. The nested mapping now admits exactly Forward Email's three fields (is_enabled required and strictly bool, subject, message); export writes only those keys and the reconciler compares only those keys, so the three stay consistent and an extra live key is neither written nor a perpetual diff. - --drift resolved the zone directory as "the first YamlProvider" globally; a domain sourced from a second one was checked in the wrong directory and reported "no zone file; not checked" with rc 0. ZoneLookup resolves per domain from zones..sources (or "*"), falls back to the only YamlProvider, and with several and no naming entry reports an explicit "ambiguous" finding (rc 1) instead of silence. - The MX check only required the two FE hosts to appear. It now requires both at exactly one shared integer preference — every entry's preference is kept, so a duplicate host at another preference, a missing preference or a malformed entry is reported — and no other exchanger at all (lower preference routes mail away, higher is a backup FE does not know about); ignore_mx_check remains the opt-out for split routing. Legacy octoDNS `value`/`priority` spellings are accepted. - A missing or null `aliases:` loaded as [], so --prune would have deleted every non-mailbox alias of a domain whose file merely forgot the key. It is now an error that names `aliases: []` as the explicit form; export already writes that. Same class, same fix: an alias without `recipients:` no longer reads as [] (which would PUT no recipients), and `domains:` null in the block is covered by the existing non-empty check. Verify: 423 passed (396 before; 27 tests added, 1 renamed). --- README.md | 11 ++- src/octodns_gitops/cli/forward_email.py | 72 +++++++++++--- src/octodns_gitops/forward_email/config.py | 29 +++++- src/octodns_gitops/forward_email/drift.py | 51 +++++++++- src/octodns_gitops/forward_email/export.py | 8 +- src/octodns_gitops/forward_email/reconcile.py | 12 ++- tests/cli/test_forward_email.py | 93 ++++++++++++++----- tests/forward_email/test_config.py | 54 ++++++++++- tests/forward_email/test_drift.py | 77 +++++++++++++++ tests/forward_email/test_export.py | 18 +++- tests/forward_email/test_reconcile.py | 30 ++++++ 11 files changed, 402 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index be9a2b9..8c536bb 100644 --- a/README.md +++ b/README.md @@ -98,8 +98,15 @@ Contract: web-UI change). A freshly exported file must plan as **zero changes**. Write-only settings already declared in the file being overwritten are preserved, since the API cannot return them. - `make mail-drift` compares FE's generated DNS records (DKIM key, `fe-bounces` CNAME, verification - TXT, the DMARC `rua` address, MX unless `ignore_mx_check`) with the repo's zone file, and reports - read-only expectation mismatches. Exit 1 on any finding. + TXT, the DMARC `rua` address) with the repo's zone file, and reports read-only expectation + mismatches. Unless `ignore_mx_check: true`, the apex MX must be exactly FE's two exchangers at + one shared preference — any other exchanger is a finding. The zone file is looked up in the + YamlProvider the zone's `sources:` names; with several YamlProviders and no such entry the + domain is reported as ambiguous rather than unchecked. Exit 1 on any finding. +- `aliases:` is always an explicit list (`aliases: []` for a domain with none) and every alias + declares `recipients:`; an absent key is an error, never "empty" — with `PRUNE=1` that would + have meant "delete everything". `vacation_responder` takes exactly `is_enabled` (bool, + required), `subject` and `message`. - `max_quota_per_alias` and `bounce_webhook` cannot be read back from the API: they are sent with every domain update but never produce a diff on their own. diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index 18f2052..7001f97 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -21,6 +21,7 @@ import argparse import os import sys +from dataclasses import dataclass from pathlib import Path from typing import TextIO @@ -39,16 +40,57 @@ from octodns_gitops.forward_email.reconcile import DomainPlan, plan_domain -def zone_directory(config_path: str) -> Path | None: - """The YamlProvider's `directory`, resolved relative to config.yaml.""" +class AmbiguousZoneDirectory(ValueError): + """Several YamlProviders and nothing saying which one holds this domain's zone file.""" + + +@dataclass(frozen=True) +class ZoneLookup: + """Where each domain's octoDNS zone file lives, from `providers:` and `zones:` in config.yaml. + + Resolved per domain: with several YamlProviders, "the first one" would check a directory the + domain is not sourced from and report the file as merely absent (rc 0). + """ + + yaml_dirs: dict[str, Path] # YamlProvider name -> directory (absolute) + sources: dict[str, list[str]] # bare zone name (or "*") -> its `sources:` provider names + + @classmethod + def single(cls, directory: Path) -> ZoneLookup: + return cls({"zones": directory}, {}) + + def directory(self, domain: str) -> Path | None: + """The zone directory for `domain`; None when it has no zone file in this repo.""" + named = self.sources.get(domain, self.sources.get("*")) + if named is not None: + yaml_named = [p for p in named if p in self.yaml_dirs] + return self.yaml_dirs[yaml_named[0]] if yaml_named else None + if len(self.yaml_dirs) <= 1: + return next(iter(self.yaml_dirs.values()), None) + raise AmbiguousZoneDirectory( + f"ambiguous: {len(self.yaml_dirs)} YamlProviders ({', '.join(sorted(self.yaml_dirs))}) and " + f"zones.{domain}.sources does not name one" + ) + + +def zone_lookup(config_path: str) -> ZoneLookup: + """Parse the octoDNS `providers:`/`zones:` blocks; directories resolve relative to config.yaml.""" cfg_file = Path(config_path) with open(cfg_file) as f: cfg = yaml.safe_load(f) or {} - for prov in (cfg.get("providers") or {}).values(): + base = cfg_file.resolve().parent + yaml_dirs: dict[str, Path] = {} + providers = cfg.get("providers") + for name, prov in (providers.items() if isinstance(providers, dict) else ()): if isinstance(prov, dict) and str(prov.get("class", "")).endswith("YamlProvider"): d = Path(prov.get("directory", "./zones")) - return d if d.is_absolute() else cfg_file.resolve().parent / d - return None + yaml_dirs[str(name)] = d if d.is_absolute() else base / d + sources: dict[str, list[str]] = {} + zones = cfg.get("zones") + for zone, spec in (zones.items() if isinstance(zones, dict) else ()): + if isinstance(spec, dict) and isinstance(spec.get("sources"), list): + sources[str(zone).rstrip(".").lower()] = [str(s) for s in spec["sources"]] + return ZoneLookup(yaml_dirs, sources) def _print_plan(plan: DomainPlan, out: TextIO) -> None: @@ -146,7 +188,7 @@ def run( doit: bool, prune: bool, mode: str, - zone_dir: Path | None, + zones: ZoneLookup | None, out: TextIO, ) -> int: scope = list(cfg.domains) @@ -191,10 +233,18 @@ def run( findings = [] plan = plan_domain(desired, cfg, live, [], prune=False) findings += [(m.field, f"{m.field} is {m.live!r}, expected {m.desired!r}") for m in plan.expect_mismatch] - zone_file = (zone_dir / f"{domain}.yaml") if zone_dir else None - if zone_file is None or not zone_file.exists(): - out.write(f"{domain:<28} no zone file in this repo; DNS records not checked\n") + zone_file = None + try: + zone_dir = zones.directory(domain) if zones else None + except AmbiguousZoneDirectory as e: + # A finding, not "not checked": rc 0 here would hide a never-compared zone file. + findings.append(("zone", f"{e}; DNS records not compared")) else: + zone_file = zone_dir / f"{domain}.yaml" if zone_dir else None + if zone_file is None or not zone_file.exists(): + zone_file = None + out.write(f"{domain:<28} no zone file in this repo; DNS records not checked\n") + if zone_file is not None: with open(zone_file) as f: zone = yaml.safe_load(f) or {} settings = {**cfg.settings, **desired.settings} @@ -204,7 +254,7 @@ def run( rc = 1 out.write(f"{domain:<28} {len(findings)} finding(s)\n") out.writelines(f" {field}: {msg}\n" for field, msg in findings) - elif zone_file is not None and zone_file.exists(): + elif zone_file is not None: out.write(f"{domain:<28} clean\n") continue @@ -261,7 +311,7 @@ def main() -> int: doit=args.doit and mode == "plan", prune=args.prune, mode=mode, - zone_dir=zone_directory(args.config) if mode == "drift" else None, + zones=zone_lookup(args.config) if mode == "drift" else None, out=sys.stdout, ) diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index d588822..ee7eda2 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -110,6 +110,12 @@ "max_quota": str, "vacation_responder": dict, } +# The responder mapping is exactly Forward Email's model (`aliases.js`): nothing else is admitted, +# in the file or on export, and the reconciler compares only these keys. `is_enabled` is +# required — a mapping without it would be an enabled-looking block that never fires. +VACATION_RESPONDER_KEYS: tuple[str, ...] = ("is_enabled", "subject", "message") +VACATION_RESPONDER_FIELDS: frozenset[str] = frozenset(VACATION_RESPONDER_KEYS) +VACATION_RESPONDER_TYPES: dict[str, type] = {"is_enabled": bool, "subject": str, "message": str} # Alias fields a repo may default. Per-alias-only fields (quota, key, responder) are excluded: # a default there would silently be ignored by the reconciler. ALIAS_DEFAULTABLE: frozenset[str] = frozenset( @@ -246,6 +252,15 @@ def _check_alias_keys(where: str, given: dict, allowed: frozenset[str]) -> None: _check_keys(where, given, allowed) +def _check_vacation_responder(where: str, given: dict) -> None: + """Strict nested schema: `vacation_responder: dict` alone let `is_enabled: "false"` through, + and a truthy string enables the responder on the API.""" + _check_keys(where, given, VACATION_RESPONDER_FIELDS) + if "is_enabled" not in given: + raise ForwardEmailConfigError(f"{where}: is_enabled (bool) is required") + _check_types(where, given, VACATION_RESPONDER_TYPES) + + def _check_types(where: str, given: dict, types: dict) -> None: for k, v in given.items(): want = types.get(k) @@ -328,8 +343,6 @@ def load_forward_email(config_path: str) -> ForwardEmailConfig | None: def _as_list(where: str, value) -> list[str]: - if value is None: - return [] if isinstance(value, str): return [value] if isinstance(value, list) and all(isinstance(v, str) for v in value): @@ -354,9 +367,12 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: _check_types(f"{path}: settings", settings, SETTINGS_TYPES) _check_types(f"{path}: expect", expect, EXPECT_TYPES) + # Absent or null must never read as "no aliases": with --prune that is "delete them all". raw_aliases = data.get("aliases") if raw_aliases is None: - raw_aliases = [] + raise ForwardEmailConfigError( + f"{path}: aliases must be an explicit list; write `aliases: []` for a domain with none" + ) if not isinstance(raw_aliases, list): raise ForwardEmailConfigError(f"{path}: aliases must be a list") @@ -372,10 +388,15 @@ def load_domain_file(path: Path, domain: str) -> DesiredDomain: if name in seen: raise ForwardEmailConfigError(f"{path}: duplicate alias {name!r}") seen.add(name) + # Same class as `aliases:` above: an absent key read as `[]` would PUT no recipients. + if "recipients" not in raw: + raise ForwardEmailConfigError(f"{where}: recipients is required (`recipients: []` only for a mailbox)") + if "vacation_responder" in raw: + _check_vacation_responder(f"{where}: vacation_responder", raw["vacation_responder"]) aliases.append( DesiredAlias( name=name, - recipients=_as_list(f"{where}: recipients", raw.get("recipients")), + recipients=_as_list(f"{where}: recipients", raw["recipients"]), description=raw.get("description"), is_enabled=raw.get("is_enabled"), error_code_if_disabled=raw.get("error_code_if_disabled"), diff --git a/src/octodns_gitops/forward_email/drift.py b/src/octodns_gitops/forward_email/drift.py index 5f78197..ed7e749 100644 --- a/src/octodns_gitops/forward_email/drift.py +++ b/src/octodns_gitops/forward_email/drift.py @@ -5,6 +5,11 @@ DMARC is special: FE suggests `p=reject`, the repo publishes its own ramped policy — only the FE `rua` address must be present. `has_strict_dmarc` is derived by FE from what it sees in DNS, so the expectation is derived from the zone file's own `p=` value. + +MX (unless the domain sets `ignore_mx_check`): FE documents itself as the domain's only mail +exchanger, so the apex must list exactly `mx1`/`mx2.forwardemail.net` at one shared preference. +Any other exchanger is a finding — a lower preference routes mail away from FE, a higher one is a +backup FE knows nothing about; split routing opts out with `ignore_mx_check`. """ from __future__ import annotations @@ -124,8 +129,48 @@ def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftF ) if expect_mx: - got = {v["exchange"].rstrip(".").lower() for v in _values(zone, "", "MX") if isinstance(v, dict)} - if not FE_MX <= got: - findings.append(DriftFinding("mx", f"apex MX {sorted(got) or 'missing'} does not include {sorted(FE_MX)}")) + findings.extend(_check_mx(_values(zone, "", "MX"))) return findings + + +def _check_mx(values: list) -> list[DriftFinding]: + """octoDNS accepts `exchange`/`preference` and the legacy `value`/`priority` spellings. + + Every preference of every entry is kept (a host may be listed twice), so the FE pair must + resolve to exactly one integer preference across all of its entries. An entry that is not an + exchange mapping is reported, never skipped: "exactly FE" cannot be claimed over it. + """ + prefs: dict[str, set] = {} + malformed = [] + for v in values: + host = str(v.get("exchange", v.get("value", ""))).rstrip(".").lower() if isinstance(v, dict) else "" + if not host: + malformed.append(v) + continue + prefs.setdefault(host, set()).add(v.get("preference", v.get("priority"))) + out = [] + if malformed: + out.append(DriftFinding("mx", f"apex MX has malformed value(s) {malformed!r}; expected exchange/preference mappings")) + if not FE_MX <= set(prefs): + out.append(DriftFinding("mx", f"apex MX {sorted(prefs) or 'missing'} does not include {sorted(FE_MX)}")) + return out + fe_prefs = set().union(*(prefs[h] for h in FE_MX)) + if len(fe_prefs) != 1 or not all(isinstance(p, int) and not isinstance(p, bool) for p in fe_prefs): + out.append( + DriftFinding( + "mx", + f"apex MX preferences for the FE exchangers are {sorted(map(str, fe_prefs))}; " + "both must share exactly one integer preference", + ) + ) + others = sorted(set(prefs) - FE_MX) + if others: + out.append( + DriftFinding( + "mx", + f"apex MX also lists {others}; Forward Email must be the only exchanger " + "(set ignore_mx_check: true for deliberate split routing)", + ) + ) + return out diff --git a/src/octodns_gitops/forward_email/export.py b/src/octodns_gitops/forward_email/export.py index 13d4598..24b7314 100644 --- a/src/octodns_gitops/forward_email/export.py +++ b/src/octodns_gitops/forward_email/export.py @@ -13,6 +13,7 @@ from .config import ( EXPECT_FIELDS, SETTINGS_FIELDS, + VACATION_RESPONDER_KEYS, WRITE_ONLY_SETTINGS, ForwardEmailConfig, ) @@ -77,11 +78,10 @@ def _alias_lines(live: dict, defaults: dict, domain_quota: int) -> list[str]: out.append(f"{ind}max_quota: {human_quota(int(live['max_quota']))}") vac = live.get("vacation_responder") if _vacation_enabled(vac): - # Every live key, or the reconciler (which compares the whole mapping) plans an update. + # Only the schema keys: the loader rejects anything else, and the reconciler compares + # exactly these, so an extra live key is neither written nor a diff. out.append(f"{ind}vacation_responder:") - known = ("is_enabled", "subject", "message") - keys = [k for k in known if k in vac] + sorted(k for k in vac if k not in known) - out.extend(f"{ind} {k}: {_scalar(vac[k])}" for k in keys) + out.extend(f"{ind} {k}: {_scalar(vac[k])}" for k in VACATION_RESPONDER_KEYS if k in vac) return out diff --git a/src/octodns_gitops/forward_email/reconcile.py b/src/octodns_gitops/forward_email/reconcile.py index 4baeccf..73c94d7 100644 --- a/src/octodns_gitops/forward_email/reconcile.py +++ b/src/octodns_gitops/forward_email/reconcile.py @@ -23,6 +23,7 @@ from .config import ( EXPECT_FIELDS, SETTINGS_FIELDS, + VACATION_RESPONDER_KEYS, WRITE_ONLY_SETTINGS, DesiredAlias, DesiredDomain, @@ -108,6 +109,12 @@ def _vacation_enabled(v) -> bool: return bool(v) and bool(v.get("is_enabled")) +def _vacation_view(v) -> dict: + """The schema keys of a responder mapping — the loader admits nothing else, so a live key + outside them must not read as a diff.""" + return {k: v[k] for k in VACATION_RESPONDER_KEYS if k in v} if isinstance(v, dict) else {} + + def _alias_body(resolved: dict) -> dict: """Write body: name/recipients plus every resolved flag, explicitly. @@ -153,8 +160,9 @@ def _diff_alias(resolved: dict, live: dict, defaults: dict, domain_quota: int) - body["max_quota"] = resolved["max_quota"] or "" want_vac = resolved["vacation_responder"] - if _vacation_enabled(want_vac) != _vacation_enabled(live.get("vacation_responder")) or ( - _vacation_enabled(want_vac) and want_vac != live.get("vacation_responder") + live_vac = live.get("vacation_responder") + if _vacation_enabled(want_vac) != _vacation_enabled(live_vac) or ( + _vacation_enabled(want_vac) and _vacation_view(want_vac) != _vacation_view(live_vac) ): changes.append("vacation_responder") body["vacation_responder"] = want_vac or {"is_enabled": False} diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py index 6425772..e736fe6 100644 --- a/tests/cli/test_forward_email.py +++ b/tests/cli/test_forward_email.py @@ -3,9 +3,16 @@ import copy import io import textwrap +from pathlib import Path import pytest -from octodns_gitops.cli.forward_email import main, run, zone_directory +from octodns_gitops.cli.forward_email import ( + AmbiguousZoneDirectory, + ZoneLookup, + main, + run, + zone_lookup, +) from octodns_gitops.forward_email.config import ( DEFAULT_ALIAS, DEFAULT_EXPECT, @@ -119,7 +126,7 @@ def _run(cfg, client, **kw): kw.setdefault("doit", False) kw.setdefault("prune", False) kw.setdefault("mode", "plan") - kw.setdefault("zone_dir", None) + kw.setdefault("zones", None) rc = run(cfg, client, out=out, **kw) return rc, out.getvalue() @@ -343,27 +350,27 @@ def _zones(self, tmp_path, text=None): zd = tmp_path / "zones" zd.mkdir() (zd / "x.be.yaml").write_text(text or self.ZONE) - return zd + return ZoneLookup.single(zd) def test_clean_zone_and_matching_expectations_exit_0(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be")], {"x.be": []}) - rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=self._zones(tmp_path)) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=self._zones(tmp_path)) assert rc == 0 assert "clean" in out def test_stale_dkim_in_zone_file_is_reported(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be")], {"x.be": []}) - zd = self._zones(tmp_path, self.ZONE.replace("p=MIIBIjANBg", "p=OLD")) - rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=zd) + zones = self._zones(tmp_path, self.ZONE.replace("p=MIIBIjANBg", "p=OLD")) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=zones) assert rc == 1 assert "dkim" in out def test_expectation_mismatch_is_drift(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be", has_smtp=False)], {"x.be": []}) - rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=self._zones(tmp_path)) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=self._zones(tmp_path)) assert rc == 1 assert "has_smtp" in out @@ -372,27 +379,69 @@ def test_domain_without_zone_file_is_informational(self, tmp_path): client = FakeClient([_live_domain("x.be")], {"x.be": []}) zd = tmp_path / "zones" zd.mkdir() - rc, out = _run(_cfg(tmp_path), client, mode="drift", zone_dir=zd) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=ZoneLookup.single(zd)) assert rc == 0 assert "no zone file" in out + def test_ambiguous_zone_directory_is_a_finding_not_unchecked(self, tmp_path): + # Two YamlProviders and nothing naming which one holds x.be: silently checking the + # first (or none) would report rc 0 for a zone file that was never compared. + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + zones = ZoneLookup({"a": tmp_path / "a", "b": tmp_path / "b"}, {}) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=zones) + assert rc == 1 + assert "ambiguous" in out and "2 YamlProviders" in out and "zones.x.be.sources" in out + assert "not checked" not in out.split("ambiguous")[0] + class TestConfigPlumbing: - def test_zone_directory_comes_from_the_yaml_provider(self, tmp_path): + CONFIG = textwrap.dedent( + """ + providers: + zones: + class: octodns.provider.yaml.YamlProvider + directory: ./zones + legacy: + class: octodns.provider.yaml.YamlProvider + directory: /abs/legacy + other: + class: octodns_hetzner.HetznerProvider + zones: + x.be.: + sources: [zones] + targets: [other] + old.be.: + sources: [legacy] + cloud.be.: + sources: [other] + """ + ) + + def test_zone_directory_is_resolved_per_domain_from_the_zone_sources(self, tmp_path): cfg = tmp_path / "config.yaml" - cfg.write_text( - textwrap.dedent( - """ - providers: - zones: - class: octodns.provider.yaml.YamlProvider - directory: ./zones - other: - class: octodns_hetzner.HetznerProvider - """ - ) - ) - assert zone_directory(str(cfg)) == tmp_path / "zones" + cfg.write_text(self.CONFIG) + zones = zone_lookup(str(cfg)) + assert zones.directory("x.be") == tmp_path / "zones" + assert zones.directory("old.be") == Path("/abs/legacy") + # sourced from a non-YAML provider only: there is no zone file to compare + assert zones.directory("cloud.be") is None + + def test_zone_directory_falls_back_to_the_only_yaml_provider(self, tmp_path): + cfg = tmp_path / "config.yaml" + cfg.write_text("providers:\n zones:\n class: octodns.provider.yaml.YamlProvider\n directory: ./zones\n") + assert zone_lookup(str(cfg)).directory("anything.be") == tmp_path / "zones" + cfg.write_text("providers:\n other:\n class: octodns_hetzner.HetznerProvider\n") + assert zone_lookup(str(cfg)).directory("anything.be") is None + + def test_zone_directory_with_several_yaml_providers_and_no_source_is_ambiguous(self, tmp_path): + cfg = tmp_path / "config.yaml" + cfg.write_text(self.CONFIG) + with pytest.raises(AmbiguousZoneDirectory, match="2 YamlProviders"): + zone_lookup(str(cfg)).directory("unlisted.be") + # a wildcard zone entry names the source for every unlisted zone + cfg.write_text(self.CONFIG + " '*':\n sources: [legacy]\n") + assert zone_lookup(str(cfg)).directory("unlisted.be") == Path("/abs/legacy") def test_main_without_opt_in_block_is_a_noop(self, tmp_path, monkeypatch, capsys): cfg = tmp_path / "config.yaml" diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index 0719c59..a40f0aa 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -109,8 +109,10 @@ def test_token_must_be_env_ref(self, tmp_path): with pytest.raises(ForwardEmailConfigError, match="env/"): load_forward_email(str(cfg)) - def test_domains_required_and_normalized(self, tmp_path): - cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: []\n") + @pytest.mark.parametrize("domains", ["domains: []\n", "domains:\n", "token: env/X\n"]) + def test_domains_required_and_normalized(self, tmp_path, domains): + # Empty, null and absent are all errors: the list is the ownership boundary. + cfg = _write(tmp_path, "config.yaml", f"forward_email:\n {domains}") with pytest.raises(ForwardEmailConfigError, match="domains"): load_forward_email(str(cfg)) cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [Autops.BE., autops.be]\n") @@ -325,3 +327,51 @@ def test_unknown_alias_key_rejected(self, tmp_path): ) with pytest.raises(ForwardEmailConfigError, match="storage_used"): load_domain_file(p, "x.be") + + @pytest.mark.parametrize("body", ["settings:\n retention_days: 0\n", "aliases:\n", "aliases: null\n"]) + def test_aliases_must_be_an_explicit_list(self, tmp_path, body): + # Absent or null used to load as `[]`, so `--prune` would delete every non-mailbox alias + # of a domain whose file merely forgot the key. + p = _write(tmp_path, "x.be.yaml", body) + with pytest.raises(ForwardEmailConfigError, match=r"aliases: \[\]"): + load_domain_file(p, "x.be") + assert load_domain_file(_write(tmp_path, "y.be.yaml", "aliases: []\n"), "y.be").aliases == [] + + def test_alias_recipients_must_be_explicit(self, tmp_path): + # Same class: an absent key read as `[]` would PUT `recipients: []` and stop forwarding. + p = _write(tmp_path, "x.be.yaml", "aliases:\n - {name: a}\n") + with pytest.raises(ForwardEmailConfigError, match=r"recipients"): + load_domain_file(p, "x.be") + + @pytest.mark.parametrize( + ("responder", "needle"), + [ + ("{is_enabled: 'false', subject: away}", "is_enabled"), # truthy string enabled it + ("{subject: away, message: back}", "is_enabled"), # required + ("{is_enabled: true, subject: away, end_date: '2026-09-01'}", "end_date"), + ("{is_enabled: true, subject: 1}", "subject"), + ("{}", "is_enabled"), + ], + ) + def test_vacation_responder_is_validated_against_the_fe_schema(self, tmp_path, responder, needle): + p = _write(tmp_path, "x.be.yaml", f"aliases:\n - {{name: a, recipients: [x@y.z], vacation_responder: {responder}}}\n") + with pytest.raises(ForwardEmailConfigError, match=needle): + load_domain_file(p, "x.be") + + def test_vacation_responder_accepts_the_three_fe_fields(self, tmp_path): + p = _write( + tmp_path, + "x.be.yaml", + """ + aliases: + - name: a + recipients: [x@y.z] + vacation_responder: {is_enabled: true, subject: away, message: back soon} + - name: b + recipients: [x@y.z] + vacation_responder: {is_enabled: false} + """, + ) + d = load_domain_file(p, "x.be") + assert d.aliases[0].vacation_responder == {"is_enabled": True, "subject": "away", "message": "back soon"} + assert d.aliases[1].vacation_responder == {"is_enabled": False} diff --git a/tests/forward_email/test_drift.py b/tests/forward_email/test_drift.py index a26d31b..38455f2 100644 --- a/tests/forward_email/test_drift.py +++ b/tests/forward_email/test_drift.py @@ -131,3 +131,80 @@ def test_mx_checked_unless_domain_ignores_it(self): z[""][1]["values"] = [{"exchange": "aspmx.l.google.com.", "preference": 1}] assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["mx"] assert check_zone(LIVE, z, expect_mx=False) == [] + + @pytest.mark.parametrize( + ("values", "needle"), + [ + # FE present, but a lower-preference exchanger routes mail elsewhere first. + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + {"exchange": "aspmx.l.google.com.", "preference": 1}, + ], + "aspmx.l.google.com", + ), + # A higher-preference extra is a backup FE does not know about: still a finding. + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + {"exchange": "backup.example.org.", "preference": 20}, + ], + "backup.example.org", + ), + # Both FE hosts present at different preferences. + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 20}, + ], + "preference", + ), + # Only one FE host. + ([{"exchange": "mx1.forwardemail.net.", "preference": 10}], "mx2.forwardemail.net"), + # Both FE hosts without any preference: "shared" None is not a valid preference. + ([{"exchange": "mx1.forwardemail.net."}, {"exchange": "mx2.forwardemail.net."}], "preference"), + # A duplicate FE entry at another preference must not be hidden by the later one. + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 20}, + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + ], + "preference", + ), + # An entry that is not an exchange/preference mapping is not "no exchanger". + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + "mx3.example.org.", + ], + "malformed", + ), + ( + [ + {"exchange": "mx1.forwardemail.net.", "preference": 10}, + {"exchange": "mx2.forwardemail.net.", "preference": 10}, + {"preference": 5}, + ], + "malformed", + ), + ], + ) + def test_mx_requires_exactly_fe_at_one_shared_preference(self, values, needle): + z = _zone() + z[""][1]["values"] = values + findings = check_zone(LIVE, z, expect_mx=True) + assert _fields(findings) == ["mx"], findings + assert needle in findings[0].message + assert check_zone(LIVE, z, expect_mx=False) == [] + + def test_mx_accepts_octodns_legacy_priority_value_keys(self): + z = _zone() + z[""][1]["values"] = [ + {"value": "MX1.forwardemail.net.", "priority": 10}, + {"value": "mx2.forwardemail.net", "priority": 10}, + ] + assert check_zone(LIVE, z, expect_mx=True) == [] diff --git a/tests/forward_email/test_export.py b/tests/forward_email/test_export.py index 6c74df2..5038123 100644 --- a/tests/forward_email/test_export.py +++ b/tests/forward_email/test_export.py @@ -134,18 +134,30 @@ def test_blank_live_description_under_a_non_empty_default_is_written_explicitly( plan = plan_domain(load_domain_file(p, "x.be"), cfg, _live_domain(), live_aliases, prune=True) assert plan.is_empty(), plan.aliases - def test_every_vacation_responder_key_is_exported(self, tmp_path): + def test_vacation_responder_exports_only_the_fe_schema_keys(self, tmp_path): + # The loader accepts exactly is_enabled/subject/message; an exported extra key would make + # the file unloadable, and the reconciler compares the same three keys, so dropping it is + # still a zero diff. vac = {"is_enabled": True, "subject": "away", "message": "back", "end_date": "2026-09-01", "extra": {"k": 1}} live_aliases = [_live_alias("a", vacation_responder=dict(vac))] text = export_domain(_cfg(), _live_domain(), live_aliases) assert "vacation_responder:\n is_enabled: true\n subject: away\n message: back\n" in text - assert "end_date: '2026-09-01'" in text + assert "end_date" not in text and "extra" not in text p = tmp_path / "x.be.yaml" p.write_text(text) desired = load_domain_file(p, "x.be") - assert desired.aliases[0].vacation_responder == vac + assert desired.aliases[0].vacation_responder == {"is_enabled": True, "subject": "away", "message": "back"} assert plan_domain(desired, _cfg(), _live_domain(), live_aliases, prune=True).is_empty() + def test_domain_without_aliases_round_trips_through_an_explicit_empty_list(self, tmp_path): + # The loader refuses an absent `aliases:` (it would read as "prune everything"), so the + # export must write the empty list out. + text = export_domain(_cfg(), _live_domain(), []) + assert text == "domain: x.be\naliases: []\n" + p = tmp_path / "x.be.yaml" + p.write_text(text) + assert load_domain_file(p, "x.be").aliases == [] + def test_alias_quotas_are_compared_against_the_preserved_per_domain_default(self, tmp_path): # A preserved `max_quota_per_alias: 10 GB` is what the reloaded file resolves aliases against; # comparing exports against the repo default instead turned a live 1 GiB alias into a reset. diff --git a/tests/forward_email/test_reconcile.py b/tests/forward_email/test_reconcile.py index 10e4c71..f75d4a3 100644 --- a/tests/forward_email/test_reconcile.py +++ b/tests/forward_email/test_reconcile.py @@ -195,6 +195,36 @@ def test_disabled_alias_uses_repo_default_error_code(self): assert chg.body["error_code_if_disabled"] == 250 +class TestVacationResponder: + def test_live_keys_outside_the_fe_schema_do_not_produce_a_diff(self): + # The loader only admits is_enabled/subject/message, so comparing the whole live mapping + # would plan an update forever if FE ever returned an extra key. + want = {"is_enabled": True, "subject": "away", "message": "back"} + live = _live_alias("a", vacation_responder={**want, "end_date": "2026-09-01"}) + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"], vacation_responder=want)]), + _cfg(), + _live_domain(), + [live], + prune=True, + ) + assert plan.is_empty(), plan.aliases + + def test_changed_message_is_an_update_carrying_the_desired_mapping(self): + want = {"is_enabled": True, "subject": "away", "message": "new"} + live = _live_alias("a", vacation_responder={"is_enabled": True, "subject": "away", "message": "old"}) + plan = plan_domain( + _desired([DesiredAlias("a", ["serge@ginsys.eu"], vacation_responder=want)]), + _cfg(), + _live_domain(), + [live], + prune=True, + ) + (chg,) = plan.aliases + assert chg.changes == ["vacation_responder"] + assert chg.body["vacation_responder"] == want + + class TestQuota: def test_absent_live_quota_means_domain_default(self): plan = plan_domain( From 2072407243cc83993f816976f30cc6940d07d9cc Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 18:09:05 +0200 Subject: [PATCH 6/7] fix(forward-email): guard mailbox updates and no-target aliases, reject duplicate YAML keys, merge zone sources - reconcile: refuse an update that would turn IMAP off on a live mailbox only because the file omits `has_imap` (an explicit `has_imap: false` is intent); refuse an alias with no recipients and no mailbox; the prune error now says "add it to git with `has_imap: true`" - config: reject duplicate YAML mapping keys (PyYAML kept the last block silently; with --prune that deleted the first block's aliases); used for config.yaml, the per-domain files, the export-preserve read and zone files - drift: read and merge every YamlProvider a zone's `sources:` names; compare the return-path CNAME and record names case-insensitively - cli: `--prune` with `--export`/`--drift` is a usage error (rc 2); the exit code docstring scopes "a finding" to --drift - makefile: PRUNE=1 means the literal 1 (`$(filter 1,$(PRUNE))`); 0/false no longer prune - README: the mailbox remedy names `has_imap: true`; mail-drift proves nothing for a domain without a zone file; `recipients: []` only for a mailbox; duplicate keys are an error Addresses the code-reviewer termination pass (CR1, CR3-CR5) and the GitHub Codex threads H1-H5 posted at ec06620. --- README.md | 23 ++-- src/octodns_gitops/bootstrap/makefile.py | 4 +- src/octodns_gitops/cli/forward_email.py | 51 +++++---- src/octodns_gitops/forward_email/config.py | 31 +++++- src/octodns_gitops/forward_email/drift.py | 34 ++++-- src/octodns_gitops/forward_email/reconcile.py | 24 ++++- tests/bootstrap/test_makefile.py | 4 +- tests/cli/test_forward_email.py | 100 ++++++++++++++++-- tests/forward_email/test_config.py | 20 ++++ tests/forward_email/test_drift.py | 11 ++ tests/forward_email/test_reconcile.py | 88 +++++++++++++++ 11 files changed, 335 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 8c536bb..8f112f1 100644 --- a/README.md +++ b/README.md @@ -91,22 +91,29 @@ Contract: - `make mail-plan` is a dry run; `make mail-apply` writes. `DOMAIN=example.com` scopes either. - Domains are **never created or deleted** from git; a claimed domain missing from the account is an error. -- `PRUNE=1` deletes aliases absent from git, inside claimed domains only, after a second listing - agrees with the first. An alias with `has_imap: true` or stored mail is a mailbox: it is never - pruned and blocks the run until it is added to git or removed in the web UI. +- `PRUNE=1` (the literal `1`; `0`/`false` do not prune) deletes aliases absent from git, inside + claimed domains only, after a second listing agrees with the first. An alias with + `has_imap: true` or stored mail is a mailbox: it is never pruned and blocks the run until it is + added to git **with `has_imap: true`** or removed in the web UI. The same guard covers updates: + a declared alias that merely omits `has_imap` never turns IMAP off on a live mailbox — write + `has_imap: true` to keep it, or `has_imap: false` to turn it off deliberately. - `make mail-export` writes the files from live state (bootstrap, or re-baseline after a deliberate web-UI change). A freshly exported file must plan as **zero changes**. Write-only settings already declared in the file being overwritten are preserved, since the API cannot return them. - `make mail-drift` compares FE's generated DNS records (DKIM key, `fe-bounces` CNAME, verification TXT, the DMARC `rua` address) with the repo's zone file, and reports read-only expectation mismatches. Unless `ignore_mx_check: true`, the apex MX must be exactly FE's two exchangers at - one shared preference — any other exchanger is a finding. The zone file is looked up in the - YamlProvider the zone's `sources:` names; with several YamlProviders and no such entry the - domain is reported as ambiguous rather than unchecked. Exit 1 on any finding. + one shared preference — any other exchanger is a finding. The zone file is read from every + YamlProvider the zone's `sources:` names (merged, as octoDNS does); with several YamlProviders + and no such entry the domain is reported as ambiguous rather than unchecked. Exit 1 on any + finding. A claimed domain with no zone file in this repo is a supported layout, but + `mail-drift` then proves nothing about its DNS records: it prints "not checked" and exits 0. - `aliases:` is always an explicit list (`aliases: []` for a domain with none) and every alias declares `recipients:`; an absent key is an error, never "empty" — with `PRUNE=1` that would - have meant "delete everything". `vacation_responder` takes exactly `is_enabled` (bool, - required), `subject` and `message`. + have meant "delete everything". `recipients: []` is only valid for a mailbox (`has_imap` + resolving to true): an alias that would deliver nowhere is an error. A duplicated YAML key is an + error, never last-wins. `vacation_responder` takes exactly `is_enabled` (bool, required), + `subject` and `message`. - `max_quota_per_alias` and `bounce_webhook` cannot be read back from the API: they are sent with every domain update but never produce a diff on their own. diff --git a/src/octodns_gitops/bootstrap/makefile.py b/src/octodns_gitops/bootstrap/makefile.py index a74fad2..23a1127 100644 --- a/src/octodns_gitops/bootstrap/makefile.py +++ b/src/octodns_gitops/bootstrap/makefile.py @@ -146,7 +146,7 @@ # Forward Email - DRY-RUN diff of account settings and aliases (DOMAIN=, PRUNE=1) mail-plan: -\t@octodns-gitops-forwardemail --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(PRUNE),--prune,) +\t@octodns-gitops-forwardemail --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(filter 1,$(PRUNE)),--prune,) # Forward Email - APPLY settings and alias changes (never creates or deletes domains) mail-apply: @@ -155,7 +155,7 @@ \t@echo " APPLYING FORWARD EMAIL ACCOUNT CHANGES" \t@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" \t@echo "" -\t@octodns-gitops-forwardemail --doit --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(PRUNE),--prune,) +\t@octodns-gitops-forwardemail --doit --config config.yaml $(if $(DOMAIN),--domain $(DOMAIN),) $(if $(filter 1,$(PRUNE)),--prune,) # Forward Email - FE-generated DNS records and read-only expectations vs the repo mail-drift: diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index 7001f97..0e71806 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -11,9 +11,11 @@ --export write `/.yaml` from live state (bootstrap / re-baseline) --drift compare FE's generated DNS records and read-only expectations with the repo -Exit codes: 0 nothing wrong; 1 a finding, a refused prune, or any per-domain error (a bad -per-domain file included — the other domains still run); 2 the invocation itself is invalid -(the `forward_email:` block, a missing token, an unclaimed `--domain`). +Exit codes: 0 nothing wrong; 1 a drift finding (`--drift` only — plan/apply print `expect:` +mismatches but do not fail on them, they are read-only), a refused prune, a blocked alias, or any +per-domain error (a bad per-domain file included — the other domains still run); 2 the invocation +itself is invalid (the `forward_email:` block, a missing token, an unclaimed `--domain`, `--prune` +outside plan/apply). """ from __future__ import annotations @@ -25,8 +27,6 @@ from pathlib import Path from typing import TextIO -import yaml - from octodns_gitops.forward_email.api import ForwardEmailApiError, ForwardEmailClient from octodns_gitops.forward_email.config import ( WRITE_ONLY_SETTINGS, @@ -34,8 +34,9 @@ ForwardEmailConfigError, load_domain_file, load_forward_email, + load_yaml_strict, ) -from octodns_gitops.forward_email.drift import check_zone +from octodns_gitops.forward_email.drift import check_zone, merge_zones from octodns_gitops.forward_email.export import export_domain from octodns_gitops.forward_email.reconcile import DomainPlan, plan_domain @@ -59,14 +60,14 @@ class ZoneLookup: def single(cls, directory: Path) -> ZoneLookup: return cls({"zones": directory}, {}) - def directory(self, domain: str) -> Path | None: - """The zone directory for `domain`; None when it has no zone file in this repo.""" + def directories(self, domain: str) -> list[Path]: + """The zone directories for `domain`, in `sources:` order; empty when it has no zone file + in this repo. octoDNS merges every source, so drift must read every YAML one.""" named = self.sources.get(domain, self.sources.get("*")) if named is not None: - yaml_named = [p for p in named if p in self.yaml_dirs] - return self.yaml_dirs[yaml_named[0]] if yaml_named else None + return [self.yaml_dirs[p] for p in named if p in self.yaml_dirs] if len(self.yaml_dirs) <= 1: - return next(iter(self.yaml_dirs.values()), None) + return list(self.yaml_dirs.values()) raise AmbiguousZoneDirectory( f"ambiguous: {len(self.yaml_dirs)} YamlProviders ({', '.join(sorted(self.yaml_dirs))}) and " f"zones.{domain}.sources does not name one" @@ -77,7 +78,7 @@ def zone_lookup(config_path: str) -> ZoneLookup: """Parse the octoDNS `providers:`/`zones:` blocks; directories resolve relative to config.yaml.""" cfg_file = Path(config_path) with open(cfg_file) as f: - cfg = yaml.safe_load(f) or {} + cfg = load_yaml_strict(f) or {} base = cfg_file.resolve().parent yaml_dirs: dict[str, Path] = {} providers = cfg.get("providers") @@ -173,7 +174,7 @@ def _preserved_write_only(path: Path) -> dict: if not path.exists(): return {} with open(path) as f: - existing = yaml.safe_load(f) or {} + existing = load_yaml_strict(f) or {} settings = existing.get("settings") if isinstance(existing, dict) else None if not isinstance(settings, dict): return {} @@ -233,28 +234,29 @@ def run( findings = [] plan = plan_domain(desired, cfg, live, [], prune=False) findings += [(m.field, f"{m.field} is {m.live!r}, expected {m.desired!r}") for m in plan.expect_mismatch] - zone_file = None + zone_files: list[Path] = [] try: - zone_dir = zones.directory(domain) if zones else None + zone_dirs = zones.directories(domain) if zones else [] except AmbiguousZoneDirectory as e: # A finding, not "not checked": rc 0 here would hide a never-compared zone file. findings.append(("zone", f"{e}; DNS records not compared")) else: - zone_file = zone_dir / f"{domain}.yaml" if zone_dir else None - if zone_file is None or not zone_file.exists(): - zone_file = None + zone_files = [p for p in (d / f"{domain}.yaml" for d in zone_dirs) if p.exists()] + if not zone_files: out.write(f"{domain:<28} no zone file in this repo; DNS records not checked\n") - if zone_file is not None: - with open(zone_file) as f: - zone = yaml.safe_load(f) or {} + if zone_files: + parts = [] + for zone_file in zone_files: + with open(zone_file) as f: + parts.append(load_yaml_strict(f) or {}) settings = {**cfg.settings, **desired.settings} - for fnd in check_zone(live, zone, expect_mx=not settings.get("ignore_mx_check")): + for fnd in check_zone(live, merge_zones(parts), expect_mx=not settings.get("ignore_mx_check")): findings.append((fnd.field, fnd.message)) if findings: rc = 1 out.write(f"{domain:<28} {len(findings)} finding(s)\n") out.writelines(f" {field}: {msg}\n" for field, msg in findings) - elif zone_file is not None: + elif zone_files: out.write(f"{domain:<28} clean\n") continue @@ -288,6 +290,9 @@ def main() -> int: g.add_argument("--export", action="store_true", help="Write per-domain files from live state") g.add_argument("--drift", action="store_true", help="Check FE DNS records and expectations against the repo") args = p.parse_args() + if args.prune and (args.export or args.drift): + # Accepted-and-ignored would read as a prune that silently did nothing. + p.error("--prune only applies to plan/apply; --export and --drift never delete anything") try: cfg = load_forward_email(args.config) diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index ee7eda2..be125b7 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -175,6 +175,35 @@ class ForwardEmailConfigError(ValueError): """Raised when the block or a domain file is invalid.""" +class DuplicateKeyError(yaml.YAMLError): + """A mapping key given twice. PyYAML keeps the last one silently; a file with two `aliases:` + blocks would plan — and with --prune, delete — against the one the author never meant.""" + + +class _StrictLoader(yaml.SafeLoader): + def construct_mapping(self, node, deep=False): + seen: dict = {} + for key_node, _value_node in node.value: + if key_node.tag == "tag:yaml.org,2002:merge": + continue # `<<: *anchor` pairs are flattened by SafeLoader and may override by design + key = self.construct_object(key_node, deep=deep) + try: + hash(key) + except TypeError: + continue # SafeLoader reports the unhashable key itself + if key in seen: + raise DuplicateKeyError( + f"duplicate key {key!r} at line {key_node.start_mark.line + 1} (first at line {seen[key]})" + ) + seen[key] = key_node.start_mark.line + 1 + return super().construct_mapping(node, deep=deep) + + +def load_yaml_strict(stream): + """`yaml.safe_load` that rejects duplicate mapping keys (`DuplicateKeyError`, a `YAMLError`).""" + return yaml.load(stream, Loader=_StrictLoader) + + @dataclass(frozen=True) class ForwardEmailConfig: """Resolved repo-level configuration (package defaults merged with repo overrides).""" @@ -215,7 +244,7 @@ def _load_yaml(path: Path) -> dict: raise ForwardEmailConfigError(f"file not found: {path}") try: with open(path) as f: - data = yaml.safe_load(f) or {} + data = load_yaml_strict(f) or {} except (OSError, yaml.YAMLError) as e: raise ForwardEmailConfigError(f"{path}: {type(e).__name__}: {e}") from e if not isinstance(data, dict): diff --git a/src/octodns_gitops/forward_email/drift.py b/src/octodns_gitops/forward_email/drift.py index ed7e749..7ed53f3 100644 --- a/src/octodns_gitops/forward_email/drift.py +++ b/src/octodns_gitops/forward_email/drift.py @@ -26,12 +26,31 @@ class DriftFinding: message: str +def merge_zones(zones: list[dict]) -> dict: + """One record set from several YAML sources of the same zone (octoDNS merges its sources): + entries under the same name concatenate, so `_records` sees all of them.""" + merged: dict = {} + for zone in zones: + for name, entry in zone.items(): + if name in merged: + prev = merged[name] + merged[name] = (prev if isinstance(prev, list) else [prev]) + ( + entry if isinstance(entry, list) else [entry] + ) + else: + merged[name] = entry + return merged + + def _records(zone: dict, name: str, rtype: str) -> list[dict]: - entry = zone.get(name) - if entry is None: - return [] - entries = entry if isinstance(entry, list) else [entry] - return [r for r in entries if r.get("type") == rtype] + """Records of `name`/`rtype`; DNS names are case-insensitive, so the key match is too.""" + want = name.lower() + entries: list = [] + for key, entry in zone.items(): + if entry is None or str(key).lower() != want: + continue + entries.extend(entry if isinstance(entry, list) else [entry]) + return [r for r in entries if isinstance(r, dict) and r.get("type") == rtype] def _values(zone: dict, name: str, rtype: str) -> list: @@ -93,8 +112,9 @@ def check_zone(live_domain: dict, zone: dict, *, expect_mx: bool) -> list[DriftF rp = recs.get("return_path") if rp: - got = [v.rstrip(".") for v in _values(zone, rp["name"], "CNAME")] - if rp["value"].rstrip(".") not in got: + # Hostnames are case-insensitive: `ForwardEmail.NET.` is the same target. + got = [str(v).rstrip(".").lower() for v in _values(zone, rp["name"], "CNAME")] + if rp["value"].rstrip(".").lower() not in got: findings.append(DriftFinding("return_path", f"{rp['name']} CNAME: expected {rp['value']}, zone has {got}")) token = live_domain.get("verification_record") diff --git a/src/octodns_gitops/forward_email/reconcile.py b/src/octodns_gitops/forward_email/reconcile.py index 73c94d7..7399e6b 100644 --- a/src/octodns_gitops/forward_email/reconcile.py +++ b/src/octodns_gitops/forward_email/reconcile.py @@ -12,7 +12,11 @@ default". A live value differing from the desired one is reset with a blank PUT. - `labels` is server-applied (`catch-all`): never compared here, rejected by the config loader. - A prune never deletes an alias with `has_imap` or stored mail: that is a mailbox. Such an - alias missing from git is an error that blocks the run. + alias missing from git is an error that blocks the run — and so is an update that would turn + IMAP off only because the file omits `has_imap` (the default is `false`); an explicit + `has_imap: false` is intent. +- An alias with no recipients must be a mailbox (`has_imap` resolving to true); otherwise mail to + it is accepted and delivered nowhere, so it is an error, never a create or update. """ from __future__ import annotations @@ -200,6 +204,22 @@ def plan_domain( for want in desired.aliases: resolved = _resolve_alias(want, cfg.alias) live = live_by_name.get(want.name) + # The prune guard below says "add it to git"; without this, doing exactly that (and + # omitting `has_imap`) would PUT has_imap=false on the next apply. Decidable only here, + # where both the resolved default and the live alias are known. + if live is not None and live.get("has_imap") and want.has_imap is None and not resolved["has_imap"]: + plan.errors.append( + f"refusing to disable IMAP on {want.name}@{desired.domain}: it is a mailbox " + f"(has_imap={live.get('has_imap')}, storage_used={live.get('storage_used')}) and the file " + "does not declare has_imap; declare `has_imap: true` to keep it or `has_imap: false` to turn it off" + ) + continue + if not resolved["recipients"] and not resolved["has_imap"]: + plan.errors.append( + f"alias {want.name}@{desired.domain} has no recipients and no mailbox (has_imap resolves to " + "false): mail to it would be accepted and delivered nowhere; give it recipients or `has_imap: true`" + ) + continue if live is None: plan.aliases.append(AliasChange("create", want.name, None, _alias_body(resolved), ["new"])) continue @@ -218,7 +238,7 @@ def plan_domain( plan.errors.append( f"refusing to prune {live['name']}@{desired.domain}: it is a mailbox " f"(has_imap={live.get('has_imap')}, storage_used={live.get('storage_used')}); " - "add it to git or delete it in the web UI" + "add it to git with `has_imap: true` or delete it in the web UI" ) continue plan.aliases.append(AliasChange("delete", live["name"], live.get("id"), {}, ["prune"])) diff --git a/tests/bootstrap/test_makefile.py b/tests/bootstrap/test_makefile.py index beb6970..599ab82 100644 --- a/tests/bootstrap/test_makefile.py +++ b/tests/bootstrap/test_makefile.py @@ -51,7 +51,9 @@ def test_makefile_contains_forward_email_targets(self): assert target in MAKEFILE_TEMPLATE assert MAKEFILE_TEMPLATE.count("octodns-gitops-forwardemail --doit") == 1 assert "--domain $(DOMAIN)" in MAKEFILE_TEMPLATE - assert "$(if $(PRUNE),--prune,)" in MAKEFILE_TEMPLATE + # PRUNE=0 / PRUNE=false must not prune: only the literal `1` the help text documents. + assert MAKEFILE_TEMPLATE.count("$(if $(filter 1,$(PRUNE)),--prune,)") == 2 + assert "$(if $(PRUNE)," not in MAKEFILE_TEMPLATE def test_makefile_supports_force_flag(self): """The Makefile should support FORCE=1 for apply.""" diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py index e736fe6..ad19a21 100644 --- a/tests/cli/test_forward_email.py +++ b/tests/cli/test_forward_email.py @@ -176,6 +176,15 @@ def test_unclaimed_domain_filter_is_rejected(self, tmp_path): assert rc == 2 assert "other.be" in out + def test_expectation_mismatch_is_printed_but_is_not_a_plan_failure(self, tmp_path): + # Plan/apply are about writes; a read-only mismatch is a drift finding (rc 1 there only). + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be", has_smtp=False)], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, doit=True) + assert rc == 0 + assert "expect: has_smtp is False, expected True" in out + assert client.writes() == [] + class TestApply: def test_doit_sends_settings_and_alias_writes(self, tmp_path): @@ -346,12 +355,67 @@ class TestDrift: """ ) + # The same zone split over two YamlProviders (octoDNS merges sources): apex MX, DKIM and the + # return-path CNAME in one, the apex verification TXT and _dmarc in the other. + ZONE_A = textwrap.dedent( + """ + '': + - type: MX + values: + - {exchange: mx1.forwardemail.net., preference: 10} + - {exchange: mx2.forwardemail.net., preference: 10} + fe-1._domainkey: + type: TXT + value: v=DKIM1\\; k=rsa\\; p=MIIBIjANBg\\; + fe-bounces: + type: CNAME + value: forwardemail.net. + """ + ) + ZONE_B = textwrap.dedent( + """ + '': + - type: TXT + values: + - forward-email-site-verification=TOKEN + _dmarc: + type: TXT + value: v=DMARC1\\; p=quarantine\\; rua=mailto:dmarc-1@forwardemail.net\\; + """ + ) + def _zones(self, tmp_path, text=None): zd = tmp_path / "zones" zd.mkdir() (zd / "x.be.yaml").write_text(text or self.ZONE) return ZoneLookup.single(zd) + def test_zone_split_over_several_yaml_sources_is_merged_for_the_check(self, tmp_path): + # Inspecting only the first named source would flag _dmarc/verification as missing; + # only the second, everything else. Same-name entries (the apex) concatenate. + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + a, b = tmp_path / "a", tmp_path / "b" + for d, text in ((a, self.ZONE_A), (b, self.ZONE_B)): + d.mkdir() + (d / "x.be.yaml").write_text(text) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=ZoneLookup({"a": a, "b": b}, {"x.be": ["a", "b"]})) + assert rc == 0, out + assert "clean" in out + for only in ("a", "b"): + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=ZoneLookup({"a": a, "b": b}, {"x.be": [only]})) + assert rc == 1, out + + def test_named_sources_without_a_zone_file_are_not_checked(self, tmp_path): + _write_domain_file(tmp_path, "x.be", "aliases: []\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + a, b = tmp_path / "a", tmp_path / "b" + a.mkdir() + b.mkdir() + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=ZoneLookup({"a": a, "b": b}, {"x.be": ["a", "b"]})) + assert rc == 0 + assert "no zone file" in out + def test_clean_zone_and_matching_expectations_exit_0(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be")], {"x.be": []}) @@ -413,35 +477,38 @@ class TestConfigPlumbing: targets: [other] old.be.: sources: [legacy] + split.be.: + sources: [other, zones, legacy] cloud.be.: sources: [other] """ ) - def test_zone_directory_is_resolved_per_domain_from_the_zone_sources(self, tmp_path): + def test_zone_directories_are_resolved_per_domain_from_the_zone_sources(self, tmp_path): cfg = tmp_path / "config.yaml" cfg.write_text(self.CONFIG) zones = zone_lookup(str(cfg)) - assert zones.directory("x.be") == tmp_path / "zones" - assert zones.directory("old.be") == Path("/abs/legacy") - # sourced from a non-YAML provider only: there is no zone file to compare - assert zones.directory("cloud.be") is None + assert zones.directories("x.be") == [tmp_path / "zones"] + assert zones.directories("old.be") == [Path("/abs/legacy")] + # every named YamlProvider, in source order; non-YAML sources have no file to compare + assert zones.directories("split.be") == [tmp_path / "zones", Path("/abs/legacy")] + assert zones.directories("cloud.be") == [] - def test_zone_directory_falls_back_to_the_only_yaml_provider(self, tmp_path): + def test_zone_directories_fall_back_to_the_only_yaml_provider(self, tmp_path): cfg = tmp_path / "config.yaml" cfg.write_text("providers:\n zones:\n class: octodns.provider.yaml.YamlProvider\n directory: ./zones\n") - assert zone_lookup(str(cfg)).directory("anything.be") == tmp_path / "zones" + assert zone_lookup(str(cfg)).directories("anything.be") == [tmp_path / "zones"] cfg.write_text("providers:\n other:\n class: octodns_hetzner.HetznerProvider\n") - assert zone_lookup(str(cfg)).directory("anything.be") is None + assert zone_lookup(str(cfg)).directories("anything.be") == [] - def test_zone_directory_with_several_yaml_providers_and_no_source_is_ambiguous(self, tmp_path): + def test_zone_directories_with_several_yaml_providers_and_no_source_is_ambiguous(self, tmp_path): cfg = tmp_path / "config.yaml" cfg.write_text(self.CONFIG) with pytest.raises(AmbiguousZoneDirectory, match="2 YamlProviders"): - zone_lookup(str(cfg)).directory("unlisted.be") + zone_lookup(str(cfg)).directories("unlisted.be") # a wildcard zone entry names the source for every unlisted zone cfg.write_text(self.CONFIG + " '*':\n sources: [legacy]\n") - assert zone_lookup(str(cfg)).directory("unlisted.be") == Path("/abs/legacy") + assert zone_lookup(str(cfg)).directories("unlisted.be") == [Path("/abs/legacy")] def test_main_without_opt_in_block_is_a_noop(self, tmp_path, monkeypatch, capsys): cfg = tmp_path / "config.yaml" @@ -459,6 +526,17 @@ def test_main_rejects_doit_together_with_dry_run(self, tmp_path, monkeypatch, ca assert e.value.code == 2 assert "not allowed with" in capsys.readouterr().err + @pytest.mark.parametrize("mode", ["--export", "--drift"]) + def test_main_rejects_prune_in_a_mode_that_never_prunes(self, tmp_path, monkeypatch, capsys, mode): + # Accepted-and-ignored would make `--drift --prune` a scary command that does nothing. + cfg = tmp_path / "config.yaml" + cfg.write_text("forward_email:\n domains: [x.be]\n") + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg), mode, "--prune"]) + with pytest.raises(SystemExit) as e: + main() + assert e.value.code == 2 + assert "--prune" in capsys.readouterr().err + @pytest.mark.parametrize("text", ["forward_email: [\n", "forward_email:\n domains: [x.be]\n directory: 5\n"]) def test_main_reports_malformed_config_as_rc_2_not_a_traceback(self, tmp_path, monkeypatch, capsys, text): cfg = tmp_path / "config.yaml" diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index a40f0aa..98ad589 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -198,6 +198,26 @@ def test_unreadable_or_malformed_yaml_is_a_config_error(self, tmp_path): with pytest.raises(ForwardEmailConfigError, match="dir.yaml"): load_domain_file(d, "x.be") + @pytest.mark.parametrize( + ("body", "needle"), + [ + ("aliases:\n - {name: keep, recipients: [x@y.z]}\naliases:\n - {name: b, recipients: [x@y.z]}\n", "'aliases'"), + ("aliases:\n - name: a\n recipients: [x@y.z]\n recipients: [z@y.x]\n", "'recipients'"), + ("settings:\n retention_days: 0\nsettings:\n retention_days: 30\naliases: []\n", "'settings'"), + ], + ) + def test_duplicate_mapping_keys_are_an_error_not_last_wins(self, tmp_path, body, needle): + # PyYAML silently keeps the last duplicate: with --prune the aliases of the first + # `aliases:` block would be deleted. The error names the key and the line. + p = _write(tmp_path, "x.be.yaml", body) + with pytest.raises(ForwardEmailConfigError, match=f"duplicate key {needle} at line [0-9]+"): + load_domain_file(p, "x.be") + + def test_duplicate_keys_in_config_yaml_are_an_error(self, tmp_path): + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [x.be]\nforward_email:\n domains: [y.be]\n") + with pytest.raises(ForwardEmailConfigError, match="duplicate key 'forward_email'"): + load_forward_email(str(cfg)) + def test_domains_must_be_strings(self, tmp_path): cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [123]\n") with pytest.raises(ForwardEmailConfigError, match="string"): diff --git a/tests/forward_email/test_drift.py b/tests/forward_email/test_drift.py index 38455f2..2665942 100644 --- a/tests/forward_email/test_drift.py +++ b/tests/forward_email/test_drift.py @@ -80,6 +80,17 @@ def test_return_path_cname_missing(self): z = _zone(**{"fe-bounces": None}) assert _fields(check_zone(LIVE, z, expect_mx=True)) == ["return_path"] + def test_hostnames_and_record_names_compare_case_insensitively(self): + # DNS names are case-insensitive: a hand-written `ForwardEmail.NET.` or an upper-cased + # record key is the same record, not drift. + z = _zone(**{"fe-53661bcfc9._domainkey": None}) + z["FE-53661BCFC9._domainkey"] = {"type": "TXT", "value": DKIM.replace(";", r"\;")} + z["fe-bounces"] = {"type": "CNAME", "value": "ForwardEmail.NET."} + assert check_zone(LIVE, z, expect_mx=True) == [] + live = copy.deepcopy(LIVE) + live["smtp_dns_records"]["return_path"]["name"] = "FE-Bounces" + assert check_zone(live, ZONE, expect_mx=True) == [] + def test_verification_txt_missing_from_apex(self): z = _zone() z[""][2]["values"] = ["v=spf1 include:spf.forwardemail.net ~all"] diff --git a/tests/forward_email/test_reconcile.py b/tests/forward_email/test_reconcile.py index f75d4a3..5f1e7b7 100644 --- a/tests/forward_email/test_reconcile.py +++ b/tests/forward_email/test_reconcile.py @@ -300,6 +300,94 @@ def test_prune_never_touches_a_mailbox(self, guard): assert "box" in plan.errors[0] +class TestMailboxUpdate: + """The prune guard's own remedy ("add it to git") must not walk the operator into a PUT that + turns IMAP off: an alias declared without `has_imap` resolves to the default `false`.""" + + def test_omitted_has_imap_never_disables_imap_on_a_live_mailbox(self): + plan = plan_domain( + _desired([DesiredAlias("box", [])]), + _cfg(), + _live_domain(), + [_live_alias("box", recipients=[], has_imap=True, storage_used=5_000_000)], + prune=False, + ) + assert plan.aliases == [] + assert len(plan.errors) == 1 + assert "box@x.be" in plan.errors[0] and "has_imap: true" in plan.errors[0] + assert not plan.is_empty() + + def test_explicit_has_imap_false_is_intent_and_still_updates(self): + # A mailbox that also forwards: turning IMAP off leaves a delivery target. + plan = plan_domain( + _desired([DesiredAlias("box", ["serge@ginsys.eu"], has_imap=False)]), + _cfg(), + _live_domain(), + [_live_alias("box", has_imap=True, storage_used=5_000_000)], + prune=False, + ) + assert plan.errors == [] + (chg,) = plan.aliases + assert (chg.action, chg.changes) == ("update", ["has_imap"]) + assert chg.body["has_imap"] is False + + def test_explicit_has_imap_true_keeps_the_mailbox_with_no_diff(self): + plan = plan_domain( + _desired([DesiredAlias("box", [], has_imap=True)]), + _cfg(), + _live_domain(), + [_live_alias("box", recipients=[], has_imap=True, storage_used=5_000_000)], + prune=True, + ) + assert plan.is_empty(), (plan.aliases, plan.errors) + + def test_stored_mail_with_imap_already_off_is_neither_a_diff_nor_an_error(self): + # Nothing to clear: the guard is about the has_imap True -> False PUT, not about storage. + plan = plan_domain( + _desired([DesiredAlias("box", ["serge@ginsys.eu"])]), + _cfg(), + _live_domain(), + [_live_alias("box", has_imap=False, storage_used=5_000_000)], + prune=True, + ) + assert plan.is_empty(), (plan.aliases, plan.errors) + + +class TestNoDeliveryTarget: + """`recipients: []` is only meaningful for a mailbox; with `has_imap` resolving to false the + alias would accept mail and deliver it nowhere. Decidable only after defaults are resolved.""" + + def test_create_without_recipients_or_mailbox_is_an_error_not_a_create(self): + plan = plan_domain(_desired([DesiredAlias("a", [])]), _cfg(), _live_domain(), [], prune=False) + assert plan.aliases == [] + assert len(plan.errors) == 1 + assert "a@x.be" in plan.errors[0] and "no recipients" in plan.errors[0] and "has_imap: true" in plan.errors[0] + + def test_update_emptying_recipients_on_a_non_mailbox_is_an_error(self): + plan = plan_domain( + _desired([DesiredAlias("a", [], has_imap=False)]), + _cfg(), + _live_domain(), + [_live_alias("a")], + prune=False, + ) + assert plan.aliases == [] + assert len(plan.errors) == 1 and "no recipients" in plan.errors[0] + + def test_mailbox_without_recipients_is_created_with_has_imap(self): + plan = plan_domain(_desired([DesiredAlias("a", [], has_imap=True)]), _cfg(), _live_domain(), [], prune=False) + assert plan.errors == [] + (chg,) = plan.aliases + assert (chg.action, chg.body["recipients"], chg.body["has_imap"]) == ("create", [], True) + + def test_repo_default_has_imap_true_makes_recipientless_aliases_mailboxes(self): + plan = plan_domain( + _desired([DesiredAlias("a", [])]), _cfg(alias={"has_imap": True}), _live_domain(), [], prune=False + ) + assert plan.errors == [] + assert plan.aliases[0].body["has_imap"] is True + + class TestExpectations: def test_read_only_mismatch_is_reported_not_written(self): plan = plan_domain(_desired(), _cfg(), _live_domain(has_smtp=False), [], prune=False) From eeaf3d770372da8fcff07eb4dd53846ddb66b9bf Mon Sep 17 00:00:00 2001 From: Serge van Ginderachter Date: Sun, 30 Aug 2026 18:27:56 +0200 Subject: [PATCH 7/7] fix(forward-email): refuse --dry-run with --export, surface plan errors in drift, reject non-string keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - cli: `--dry-run --export` is a usage error (rc 2) — export always writes the domain files, so a "dry run" of it overwrote every selected file; `--dry-run --drift` stays allowed (drift writes nothing) - cli: the drift branch now reports every `plan.errors` entry as an `alias` finding (rc 1) instead of reading "clean" for a file plan/apply refuses - config: `_check_keys` rejects non-string mapping keys with a clear message; an unquoted `on:` loads as True and made the unknown-key join raise TypeError (traceback instead of rc 2/1) Addresses GitHub Codex threads I1-I3 posted at 2072407. --- src/octodns_gitops/cli/forward_email.py | 9 ++++++++- src/octodns_gitops/forward_email/config.py | 7 +++++++ tests/cli/test_forward_email.py | 20 ++++++++++++++++++++ tests/forward_email/test_config.py | 21 +++++++++++++++++++++ 4 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/octodns_gitops/cli/forward_email.py b/src/octodns_gitops/cli/forward_email.py index 0e71806..5acd44d 100644 --- a/src/octodns_gitops/cli/forward_email.py +++ b/src/octodns_gitops/cli/forward_email.py @@ -15,7 +15,9 @@ mismatches but do not fail on them, they are read-only), a refused prune, a blocked alias, or any per-domain error (a bad per-domain file included — the other domains still run); 2 the invocation itself is invalid (the `forward_email:` block, a missing token, an unclaimed `--domain`, `--prune` -outside plan/apply). +outside plan/apply, `--dry-run` with `--export`). In `--drift` an alias the plan would refuse on +the file alone (no recipients and no mailbox) is a finding as well; guards that need live state +(the mailbox update guard, prune) are plan/apply only, since drift never reads the live aliases. """ from __future__ import annotations @@ -234,6 +236,8 @@ def run( findings = [] plan = plan_domain(desired, cfg, live, [], prune=False) findings += [(m.field, f"{m.field} is {m.live!r}, expected {m.desired!r}") for m in plan.expect_mismatch] + # A file plan/apply refuses is drift too — "clean" here must not contradict `make mail-plan`. + findings += [("alias", e) for e in plan.errors] zone_files: list[Path] = [] try: zone_dirs = zones.directories(domain) if zones else [] @@ -293,6 +297,9 @@ def main() -> int: if args.prune and (args.export or args.drift): # Accepted-and-ignored would read as a prune that silently did nothing. p.error("--prune only applies to plan/apply; --export and --drift never delete anything") + if args.dry_run and args.export: + # --export always writes the files; a "dry run" of it would overwrite every selected one. + p.error("--dry-run cannot be combined with --export, which always writes the domain files") try: cfg = load_forward_email(args.config) diff --git a/src/octodns_gitops/forward_email/config.py b/src/octodns_gitops/forward_email/config.py index be125b7..c1e1bbb 100644 --- a/src/octodns_gitops/forward_email/config.py +++ b/src/octodns_gitops/forward_email/config.py @@ -265,6 +265,13 @@ def _section(where: str, container: dict, key: str) -> dict: def _check_keys(where: str, given: dict, allowed: frozenset[str]) -> None: + # YAML 1.1 reads an unquoted `on:`/`yes:`/`no:` as a bool and a bare number as an int; such + # a key can never be a field, and sorting/joining it against str keys raised TypeError. + odd = [k for k in given if not isinstance(k, str)] + if odd: + raise ForwardEmailConfigError( + f"{where}: keys must be strings, got {', '.join(repr(k) for k in odd)} (quote YAML words such as `on`)" + ) unknown = sorted(set(given) - allowed) if unknown: raise ForwardEmailConfigError(f"{where}: unknown or read-only field(s): {', '.join(unknown)}") diff --git a/tests/cli/test_forward_email.py b/tests/cli/test_forward_email.py index ad19a21..dab0f7d 100644 --- a/tests/cli/test_forward_email.py +++ b/tests/cli/test_forward_email.py @@ -438,6 +438,15 @@ def test_expectation_mismatch_is_drift(self, tmp_path): assert rc == 1 assert "has_smtp" in out + def test_plan_errors_are_drift_findings_not_silently_clean(self, tmp_path): + # A file plan/apply refuses (recipients: [] on a non-mailbox) must not read "clean" here. + _write_domain_file(tmp_path, "x.be", "aliases:\n - {name: a, recipients: []}\n") + client = FakeClient([_live_domain("x.be")], {"x.be": []}) + rc, out = _run(_cfg(tmp_path), client, mode="drift", zones=self._zones(tmp_path)) + assert rc == 1 + assert "alias: alias a@x.be has no recipients" in out + assert "clean" not in out + def test_domain_without_zone_file_is_informational(self, tmp_path): _write_domain_file(tmp_path, "x.be", "aliases: []\n") client = FakeClient([_live_domain("x.be")], {"x.be": []}) @@ -526,6 +535,17 @@ def test_main_rejects_doit_together_with_dry_run(self, tmp_path, monkeypatch, ca assert e.value.code == 2 assert "not allowed with" in capsys.readouterr().err + def test_main_rejects_dry_run_with_export(self, tmp_path, monkeypatch, capsys): + # `--export` writes the domain files whatever else is passed: accepting `--dry-run` + # alongside it would promise a preview and overwrite every selected file. + cfg = tmp_path / "config.yaml" + cfg.write_text("forward_email:\n domains: [x.be]\n") + monkeypatch.setattr("sys.argv", ["x", "--config", str(cfg), "--export", "--dry-run"]) + with pytest.raises(SystemExit) as e: + main() + assert e.value.code == 2 + assert "--dry-run" in capsys.readouterr().err + @pytest.mark.parametrize("mode", ["--export", "--drift"]) def test_main_rejects_prune_in_a_mode_that_never_prunes(self, tmp_path, monkeypatch, capsys, mode): # Accepted-and-ignored would make `--drift --prune` a scary command that does nothing. diff --git a/tests/forward_email/test_config.py b/tests/forward_email/test_config.py index 98ad589..cca7f12 100644 --- a/tests/forward_email/test_config.py +++ b/tests/forward_email/test_config.py @@ -213,6 +213,27 @@ def test_duplicate_mapping_keys_are_an_error_not_last_wins(self, tmp_path, body, with pytest.raises(ForwardEmailConfigError, match=f"duplicate key {needle} at line [0-9]+"): load_domain_file(p, "x.be") + @pytest.mark.parametrize( + "body", + [ + "on: true\naliases: []\n", + "settings:\n on: true\naliases: []\n", + "aliases:\n - {name: a, recipients: [x@y.z], on: 1}\n", + "aliases:\n - {name: a, recipients: [x@y.z], vacation_responder: {is_enabled: true, 1: x}}\n", + ], + ) + def test_non_string_keys_are_a_config_error_not_a_traceback(self, tmp_path, body): + # YAML 1.1 reads an unquoted `on:` as the boolean True; sorting it against str keys + # raised TypeError inside the unknown-key check (traceback instead of rc 2/1). + p = _write(tmp_path, "x.be.yaml", body) + with pytest.raises(ForwardEmailConfigError, match="keys must be strings"): + load_domain_file(p, "x.be") + + def test_non_string_keys_in_the_block_are_a_config_error(self, tmp_path): + cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [x.be]\n on: x\n") + with pytest.raises(ForwardEmailConfigError, match="keys must be strings.*True"): + load_forward_email(str(cfg)) + def test_duplicate_keys_in_config_yaml_are_an_error(self, tmp_path): cfg = _write(tmp_path, "config.yaml", "forward_email:\n domains: [x.be]\nforward_email:\n domains: [y.be]\n") with pytest.raises(ForwardEmailConfigError, match="duplicate key 'forward_email'"):