diff --git a/plugins/action/cloudflare_records_converged.py b/plugins/action/cloudflare_records_converged.py new file mode 100644 index 0000000000..6e24436f37 --- /dev/null +++ b/plugins/action/cloudflare_records_converged.py @@ -0,0 +1,444 @@ +from __future__ import annotations + +import json +from collections import Counter +from http.client import HTTPException +from typing import Any +from urllib.parse import urlencode + +from ansible.errors import AnsibleActionFail +from ansible.module_utils.common.validation import check_type_int +from ansible.module_utils.parsing.convert_bool import boolean +from ansible.module_utils.urls import ConnectionError as UrlsConnectionError +from ansible.module_utils.urls import open_url +from ansible.plugins.action import ActionBase + +API = "https://api.cloudflare.com/client/v4" +REVIEWED_COMMUNITY_GENERAL = "14.0.0" +PAGE_SIZE = 5000 +ARGUMENTS = frozenset({"api_token", "records", "timeout"}) +JUDGED_TYPES = ("A", "AAAA", "CNAME", "MX", "TXT", "SRV") +LOWERED_TYPES = ("CNAME", "MX", "SRV") +PROXIABLE_TYPES = ("A", "AAAA", "CNAME") +APPLY_TTL = 1 +APPLY_PROXIED = False +APPLY_SOLO = False +APPLY_STATE = "present" +APPLY_MX_PRIORITY = 10 +MODULE_PRIORITY = 1 +MODULE_PROXIED = False +READ_FAILURES = ( + OSError, + ValueError, + KeyError, + TypeError, + HTTPException, + UrlsConnectionError, +) + + +def _get(path: str, token: str, timeout: int) -> dict[str, Any]: + """ + Args: + path: API path below ``API``, query string included. + token: Cloudflare API token, sent in the bearer header only. + timeout: seconds one socket operation may stall. + + Returns: + The decoded answer; raises ``ValueError`` when Cloudflare reports no success. + """ + response = open_url( + API + path, + method="GET", + headers={ + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + }, + timeout=timeout, + ) + answer = json.loads(response.read()) + if not isinstance(answer, dict) or answer.get("success") is not True: + errors = answer.get("errors") if isinstance(answer, dict) else answer + raise ValueError(f"GET {path} answered without success: {errors}") + return answer + + +def zone_records(zone: str, token: str, timeout: int) -> list[dict[str, Any]]: + """ + Args: + zone: Cloudflare zone name. + token: Cloudflare API token. + timeout: seconds one socket operation may stall. + + Returns: + Every DNS record of the zone, across all pages; raises ``ValueError`` + unless exactly one zone carries the name. + """ + zones = _get("/zones?" + urlencode({"name": zone}), token, timeout)["result"] + if len(zones) != 1: + raise ValueError(f"{len(zones)} Cloudflare zones match {zone}") + records: list[dict[str, Any]] = [] + page = 1 + while True: + answer = _get( + f"/zones/{zones[0]['id']}/dns_records?" + + urlencode({"page": page, "per_page": PAGE_SIZE}), + token, + timeout, + ) + records.extend(answer["result"]) + if page >= int(answer["result_info"]["total_pages"]): + return records + page += 1 + + +def _int(value: Any) -> int | None: + """ + Args: + value: a record field the module reads as ``int``. + + Returns: + The integer ansible-core's ``check_type_int`` makes of the field, or + ``None`` when it is a boolean or ``check_type_int`` rejects it. + """ + if isinstance(value, bool): + return None + try: + return check_type_int(value) + except (TypeError, OverflowError): + return None + + +def _bool(value: Any) -> bool | None: + """ + Args: + value: a record field the module reads as ``bool``. + + Returns: + The boolean, or ``None`` when the field is not one. + """ + try: + return boolean(value, strict=True) + except TypeError: + return None + + +def _owner(record: Any) -> tuple[str, str, str] | None: + """ + Args: + record: one ``cloudflare_records`` entry. + + Returns: + ``(zone, type, name)`` of the record set the module edits for the + entry, normalised as the module normalises them, or ``None`` when the + entry names no A, AAAA, CNAME, MX, TXT or SRV record set. + """ + if not isinstance(record, dict): + return None + rtype = record.get("type") + zone = record.get("zone") + name = record.get("name") + if rtype not in JUDGED_TYPES: + return None + if not all(isinstance(v, str) and v for v in (zone, name)): + return None + zone = zone.lower() + fqdn = name.lower() + if fqdn == "@": + fqdn = zone + if not fqdn.endswith(zone): + fqdn = f"{fqdn}.{zone}" + if rtype == "SRV": + service = record.get("service") + proto = record.get("proto") + if not all(isinstance(v, str) and v for v in (service, proto)): + return None + service = service.lower() + proto = proto.lower() + if not service.startswith("_"): + service = f"_{service}" + if not proto.startswith("_"): + proto = f"_{proto}" + fqdn = f"{service}.{proto}.{fqdn}" + return zone, rtype, fqdn + + +def _hazardous(record: dict[str, Any]) -> bool: + """ + Args: + record: one ``cloudflare_records`` entry ``_owner`` keyed. + + Returns: + True when the module run for the entry may delete records of its + record set: it is solo, its solo flag reads as no boolean, or it is + not in state present. + """ + solo = _bool(record["solo"]) if "solo" in record else APPLY_SOLO + return solo is not False or record.get("state", APPLY_STATE) != "present" + + +def expected(record: Any) -> dict[str, Any] | None: + """ + Args: + record: one ``cloudflare_records`` entry as ``tasks/apply.yml`` of + ``sys-dns-cloudflare-records`` hands it to + ``community.general.cloudflare_dns``. + + Returns: + ``type``, ``name``, ``content``, ``ttl``, ``priority``, ``proxied``, + ``data`` and ``solo`` of the record the module converges the entry + to, or ``None`` unless the entry is a present A, AAAA, CNAME, MX, TXT + or SRV record whose every field reads as the module reads it. + """ + owner = _owner(record) + if owner is None: + return None + _zone, rtype, fqdn = owner + if record.get("state", APPLY_STATE) != "present": + return None + raw = record.get("content" if rtype in ("A", "AAAA") else "value") + if not (isinstance(raw, str) and raw): + return None + + if rtype in LOWERED_TYPES: + content = raw.rstrip(".").lower() + elif rtype == "AAAA": + content = raw.lower() + else: + content = raw + + ttl = _int(record["ttl"]) if "ttl" in record else APPLY_TTL + solo = _bool(record["solo"]) if "solo" in record else APPLY_SOLO + if rtype in ("A", "AAAA"): + proxied = _bool(record["proxied"]) if "proxied" in record else APPLY_PROXIED + elif rtype == "CNAME": + proxied = MODULE_PROXIED + else: + proxied = None + if rtype == "MX": + priority = ( + _int(record["priority"]) if "priority" in record else APPLY_MX_PRIORITY + ) + elif rtype == "SRV": + priority = _int(record.get("priority")) + else: + priority = MODULE_PRIORITY + if None in (ttl, solo, priority) or (rtype in PROXIABLE_TYPES and proxied is None): + return None + + data = None + if rtype == "SRV": + weight = _int(record.get("weight")) + port = _int(record.get("port")) + if weight is None or port is None: + return None + data = {"target": content, "port": port, "weight": weight, "priority": priority} + + return { + "type": rtype, + "name": fqdn, + "content": content, + "ttl": ttl, + "priority": priority, + "proxied": proxied, + "data": data, + "solo": solo, + } + + +def _srv_key(rr: dict[str, Any]) -> tuple[Any, Any, str] | None: + """ + Args: + rr: one DNS record as the Cloudflare API returns it. + + Returns: + ``(weight, port, target)`` the module matches SRV records by, or + ``None`` when the record carries no SRV data. + """ + data = rr.get("data") + if not isinstance(data, dict): + return None + return ( + data.get("weight"), + data.get("port"), + str(data.get("target")).rstrip(".").lower(), + ) + + +def _unquoted(content: Any) -> str: + """ + Args: + content: a TXT record content. + + Returns: + The content without one pair of surrounding double quotes. + """ + text = str(content) + if len(text) >= 2 and text.startswith('"') and text.endswith('"'): + return text[1:-1] + return text + + +def _identity(want: dict[str, Any]) -> Any: + """ + Args: + want: the record ``expected`` returns. + + Returns: + The key the module finds the record by within its record set: + ``(weight, port, target)`` for SRV, ``()`` for CNAME, whose record + set holds one record, and the case-folded content otherwise, TXT + without one pair of surrounding quotes. + """ + if want["type"] == "SRV": + return (want["data"]["weight"], want["data"]["port"], want["content"]) + if want["type"] == "CNAME": + return () + if want["type"] == "TXT": + return _unquoted(want["content"]).lower() + return want["content"].lower() + + +def converged(want: dict[str, Any], zone_rrs: list[Any]) -> bool: + """ + Args: + want: the record ``expected`` returns. + zone_rrs: every DNS record of the record's zone. + + Returns: + True only when the zone already holds exactly the record the module + would leave behind, so the module call would change nothing. + """ + same_name = [ + rr + for rr in zone_rrs + if isinstance(rr, dict) + and rr.get("type") == want["type"] + and str(rr.get("name")).lower() == want["name"] + ] + key = _identity(want) + if want["type"] == "SRV": + matches = [rr for rr in same_name if _srv_key(rr) == key] + elif want["type"] == "CNAME": + matches = same_name + elif want["type"] == "TXT": + matches = [ + rr for rr in same_name if _unquoted(rr.get("content")).lower() == key + ] + else: + matches = [rr for rr in same_name if str(rr.get("content")).lower() == key] + if len(matches) != 1 or (want["solo"] and len(same_name) != 1): + return False + rr = matches[0] + if rr.get("name") != want["name"] or rr.get("ttl") != want["ttl"]: + return False + if "priority" in rr and rr["priority"] != want["priority"]: + return False + if "comment" not in rr or rr["comment"] is not None or rr.get("tags") != []: + return False + if want["type"] in PROXIABLE_TYPES and ( + "proxied" not in rr or rr["proxied"] != want["proxied"] + ): + return False + if want["type"] == "SRV": + return rr.get("data") == want["data"] + return rr.get("content") == want["content"] + + +def split( + records: list[Any], token: str, timeout: int +) -> tuple[list[Any], list[str], list[str]]: + """ + Args: + records: the ``cloudflare_records`` list. + token: Cloudflare API token. + timeout: seconds one socket operation may stall. + + Returns: + ``(pending, converged, warnings)``: the entries the module still has + to apply, in their original order, the labels of the entries the + zone already holds as declared, and one warning per zone whose + records could not be read, whose entries all stay pending. Every + entry of a record set declared more than once stays pending when + one of its entries is hazardous or two of them declare the record + the module finds by one ``_identity`` differently, since each + verdict alone would let the last entry's apply undo the other's. + """ + owners = [_owner(record) for record in records] + wants = [expected(record) for record in records] + sizes = Counter(owner for owner in owners if owner is not None) + declared: dict[tuple[Any, Any], dict[str, Any]] = {} + blocked: set[tuple[str, str, str]] = set() + for owner, record, want in zip(owners, records, wants, strict=True): + if owner is None or sizes[owner] < 2: + continue + if _hazardous(record) or ( + want is not None + and declared.setdefault((owner, _identity(want)), want) != want + ): + blocked.add(owner) + zones: dict[str, list[Any] | None] = {} + pending: list[Any] = [] + labels: list[str] = [] + warnings: list[str] = [] + for owner, record, candidate in zip(owners, records, wants, strict=True): + want = None if owner in blocked else candidate + if want is None: + pending.append(record) + continue + zone = owner[0] + if zone not in zones: + try: + zones[zone] = zone_records(zone, token, timeout) + except READ_FAILURES as error: + zones[zone] = None + warnings.append( + f"Cloudflare zone {zone}: its records could not be read " + f"({error}), so every record of it goes through cloudflare_dns" + ) + if zones[zone] is not None and converged(want, zones[zone]): + labels.append(f"{want['type']} {want['name']}") + else: + pending.append(record) + return pending, labels, warnings + + +class ActionModule(ActionBase): + TRANSFERS_FILES = False + + def run( + self, tmp: Any = None, task_vars: dict[str, Any] | None = None + ) -> dict[str, Any]: + """ + Args: + tmp: unused, kept for the ``ActionBase`` signature. + task_vars: the task's variables. + + Returns: + The action result with ``pending`` and ``converged``. + """ + result = super().run(tmp, task_vars) + args = self._task.args or {} + unexpected = sorted(set(args) - ARGUMENTS) + missing = sorted(ARGUMENTS - set(args)) + if unexpected or missing: + raise AnsibleActionFail( + "cloudflare_records_converged: takes exactly api_token, records " + f"and timeout; unknown {unexpected}, missing {missing}" + ) + records = args["records"] + if not isinstance(records, list): + raise AnsibleActionFail( + "cloudflare_records_converged: records must be a list" + ) + timeout = _int(args["timeout"]) + if timeout is None: + raise AnsibleActionFail( + "cloudflare_records_converged: timeout must be an integer" + ) + + pending, labels, warnings = split(records, str(args["api_token"]), timeout) + result.update(changed=False, pending=pending, converged=labels) + if warnings: + result["warnings"] = warnings + return result diff --git a/plugins/lookup/proxy_pass.py b/plugins/lookup/proxy_pass.py index 15b057acd5..e828864413 100644 --- a/plugins/lookup/proxy_pass.py +++ b/plugins/lookup/proxy_pass.py @@ -1,5 +1,10 @@ """Lookup ``proxy_pass``: thin wrapper emitting the mode-aware directive via -:func:`utils.networks.proxy.resolve_upstream` + :func:`render_proxy_pass`.""" +:func:`utils.networks.proxy.resolve_upstream` + :func:`render_proxy_pass`. + +Trip-wire: a role's ``compose_mode_force`` stays in scope while its vhost +renders locations of other apps (the ``/logout`` location of web-svc-logout), +so the override applies only when the term names the scope's own +``application_id``.""" from __future__ import annotations @@ -54,9 +59,15 @@ class LookupModule(LookupBase): real_deployment_mode = str(raw_mode).strip() mode_force = vars_.get("compose_mode_force", "") + scope_application_id = vars_.get("application_id", "") if templar is not None: with contextlib.suppress(Exception): mode_force = templar.template(mode_force) + with contextlib.suppress(Exception): + scope_application_id = templar.template(scope_application_id) + scope_application_id = _as_str(scope_application_id) + if scope_application_id and scope_application_id != application_id: + mode_force = "" deployment_mode = _as_str(mode_force) or real_deployment_mode applications = lookup_loader.get( diff --git a/roles/svc-db-openldap/handlers/main.yml b/roles/svc-db-openldap/handlers/main.yml index ffe49df6c3..75555a624c 100644 --- a/roles/svc-db-openldap/handlers/main.yml +++ b/roles/svc-db-openldap/handlers/main.yml @@ -4,6 +4,8 @@ container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapmodify -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/01_member_of_configuration.ldif'] | path_join }}" + vars: + compose_mode_force: "" listen: - "import-configuration-ldif-files" register: r @@ -16,6 +18,8 @@ container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapmodify -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/04_refint_module.ldif'] | path_join }}" + vars: + compose_mode_force: "" listen: - "import-configuration-ldif-files" register: r @@ -28,6 +32,8 @@ container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapadd -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/02_member_of_configuration.ldif'] | path_join }}" + vars: + compose_mode_force: "" listen: - "import-configuration-ldif-files" register: r @@ -38,6 +44,8 @@ container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapadd -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/03_member_of_configuration.ldif'] | path_join }}" + vars: + compose_mode_force: "" listen: - "import-configuration-ldif-files" register: r @@ -53,6 +61,8 @@ -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'groups', (item | basename | regex_replace('\.j2$', ''))] | path_join }}"' environment: OPENLDAP_BIND_PW: "{{ OPENLDAP_BIND_PW }}" + vars: + compose_mode_force: "" listen: - "import-groups-ldif-files" register: ldapadd_result diff --git a/roles/svc-prx-openresty/handlers/reload.yml b/roles/svc-prx-openresty/handlers/reload.yml index 8c7873b25a..aa8cc63287 100644 --- a/roles/svc-prx-openresty/handlers/reload.yml +++ b/roles/svc-prx-openresty/handlers/reload.yml @@ -8,6 +8,8 @@ - name: ✅ Validate OpenResty configuration before reloading ansible.builtin.shell: > container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -t -q + vars: + compose_mode_force: "" register: openresty_test_reload changed_when: false retries: 10 @@ -22,6 +24,8 @@ - name: ♻️ Reload OpenResty ansible.builtin.shell: > container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -s reload + vars: + compose_mode_force: "" register: openresty_reload changed_when: openresty_reload.rc == 0 failed_when: > diff --git a/roles/svc-prx-openresty/handlers/restart.yml b/roles/svc-prx-openresty/handlers/restart.yml index 06db361cfc..5427956c1a 100644 --- a/roles/svc-prx-openresty/handlers/restart.yml +++ b/roles/svc-prx-openresty/handlers/restart.yml @@ -20,6 +20,8 @@ - name: ✅ Validate OpenResty configuration (Post-Flight-Check) ansible.builtin.shell: > container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -t -q + vars: + compose_mode_force: "" register: openresty_test_post changed_when: false retries: 10 @@ -58,6 +60,8 @@ - ansible.builtin.shell: > container logs --tail=200 {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} + vars: + compose_mode_force: "" register: openresty_logs changed_when: false failed_when: false diff --git a/roles/sys-dns-cloudflare-records/defaults/main.yml b/roles/sys-dns-cloudflare-records/defaults/main.yml index 4226f6f8ec..c0d187c1f2 100644 --- a/roles/sys-dns-cloudflare-records/defaults/main.yml +++ b/roles/sys-dns-cloudflare-records/defaults/main.yml @@ -7,7 +7,8 @@ cloudflare_request_timeout: 20 # Seconds one Cloudflare HTTP socket operation ma cloudflare_attempt_timeout: 60 # Seconds one record job may run before async_wrapper kills it as hung cloudflare_attempts: 3 # Attempts per record; only hangs, timeouts, connection errors, 429 and 5xx earn another cloudflare_retry_delay: 10 # Seconds between two attempts -cloudflare_collect_retries: "{{ ((lookup('timeout', cloudflare_attempt_timeout | int) | int) / 5) | round(0, 'ceil') | int + 2 }}" # Cap on 5 s polls per job; the attempt's collect deadline ends them sooner +cloudflare_collect_interval: 1 # Seconds between two polls of one record job while collecting +cloudflare_collect_retries: "{{ ((lookup('timeout', cloudflare_attempt_timeout | int) | int) / (cloudflare_collect_interval | int)) | round(0, 'ceil') | int + 2 }}" # Cap on polls per job; the attempt's collect deadline ends them sooner cloudflare_tolerate: # Substrings of an answer that mean the record already stands as wanted - "An identical record already exists" - "code: 81058" diff --git a/roles/sys-dns-cloudflare-records/tasks/judge.yml b/roles/sys-dns-cloudflare-records/tasks/judge.yml index b996b516a8..4602094153 100644 --- a/roles/sys-dns-cloudflare-records/tasks/judge.yml +++ b/roles/sys-dns-cloudflare-records/tasks/judge.yml @@ -8,7 +8,7 @@ register: _cf_reaped until: _cf_reaped.finished or (now(utc=true).timestamp() > (_cf_collect_deadline | float)) retries: "{{ cloudflare_collect_retries | int }}" - delay: 5 + delay: "{{ cloudflare_collect_interval | int }}" changed_when: false ignore_errors: true when: ASYNC_ENABLED | bool diff --git a/roles/sys-dns-cloudflare-records/tasks/main.yml b/roles/sys-dns-cloudflare-records/tasks/main.yml index be298f65bf..7fa8d2f3ca 100644 --- a/roles/sys-dns-cloudflare-records/tasks/main.yml +++ b/roles/sys-dns-cloudflare-records/tasks/main.yml @@ -7,9 +7,17 @@ no_log: "{{ cloudflare_no_log | bool }}" when: MODE_ASSERT | bool -- name: 🗂️ Queue every Cloudflare record for the first attempt +- name: 🔎 Read each zone once, set aside the records it already holds + cloudflare_records_converged: + api_token: "{{ lookup('api', 'cloudflare.api_token') }}" + records: "{{ cloudflare_records }}" + timeout: "{{ lookup('timeout', cloudflare_request_timeout | int) | int }}" + no_log: "{{ cloudflare_no_log | bool }}" + register: _cf_converged + +- name: 🗂️ Queue every drifted Cloudflare record for the first attempt ansible.builtin.set_fact: - _cf_pending: "{{ cloudflare_records }}" + _cf_pending: "{{ _cf_converged.pending }}" _cf_retry: [] - name: 🔁 Apply the Cloudflare records, retrying only hung and transiently failed ones diff --git a/roles/sys-front-inj-design/tasks/main.yml b/roles/sys-front-inj-design/tasks/main.yml index 4c520832a4..3e001a5a5f 100644 --- a/roles/sys-front-inj-design/tasks/main.yml +++ b/roles/sys-front-inj-design/tasks/main.yml @@ -21,13 +21,15 @@ _cdn_root: "{{ lookup('cdn', application_id).urls.root }}" _cdn_origin: "{{ _cdn_root | urlsplit('scheme') }}://{{ _cdn_root | urlsplit('netloc') }}/" _app_style_css: >- - {{ (lookup('template', _app_compose_src) | trim | replace(_cdn_origin, '/')) + {{ (lookup('template', _app_compose_src, + template_vars={'app_body_css': app_body_css, 'app_logo_css': app_logo_css}) + | trim | replace(_cdn_origin, '/')) if (app_body_css ~ app_logo_css) | length > 0 else '' }} set_fact: app_style_src: "{{ _app_style_src }}" app_style_file: "{{ css_app_file }}" app_style_css: "{{ _app_style_css }}" - app_style_present: "{{ _app_style_css | length > 0 }}" + app_style_present: "{{ (app_body_css ~ app_logo_css) | length > 0 }}" - name: "🚀 Deploy per-app '{{ app_style_src }}' to '{{ css_app_dst }}'" when: @@ -63,13 +65,12 @@ _design_compose_src: "{{ lookup('path_absolute', 'roles', 'sys-front-inj-design', 'templates', 'js', 'design.js.j2') }}" _design_config_src: "{{ lookup('path_absolute', 'roles', 'sys-front-inj-design', 'templates', 'js', 'design-config.json.j2') }}" design_body_js: "{{ (lookup('template', _design_js_src) | trim) if _design_js_src | length > 0 else '' }}" - _design_configured: "{{ 'INFINITO_DESIGN' in design_body_js }}" _design_js: >- - {{ (lookup('template', _design_compose_src) | trim) - if _design_configured | bool else design_body_js }} + {{ (lookup('template', _design_compose_src, template_vars={'design_body_js': design_body_js}) | trim) + if 'INFINITO_DESIGN' in design_body_js else design_body_js }} set_fact: - design_config_json: "{{ (lookup('template', _design_config_src) | trim) if _design_configured | bool else '' }}" - design_js_one_liner: "{{ (_design_js | to_one_liner) if _design_js | length > 0 else '' }}" + design_config_json: "{{ (lookup('template', _design_config_src) | trim) if 'INFINITO_DESIGN' in design_body_js else '' }}" + design_js_one_liner: "{{ _design_js | to_one_liner }}" design_css_states: "{{ design_css_states | combine({css_app_state_key: css_app_state}) }}" - name: "➕ Append design script CSP hash for '{{ application_id }}'" diff --git a/roles/web-opt-rdr-domains/lookup_plugins/template_shallow.py b/roles/web-opt-rdr-domains/lookup_plugins/template_shallow.py new file mode 100644 index 0000000000..3947611172 --- /dev/null +++ b/roles/web-opt-rdr-domains/lookup_plugins/template_shallow.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import Any + +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + + +class _SharedVariables(dict): + def __deepcopy__(self, memo: dict[int, Any]) -> dict[str, Any]: + return dict(self) + + +class LookupModule(LookupBase): + def run( + self, terms: list[Any], variables: dict[str, Any], **kwargs: Any + ) -> list[Any]: + """ + Args: + terms: the template paths, resolved like ``ansible.builtin.template``. + variables: the caller's variables; every term renders over a fresh + top-level copy whose values are shared with the caller. + kwargs: the ``ansible.builtin.template`` options, such as + ``template_vars``. + + Returns: + One rendered string per term. + """ + template = lookup_loader.get( + "template", loader=self._loader, templar=self._templar + ) + return template.run(terms, variables=_SharedVariables(variables), **kwargs) diff --git a/roles/web-opt-rdr-domains/tasks/main.yml b/roles/web-opt-rdr-domains/tasks/main.yml index 8efe8fa21b..d7aef08ef5 100644 --- a/roles/web-opt-rdr-domains/tasks/main.yml +++ b/roles/web-opt-rdr-domains/tasks/main.yml @@ -26,11 +26,11 @@ - "{{ lookup('cert', item.source, 'files.key') }}" files: >- {{ [{'path': lookup('nginx', 'files.domain', item.source), - 'content': lookup('template', 'redirect-domain.conf.j2', + 'content': lookup('template_shallow', 'redirect-domain.conf.j2', template_vars={'domain': item.source, 'target': item.target, 'keep_path': item.get('keep_path', true)})}] + ([{'path': lookup('nginx', 'files.domain', item.source, protocol='http'), - 'content': lookup('template', lookup('path_absolute', 'roles/sys-front-tls/templates/http.conf.j2'), + 'content': lookup('template_shallow', lookup('path_absolute', 'roles/sys-front-tls/templates/http.conf.j2'), template_vars={'domain': item.source})}] if redirect_source_tls else []) }} diff --git a/tests/integration/roles/svc-prx-openresty/__init__.py b/tests/integration/roles/svc-prx-openresty/__init__.py new file mode 100644 index 0000000000..eec6d4835a --- /dev/null +++ b/tests/integration/roles/svc-prx-openresty/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/integration/roles/svc-prx-openresty/test_handlers_ignore_caller_mode_force.py b/tests/integration/roles/svc-prx-openresty/test_handlers_ignore_caller_mode_force.py new file mode 100644 index 0000000000..97e3a7058e --- /dev/null +++ b/tests/integration/roles/svc-prx-openresty/test_handlers_ignore_caller_mode_force.py @@ -0,0 +1,255 @@ +"""The OpenResty handlers must address OpenResty at the cluster's own mode. + +A role that pins ``compose_mode_force`` in its vars (web-app-matrix's ansible +flavor, web-app-bigbluebutton) keeps that value in scope for every role it +includes, and for the svc-prx-openresty handler copy that +``tasks/utils/load/handlers.yml`` loads inside that chain. The +``container_address`` lookup honours the caller's override, so in a swarm +cluster the handlers asked for the compose name of a container that only exists +as a swarm task, tolerated the "no such container" and skipped the reload. + +These cases run real Ansible over the real handler files and the real lookup: +the forced role's own probe reproduces the override, so the handler assertions +cannot pass vacuously. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from typing import ClassVar + +from utils.cache.files import read_text +from utils.cache.yaml import dump_yaml +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +LOAD_HANDLERS = str(PROJECT_ROOT / "tasks" / "utils" / "load" / "handlers.yml") +OPENRESTY_LOOKUP = "{{ lookup('container_address', 'svc-prx-openresty', 'openresty') }}" +SWARM_MARK = "swarm-task" +MODES = ("swarm", "compose") + +FAKE_CONTAINER = """#!/bin/sh +printf '%s\\n' "$*" >> "$FAKE_CONTAINER_LOG" +""" + +FAKE_RESOLVER = f"""#!/bin/sh +printf '{SWARM_MARK}:%s:%s' "$1" "$2" +""" + + +def _load_handlers_task() -> dict: + return { + "name": "Load the OpenResty handlers", + "ansible.builtin.include_tasks": LOAD_HANDLERS, + "vars": {"handler_role_name": "svc-prx-openresty"}, + } + + +ROLES: dict[str, dict[str, object]] = { + "probe-forced": { + ROLE_FILE_VARS_MAIN: {"compose_mode_force": "compose"}, + ROLE_FILE_TASKS_MAIN: [ + { + "name": "Record what the forced scope resolves for OpenResty", + "ansible.builtin.copy": { + "dest": "{{ forced_scope_out }}", + "content": OPENRESTY_LOOKUP, + "mode": "0644", + }, + }, + { + "name": "Serve a vhost the way sys-stk-front-proxy does", + "ansible.builtin.include_role": {"name": "probe-front-proxy"}, + }, + ], + }, + "probe-front-proxy": { + ROLE_FILE_TASKS_MAIN: [ + { + "name": "Bootstrap the front base", + "ansible.builtin.include_role": {"name": "probe-front-base"}, + }, + { + "name": "Change a vhost", + "ansible.builtin.command": "true", + "changed_when": True, + "notify": "reload-openresty", + }, + { + "name": "Change the base configuration", + "ansible.builtin.command": "true", + "changed_when": True, + "notify": "restart-openresty", + "when": "notify_restart | bool", + }, + { + "name": "Run the notified handlers", + "ansible.builtin.meta": "flush_handlers", + }, + ], + }, + "probe-front-base": {ROLE_FILE_TASKS_MAIN: [_load_handlers_task()]}, +} + + +def _executable(path: Path, body: str) -> None: + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def _play(mode: str, resolver: Path, work: Path) -> dict: + """Build the play for one cluster mode. + + Args: + mode: the cluster ``DEPLOYMENT_MODE``, ``swarm`` or ``compose``. + resolver: the fake swarm container-id resolver. + work: the directory the play's output files land in. + """ + swarm = mode == "swarm" + return { + "name": f"OpenResty handlers notified from a forced role ({mode})", + "hosts": "localhost", + "gather_facts": False, + "connection": "local", + "environment": {"FAKE_CONTAINER_LOG": str(work / f"{mode}-container.log")}, + "vars": { + "ansible_python_interpreter": sys.executable, + "DEPLOYMENT_MODE": mode, + "IS_COMPOSE_MODE": not swarm, + "IS_SWARM_MODE": swarm, + "IS_STACK_HOST": False, + "MODE_DEBUG": swarm, + "STACK_HOST": "localhost", + "BIN_RESOLVE_CONTAINER_ID": str(resolver), + "notify_restart": swarm, + "forced_scope_out": str(work / f"{mode}-forced-scope.txt"), + }, + "tasks": [ + { + "name": "Render the applications SPOT once, as the constructor does", + "applications_carrier": {}, + }, + _load_handlers_task(), + { + "name": "Run the forced role the way tasks/utils/setup/role.yml does", + "ansible.builtin.include_role": {"name": "probe-forced"}, + "vars": {"application_id": "web-app-forced"}, + }, + ], + } + + +def _run(work: Path) -> dict[str, tuple[str, list[str]]]: + """Run one play per cluster mode in a single ansible-playbook process. + + Args: + work: an empty directory for the fixture roles, play and fakes. + + Returns: + Per mode ``(forced_scope, calls)``: what the forced role itself resolved + for OpenResty, and every argv the fake ``container`` CLI received. + + Raises: + RuntimeError: when ansible-playbook exits non-zero. + """ + for role, files in ROLES.items(): + for relative, content in files.items(): + target = work / "roles" / role / relative + target.parent.mkdir(parents=True, exist_ok=True) + dump_yaml(target, content) + bin_dir = work / "bin" + bin_dir.mkdir() + _executable(bin_dir / "container", FAKE_CONTAINER) + resolver = bin_dir / "resolve-container-id" + _executable(resolver, FAKE_RESOLVER) + playbook = work / "play.yml" + dump_yaml(playbook, [_play(mode, resolver, work) for mode in MODES]) + env = dict(os.environ) + env.update( + { + "ANSIBLE_CONFIG": str(PROJECT_ROOT / "ansible.cfg"), + "ANSIBLE_LOCAL_TEMP": str(work / "ansible-local"), + "ANSIBLE_REMOTE_TEMP": str(work / "ansible-remote"), + "ANSIBLE_NOCOLOR": "1", + "PATH": f"{bin_dir}{os.pathsep}{env['PATH']}", + } + ) + result = subprocess.run( + ["ansible-playbook", "-i", "localhost,", str(playbook)], + cwd=str(PROJECT_ROOT), + env=env, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + raise RuntimeError( + f"ansible-playbook failed\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" + ) + observed = {} + for mode in MODES: + log = read_text(str(work / f"{mode}-container.log")) + observed[mode] = ( + read_text(str(work / f"{mode}-forced-scope.txt")), + [line for line in log.splitlines() if line], + ) + return observed + + +def _targets(calls: list[str], verb: str) -> list[str]: + position = -1 if verb == "logs" else 1 + return [line.split()[position] for line in calls if line.startswith(f"{verb} ")] + + +@unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook is required") +class TestOpenRestyHandlersIgnoreCallerModeForce(unittest.TestCase): + observed: ClassVar[dict[str, tuple[str, list[str]]]] = {} + + @classmethod + def setUpClass(cls) -> None: + """One ansible-playbook run answers every case, so it runs once.""" + with tempfile.TemporaryDirectory(prefix="openresty-mode-force-") as tmp: + cls.observed = _run(Path(tmp)) + + def test_the_forced_scope_really_forces_the_lookup(self) -> None: + forced_scope, _ = self.observed["swarm"] + self.assertEqual( + forced_scope, + "openresty", + "the forced role must resolve OpenResty's compose name, or the " + "handler cases below prove nothing", + ) + + def test_swarm_reload_validates_and_reloads_the_swarm_task(self) -> None: + _, calls = self.observed["swarm"] + execs = [line for line in calls if line.startswith("exec ")] + self.assertIn("-s reload", " ".join(execs), calls) + targets = _targets(calls, "exec") + self.assertTrue(targets, calls) + for target in targets: + self.assertTrue(target.startswith(f"{SWARM_MARK}:"), calls) + + def test_swarm_restart_debug_logs_read_the_swarm_task(self) -> None: + _, calls = self.observed["swarm"] + targets = _targets(calls, "logs") + self.assertTrue(targets, calls) + for target in targets: + self.assertTrue(target.startswith(f"{SWARM_MARK}:"), calls) + + def test_compose_cluster_keeps_the_compose_name(self) -> None: + _, calls = self.observed["compose"] + targets = _targets(calls, "exec") + self.assertTrue(targets, calls) + self.assertEqual(set(targets), {"openresty"}, calls) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/tasks/test_handler_fixed_app_lookup_clears_mode_force.py b/tests/lint/ansible/tasks/test_handler_fixed_app_lookup_clears_mode_force.py new file mode 100644 index 0000000000..8fa95ea0d4 --- /dev/null +++ b/tests/lint/ansible/tasks/test_handler_fixed_app_lookup_clears_mode_force.py @@ -0,0 +1,167 @@ +"""A handler that resolves a fixed app must not inherit a caller's mode override. + +A role that pins ``compose_mode_force`` in its vars (web-app-matrix's ansible +flavor, web-app-bigbluebutton) keeps it in scope for every handler copy loaded +inside its include chain. A lookup that reads the caller's override then +resolves the named app at the caller's mode instead of the mode that app runs +at: the OpenResty reload asked a swarm cluster for a compose container name and +skipped the reload. + +So a handler task whose lookup names a fixed application clears the override +in its effective vars: its own ``vars:``, an enclosing block's, or those of the +``handlers/main.yml`` entry that includes its file by a literal path. A named +app that forces its own mode is exempt, since the override is then its own. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from collections.abc import Iterator + +ROLES = PROJECT_ROOT / "roles" +LOOKUPS = PROJECT_ROOT / "plugins" / "lookup" +READS_CALLER_OVERRIDE = re.compile(r"""\.get\(\s*["']compose_mode_force["']""") +SHARED_CONTEXT = re.compile(r"build_context\((?![^)]*honour_mode_force=False)") +INCLUDE_KEYS = ( + "include_tasks", + "import_tasks", + "ansible.builtin.include_tasks", + "ansible.builtin.import_tasks", +) +BLOCK_KEYS = ("block", "rescue", "always") + + +def _honouring_lookups() -> set[str]: + names = set() + for path in LOOKUPS.glob("*.py"): + text = read_text(str(path)) + if READS_CALLER_OVERRIDE.search(text) or SHARED_CONTEXT.search(text): + names.add(path.stem) + return names + + +def _forced_roles() -> set[str]: + forced = set() + for vars_main in ROLES.glob(f"*/{ROLE_FILE_VARS_MAIN}"): + data = load_yaml_any(str(vars_main), default_if_missing={}) + if isinstance(data, dict) and str(data.get("compose_mode_force") or "").strip(): + forced.add(vars_main.relative_to(ROLES).parts[0]) + return forced + + +def _vars(node: dict) -> dict: + found = node.get("vars") + return found if isinstance(found, dict) else {} + + +def _included_vars(handlers_dir: Path) -> dict[Path, dict]: + entries = load_yaml_any(str(handlers_dir / "main.yml"), default_if_missing=[]) + found: dict[Path, dict] = {} + for entry in entries if isinstance(entries, list) else []: + if not isinstance(entry, dict): + continue + for key in INCLUDE_KEYS: + target = entry.get(key) + if isinstance(target, dict): + target = target.get("file") + if isinstance(target, str) and "{{" not in target: + found[(handlers_dir / target).resolve()] = _vars(entry) + return found + + +def _tasks(items: Any, inherited: dict) -> Iterator[tuple[dict, dict]]: + for item in items if isinstance(items, list) else []: + if not isinstance(item, dict): + continue + scope = {**inherited, **_vars(item)} + bodies = [item[key] for key in BLOCK_KEYS if key in item] + if not bodies: + yield item, scope + for body in bodies: + yield from _tasks(body, scope) + + +def _handler_files() -> list[Path]: + found = [] + for raw in iter_project_files(extensions=(".yml",), exclude_tests=True): + relative = Path(raw).relative_to(PROJECT_ROOT).parts + if len(relative) > 3 and relative[0] == "roles" and relative[2] == "handlers": + found.append(Path(raw)) + return sorted(found) + + +def _strings(node: Any) -> Iterator[str]: + if isinstance(node, str): + yield node + elif isinstance(node, dict): + for value in node.values(): + yield from _strings(value) + elif isinstance(node, list): + for value in node: + yield from _strings(value) + + +def _scan() -> tuple[list[str], int]: + names = "|".join(sorted(re.escape(name) for name in _honouring_lookups())) + call = re.compile( + rf"""lookup\(\s*['"](?P{names})['"]\s*,\s*['"](?P[a-z0-9][a-z0-9-]*)['"]""" + ) + forced = _forced_roles() + included: dict[Path, dict[Path, dict]] = {} + offenders: list[str] = [] + checked = 0 + for path in _handler_files(): + handlers_dir = ROLES / path.relative_to(ROLES).parts[0] / "handlers" + if handlers_dir not in included: + included[handlers_dir] = _included_vars(handlers_dir) + tasks = load_yaml_any(str(path), default_if_missing=[]) + inherited = included[handlers_dir].get(path.resolve(), {}) + for task, scope in _tasks(tasks, inherited): + for text in _strings(task): + for match in call.finditer(text): + app = match["app"] + if app in forced or not (ROLES / app).is_dir(): + continue + checked += 1 + if scope.get("compose_mode_force") != "": + offenders.append( + f"{path.relative_to(PROJECT_ROOT)}: " + f"{task.get('name', '')}: " + f"lookup('{match['plugin']}', '{app}', ...)" + ) + return offenders, checked + + +class TestHandlerFixedAppLookupClearsModeForce(unittest.TestCase): + def test_container_address_is_known_to_honour_the_override(self) -> None: + self.assertIn("container_address", _honouring_lookups()) + + def test_every_fixed_app_lookup_in_a_handler_clears_the_override(self) -> None: + offenders, checked = _scan() + + self.assertGreater( + checked, 0, "no handler lookup names a fixed app, so nothing was checked" + ) + self.assertEqual( + offenders, + [], + f"{len(offenders)} handler lookup(s) resolve a fixed app under the " + f'caller\'s compose_mode_force. Add `compose_mode_force: ""` to the ' + f"task's vars (or to the handlers/main.yml entry that includes it):\n" + + "\n".join(offenders), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/action/test_cloudflare_records_converged.py b/tests/unit/python/plugins/action/test_cloudflare_records_converged.py new file mode 100644 index 0000000000..9cf64cfaf3 --- /dev/null +++ b/tests/unit/python/plugins/action/test_cloudflare_records_converged.py @@ -0,0 +1,691 @@ +import ast +import configparser +import json +import re +import unittest +from http.client import IncompleteRead +from pathlib import Path +from unittest.mock import patch +from urllib.error import HTTPError, URLError +from urllib.parse import parse_qs, urlsplit + +from ansible.errors import AnsibleActionFail +from ansible.module_utils.urls import ConnectionError as UrlsConnectionError + +from plugins.action import cloudflare_records_converged as plugin +from plugins.action.cloudflare_records_converged import ActionModule +from utils import PROJECT_ROOT +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any, load_yaml_str +from utils.install.collections import declared_pins +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + +ROLE = PROJECT_ROOT / "roles" / "sys-dns-cloudflare-records" +TOKEN = "cf-secret-token-value" +ZONE = "example.org" +ZONE_ID = "zone-id-1" + + +def rr(rtype, name, content=None, **extra): + record = { + "id": f"{rtype}-{name}-{content}", + "type": rtype, + "name": name, + "ttl": 1, + "comment": None, + "tags": [], + } + if content is not None: + record["content"] = content + if rtype in ("A", "AAAA", "CNAME"): + record["proxied"] = False + record.update(extra) + return record + + +class _Answer: + def __init__(self, payload): + self.payload = payload + + def read(self): + return json.dumps(self.payload).encode() + + +class _FakeCloudflare: + def __init__(self, pages, zones=None, error=None): + self.pages = pages + self.zones = [{"id": ZONE_ID, "name": ZONE}] if zones is None else zones + self.error = error + self.calls = [] + + def __call__(self, url, method, headers, timeout): + self.calls.append( + {"url": url, "method": method, "headers": headers, "timeout": timeout} + ) + if self.error is not None: + raise self.error + parts = urlsplit(url) + query = parse_qs(parts.query) + if parts.path.endswith("/zones"): + return _Answer( + { + "success": True, + "result": [z for z in self.zones if z["name"] == query["name"][0]], + } + ) + page = int(query["page"][0]) + return _Answer( + { + "success": True, + "result": self.pages[page - 1], + "result_info": {"page": page, "total_pages": len(self.pages)}, + } + ) + + +def run_split(records, cloudflare): + with patch.object(plugin, "open_url", side_effect=cloudflare): + return plugin.split(records, TOKEN, 20) + + +def a(name, content="203.0.113.7", **extra): + return {"type": "A", "zone": ZONE, "name": name, "content": content, **extra} + + +def cname(name, target): + return {"type": "CNAME", "zone": ZONE, "name": name, "value": target} + + +def srv(service, port, **extra): + return { + "type": "SRV", + "zone": ZONE, + "name": ZONE, + "service": service, + "proto": "_tcp", + "priority": 20, + "weight": 1, + "port": port, + "value": "Mail.Example.org.", + **extra, + } + + +def srv_rr(service, port, priority=20, target="mail.example.org", **extra): + return rr( + "SRV", + f"{service}._tcp.{ZONE}", + priority=priority, + data={"target": target, "port": port, "weight": 1, "priority": priority}, + **extra, + ) + + +class TestCloudflareRecordsConverged(unittest.TestCase): + def test_converged_records_cost_one_zone_read_whatever_their_number(self): + records = [a(f"*.app{i}") for i in range(20)] + [ + {"type": "AAAA", "zone": ZONE, "name": "*", "content": "2001:DB8::7"} + ] + zone = [rr("A", f"*.app{i}.{ZONE}", "203.0.113.7") for i in range(20)] + zone.append(rr("AAAA", f"*.{ZONE}", "2001:db8::7")) + cloudflare = _FakeCloudflare([zone]) + + pending, labels, warnings = run_split(records, cloudflare) + + self.assertEqual(pending, []) + self.assertEqual(len(labels), 21) + self.assertEqual(warnings, []) + self.assertEqual(len(cloudflare.calls), 2) + self.assertTrue(all(c["method"] == "GET" for c in cloudflare.calls)) + self.assertTrue(all(c["timeout"] == 20 for c in cloudflare.calls)) + self.assertTrue(all(TOKEN not in c["url"] for c in cloudflare.calls)) + self.assertEqual( + cloudflare.calls[0]["headers"]["Authorization"], f"Bearer {TOKEN}" + ) + + def test_every_drift_the_module_would_write_keeps_the_record_pending(self): + drifts = { + "missing": [], + "other content": [rr("A", f"www.{ZONE}", "203.0.113.8")], + "ttl": [rr("A", f"www.{ZONE}", "203.0.113.7", ttl=300)], + "proxied": [rr("A", f"www.{ZONE}", "203.0.113.7", proxied=True)], + "proxied unknown": [ + { + k: v + for k, v in rr("A", f"www.{ZONE}", "203.0.113.7").items() + if k != "proxied" + } + ], + "comment": [rr("A", f"www.{ZONE}", "203.0.113.7", comment="hand made")], + "comment unknown": [ + { + k: v + for k, v in rr("A", f"www.{ZONE}", "203.0.113.7").items() + if k != "comment" + } + ], + "tags": [rr("A", f"www.{ZONE}", "203.0.113.7", tags=["team:ops"])], + "priority": [rr("A", f"www.{ZONE}", "203.0.113.7", priority=5)], + "duplicate": [ + rr("A", f"www.{ZONE}", "203.0.113.7"), + rr("A", f"www.{ZONE}", "203.0.113.7", id="second"), + ], + } + for drift, zone in drifts.items(): + with self.subTest(drift=drift): + record = a("www") + pending, labels, _ = run_split([record], _FakeCloudflare([zone])) + self.assertEqual(pending, [record]) + self.assertEqual(labels, []) + + def test_a_record_matches_the_declared_proxied_and_ttl(self): + record = a("www", proxied=True, ttl="1") + zone = [rr("A", f"www.{ZONE}", "203.0.113.7", proxied=True)] + + pending, labels, _ = run_split([record], _FakeCloudflare([zone])) + + self.assertEqual(pending, []) + self.assertEqual(labels, [f"A www.{ZONE}"]) + + def test_solo_record_stays_pending_while_another_record_shares_its_name(self): + record = a("mail", solo=True) + alone = [rr("A", f"mail.{ZONE}", "203.0.113.7")] + crowded = [*alone, rr("A", f"mail.{ZONE}", "198.51.100.1")] + + self.assertEqual(run_split([record], _FakeCloudflare([alone]))[0], []) + self.assertEqual(run_split([record], _FakeCloudflare([crowded]))[0], [record]) + self.assertEqual(run_split([a("mail")], _FakeCloudflare([crowded]))[0], []) + + def test_cname_is_normalized_like_the_module_and_compared_by_target(self): + record = { + "type": "CNAME", + "zone": ZONE, + "name": "autoconfig", + "value": "Mail.Example.org.", + "proxied": True, + } + held = [rr("CNAME", f"autoconfig.{ZONE}", "mail.example.org")] + moved = [rr("CNAME", f"autoconfig.{ZONE}", "other.example.org")] + proxied = [rr("CNAME", f"autoconfig.{ZONE}", "mail.example.org", proxied=True)] + + self.assertEqual(run_split([record], _FakeCloudflare([held]))[0], []) + self.assertEqual(run_split([record], _FakeCloudflare([moved]))[0], [record]) + self.assertEqual(run_split([record], _FakeCloudflare([proxied]))[0], [record]) + + def test_mx_priority_defaults_like_apply_and_is_compared(self): + record = {"type": "MX", "zone": ZONE, "name": "@", "value": "mail.example.org"} + held = [rr("MX", ZONE, "mail.example.org", priority=10)] + other = [rr("MX", ZONE, "mail.example.org", priority=20)] + + self.assertEqual(run_split([record], _FakeCloudflare([held]))[0], []) + self.assertEqual(run_split([record], _FakeCloudflare([other]))[0], [record]) + self.assertEqual( + run_split([dict(record, priority=20)], _FakeCloudflare([other]))[0], [] + ) + + def test_txt_content_is_compared_exactly(self): + record = { + "type": "TXT", + "zone": ZONE, + "name": "_dmarc", + "value": '"v=DMARC1; p=reject"', + "solo": True, + } + held = [rr("TXT", f"_dmarc.{ZONE}", '"v=DMARC1; p=reject"')] + unquoted = [rr("TXT", f"_dmarc.{ZONE}", "v=DMARC1; p=reject")] + recased = [rr("TXT", f"_dmarc.{ZONE}", '"V=DMARC1; p=reject"')] + + self.assertEqual(run_split([record], _FakeCloudflare([held]))[0], []) + self.assertEqual(run_split([record], _FakeCloudflare([unquoted]))[0], [record]) + self.assertEqual(run_split([record], _FakeCloudflare([recased]))[0], [record]) + + def test_srv_is_matched_by_weight_port_target_and_compared_by_data(self): + record = srv("submission", 587, solo=True) + cases = { + "held": ([srv_rr("_submission", 587)], []), + "priority": ([srv_rr("_submission", 587, priority=10)], [record]), + "port": ([srv_rr("_submission", 465)], [record]), + "ambiguous": ( + [ + srv_rr("_submission", 587), + srv_rr("_submission", 587, priority=30, id="b"), + ], + [record], + ), + "stale data keys": ( + [ + dict( + srv_rr("_submission", 587), + data={ + "target": "mail.example.org", + "port": 587, + "weight": 1, + "priority": 20, + "service": "_submission", + }, + ) + ], + [record], + ), + } + for case, (zone, want) in cases.items(): + with self.subTest(case=case): + self.assertEqual(run_split([record], _FakeCloudflare([zone]))[0], want) + + def test_records_outside_the_judged_shapes_stay_pending_without_a_read(self): + records = [ + a("gone", state="absent"), + {"type": "CAA", "zone": ZONE, "name": "@", "value": "letsencrypt.org"}, + {"type": "A", "zone": ZONE, "name": "www"}, + a("www", ttl=None), + a("www", proxied="perhaps"), + {k: v for k, v in srv("imaps", 993).items() if k != "port"}, + "not a record", + ] + cloudflare = _FakeCloudflare([[]]) + + pending, labels, warnings = run_split(records, cloudflare) + + self.assertEqual(pending, records) + self.assertEqual(labels, []) + self.assertEqual(warnings, []) + self.assertEqual(cloudflare.calls, []) + + def test_an_unreadable_zone_leaves_its_records_to_the_module_and_warns_without_the_token( + self, + ): + records = [a("www"), a("api")] + error = HTTPError( + f"{plugin.API}/zones?name={ZONE}", 429, "Too Many Requests", {}, None + ) + cloudflare = _FakeCloudflare([[]], error=error) + + pending, labels, warnings = run_split(records, cloudflare) + + self.assertEqual(pending, records) + self.assertEqual(labels, []) + self.assertEqual(len(warnings), 1) + self.assertIn(ZONE, warnings[0]) + self.assertIn("429", warnings[0]) + self.assertNotIn(TOKEN, warnings[0]) + self.assertEqual(len(cloudflare.calls), 1) + + def test_every_transport_failure_leaves_the_records_to_the_module(self): + for error in ( + IncompleteRead(b""), + TimeoutError("timed out"), + URLError("refused"), + UrlsConnectionError("tls"), + ): + with self.subTest(error=type(error).__name__): + record = a("www") + pending, _, warnings = run_split( + [record], _FakeCloudflare([[]], error=error) + ) + self.assertEqual(pending, [record]) + self.assertEqual(len(warnings), 1) + + def test_a_zone_name_without_exactly_one_zone_leaves_its_records_to_the_module( + self, + ): + record = a("www") + pending, _, warnings = run_split([record], _FakeCloudflare([[]], zones=[])) + + self.assertEqual(pending, [record]) + self.assertIn("0 Cloudflare zones match example.org", warnings[0]) + + def test_an_answer_without_success_leaves_its_records_to_the_module(self): + record = a("www") + with patch.object( + plugin, + "open_url", + side_effect=lambda *args, **kwargs: _Answer( + {"success": False, "errors": [{"code": 10000}]} + ), + ): + pending, _, warnings = plugin.split([record], TOKEN, 20) + + self.assertEqual(pending, [record]) + self.assertIn("10000", warnings[0]) + self.assertNotIn(TOKEN, warnings[0]) + + def test_every_page_of_the_zone_is_read(self): + record = a("late") + pages = [ + [rr("A", f"early{i}.{ZONE}", "203.0.113.7") for i in range(3)], + [rr("A", f"late.{ZONE}", "203.0.113.7")], + ] + cloudflare = _FakeCloudflare(pages) + + pending, labels, _ = run_split([record], cloudflare) + + self.assertEqual(pending, []) + self.assertEqual(labels, [f"A late.{ZONE}"]) + self.assertEqual(len(cloudflare.calls), 3) + + def test_each_zone_is_read_once_and_order_is_kept(self): + other = { + "type": "A", + "zone": "Other.NET", + "name": "www", + "content": "203.0.113.7", + } + records = [a("one"), other, a("two")] + zones = [ + {"id": ZONE_ID, "name": ZONE}, + {"id": "zone-id-2", "name": "other.net"}, + ] + cloudflare = _FakeCloudflare( + [[rr("A", f"two.{ZONE}", "203.0.113.7")]], zones=zones + ) + + pending, labels, _ = run_split(records, cloudflare) + + self.assertEqual(pending, [records[0], other]) + self.assertEqual(labels, [f"A two.{ZONE}"]) + self.assertEqual(len(cloudflare.calls), 4) + + def test_fields_the_module_rejects_as_int_stay_pending(self): + held = [rr("A", f"www.{ZONE}", "203.0.113.7")] + for ttl in (1.5, "1.5", True, "one"): + with self.subTest(ttl=ttl): + record = a("www", ttl=ttl) + pending, labels, _ = run_split([record], _FakeCloudflare([held])) + self.assertEqual(pending, [record]) + self.assertEqual(labels, []) + for ttl in (1, "1", 1.0, "1.0"): + with self.subTest(ttl=ttl): + record = a("www", ttl=ttl) + self.assertEqual(run_split([record], _FakeCloudflare([held]))[0], []) + mx = {"type": "MX", "zone": ZONE, "name": "@", "value": "mail.example.org"} + mx_held = [rr("MX", ZONE, "mail.example.org", priority=10)] + for priority in (10.5, False): + with self.subTest(priority=priority): + record = dict(mx, priority=priority) + pending, _, _ = run_split([record], _FakeCloudflare([mx_held])) + self.assertEqual(pending, [record]) + record = srv("submission", 587.5) + zone = [srv_rr("_submission", 587)] + self.assertEqual(run_split([record], _FakeCloudflare([zone]))[0], [record]) + + def test_a_name_with_a_solo_entry_and_another_entry_stays_pending(self): + records = [a("h", "192.0.2.1", solo=True), a("h", "192.0.2.2")] + both = [rr("A", f"h.{ZONE}", "192.0.2.1"), rr("A", f"h.{ZONE}", "192.0.2.2")] + for held in (both, both[:1], both[1:]): + with self.subTest(held=[r["content"] for r in held]): + pending, labels, _ = run_split(records, _FakeCloudflare([held])) + self.assertEqual(pending, records) + self.assertEqual(labels, []) + + def test_a_name_another_entry_deletes_from_stays_pending(self): + held = [rr("A", f"h.{ZONE}", "192.0.2.1")] + records = [a("h", "192.0.2.1"), a("h", "192.0.2.1", state="absent")] + + pending, labels, _ = run_split(records, _FakeCloudflare([held])) + + self.assertEqual(pending, records) + self.assertEqual(labels, []) + + def test_a_hazard_on_one_name_or_type_leaves_the_others_judged(self): + records = [ + a("h", "192.0.2.1", solo=True), + a("h", "192.0.2.2"), + a("other"), + {"type": "AAAA", "zone": ZONE, "name": "h", "content": "2001:db8::1"}, + ] + zone = [ + rr("A", f"h.{ZONE}", "192.0.2.1"), + rr("A", f"other.{ZONE}", "203.0.113.7"), + rr("AAAA", f"h.{ZONE}", "2001:db8::1"), + ] + + pending, labels, _ = run_split(records, _FakeCloudflare([zone])) + + self.assertEqual(pending, records[:2]) + self.assertEqual(labels, [f"A other.{ZONE}", f"AAAA h.{ZONE}"]) + + def test_one_record_declared_twice_with_different_settings_stays_pending(self): + x = f"x.{ZONE}" + mx = {"type": "MX", "zone": ZONE, "name": "x", "value": "mx.example.org"} + groups = { + "cname target": ( + [cname("x", "a.example.org"), cname("x", "b.example.org")], + [rr("CNAME", x, "a.example.org")], + [rr("CNAME", x, "b.example.org")], + ), + "a ttl": ( + [a("x", ttl=1), a("x", ttl=300)], + [rr("A", x, "203.0.113.7")], + [rr("A", x, "203.0.113.7", ttl=300)], + ), + "mx priority": ( + [mx, dict(mx, value="MX.example.org.", priority=20)], + [rr("MX", x, "mx.example.org", priority=10)], + [rr("MX", x, "mx.example.org", priority=20)], + ), + } + for group, (records, *held) in groups.items(): + for zone in held: + with self.subTest(group=group, held=zone): + pending, labels, _ = run_split(records, _FakeCloudflare([zone])) + self.assertEqual(pending, records) + self.assertEqual(labels, []) + + def test_entries_of_one_name_the_module_edits_as_distinct_or_equal_records_stay_judged( + self, + ): + x = f"x.{ZONE}" + groups = { + "distinct a": ( + [a("x", "192.0.2.1"), a("x", "192.0.2.2", ttl=300)], + [rr("A", x, "192.0.2.1"), rr("A", x, "192.0.2.2", ttl=300)], + ), + "distinct srv": ( + [srv("submission", 587), srv("submission", 465, priority=10)], + [ + srv_rr("_submission", 587), + srv_rr("_submission", 465, priority=10, id="b"), + ], + ), + "equal a": ( + [a("x", ttl=1), a("x", ttl="1")], + [rr("A", x, "203.0.113.7")], + ), + } + for group, (records, zone) in groups.items(): + with self.subTest(group=group): + pending, labels, _ = run_split(records, _FakeCloudflare([zone])) + self.assertEqual(pending, []) + self.assertEqual(len(labels), 2) + + def test_txt_held_both_quoted_and_unquoted_stays_pending(self): + record = { + "type": "TXT", + "zone": ZONE, + "name": "_dmarc", + "value": '"v=DMARC1; p=reject"', + } + quoted = rr("TXT", f"_dmarc.{ZONE}", '"v=DMARC1; p=reject"') + unquoted = rr("TXT", f"_dmarc.{ZONE}", "v=dmarc1; p=reject", id="unquoted") + other = rr("TXT", f"_dmarc.{ZONE}", '"v=spf1 -all"', id="spf") + + self.assertEqual( + run_split([record], _FakeCloudflare([[quoted, unquoted]]))[0], [record] + ) + self.assertEqual(run_split([record], _FakeCloudflare([[quoted, other]]))[0], []) + + +class _FakeTask: + def __init__(self, args): + self.args = args + + +def _action(args): + action = object.__new__(ActionModule) + action._task = _FakeTask(args) + return action + + +class TestCloudflareRecordsConvergedAction(unittest.TestCase): + def test_run_returns_pending_and_converged_without_change(self): + record = a("www") + cloudflare = _FakeCloudflare([[rr("A", f"www.{ZONE}", "203.0.113.7")]]) + action = _action( + {"api_token": TOKEN, "records": [record, a("api")], "timeout": "20"} + ) + with ( + patch( + "plugins.action.cloudflare_records_converged.ActionBase.run", + autospec=True, + return_value={}, + ), + patch.object(plugin, "open_url", side_effect=cloudflare), + ): + result = action.run(task_vars={}) + + self.assertFalse(result["changed"]) + self.assertEqual(result["pending"], [a("api")]) + self.assertEqual(result["converged"], [f"A www.{ZONE}"]) + self.assertNotIn("warnings", result) + self.assertNotIn(TOKEN, json.dumps(result)) + + def test_run_rejects_wrong_arguments(self): + for args in ( + {"records": [], "timeout": 20}, + {"api_token": TOKEN, "records": [], "timeout": 20, "zone": ZONE}, + {"api_token": TOKEN, "records": "a", "timeout": 20}, + {"api_token": TOKEN, "records": [], "timeout": "soon"}, + ): + with ( + self.subTest(args=sorted(args)), + patch( + "plugins.action.cloudflare_records_converged.ActionBase.run", + autospec=True, + return_value={}, + ), + self.assertRaises(AnsibleActionFail), + ): + _action(args).run(task_vars={}) + + +def _task(tasks, name): + return next(t for t in tasks if t.get("name") == name) + + +class TestApplyDefaultsMatchThePlugin(unittest.TestCase): + def test_the_defaults_apply_hands_the_module_are_the_ones_the_plugin_predicts(self): + tasks = load_yaml_any(str(ROLE / "tasks" / "apply.yml")) + a_args = _task(tasks, "📌 Apply A/AAAA")["community.general.cloudflare_dns"] + cname_args = _task(tasks, "📌 Apply CNAME/MX/TXT")[ + "community.general.cloudflare_dns" + ] + srv_args = _task(tasks, "📌 Apply SRV")["community.general.cloudflare_dns"] + + def default(text, field): + match = re.search(rf"item\.{field} \| default\(([^)]*)\)", text) + self.assertIsNotNone(match, f"{field} default not found in {text!r}") + return load_yaml_str(match.group(1)) + + for args in (a_args, cname_args, srv_args): + self.assertEqual(default(args["ttl"], "ttl"), plugin.APPLY_TTL) + self.assertEqual(default(args["state"], "state"), plugin.APPLY_STATE) + self.assertEqual(default(args["solo"], "solo"), plugin.APPLY_SOLO) + self.assertEqual(default(a_args["proxied"], "proxied"), plugin.APPLY_PROXIED) + self.assertEqual( + default(cname_args["priority"], "priority"), plugin.APPLY_MX_PRIORITY + ) + self.assertIn("omit", cname_args["priority"]) + self.assertNotIn("priority", a_args) + self.assertNotIn("proxied", cname_args) + self.assertNotIn("proxied", srv_args) + self.assertEqual(srv_args["priority"], "{{ item.priority }}") + self.assertEqual(a_args["content"], "{{ item.content }}") + self.assertEqual(cname_args["value"], "{{ item.value }}") + self.assertEqual(srv_args["value"], "{{ item.value }}") + + def test_the_first_attempt_queues_only_what_the_plugin_left_pending(self): + tasks = load_yaml_any(str(ROLE / ROLE_FILE_TASKS_MAIN)) + names = [t.get("name") for t in tasks] + check = next(t for t in tasks if "cloudflare_records_converged" in t) + queue = next( + t for t in tasks if "_cf_pending" in t.get("ansible.builtin.set_fact", {}) + ) + + self.assertEqual( + check["cloudflare_records_converged"]["records"], "{{ cloudflare_records }}" + ) + self.assertEqual(check["register"], "_cf_converged") + self.assertIn("cloudflare_no_log", check["no_log"]) + self.assertEqual( + queue["ansible.builtin.set_fact"]["_cf_pending"], + "{{ _cf_converged.pending }}", + ) + self.assertLess(names.index(check["name"]), names.index(queue["name"])) + + +def _resolved_community_general() -> Path: + """ + Returns: + The community.general directory of the first ``collections_paths`` + entry of the repository's ansible.cfg that holds one, as Ansible + resolves it. + """ + config = configparser.ConfigParser(interpolation=None, strict=False) + config.read(PROJECT_ROOT / "ansible.cfg", encoding="utf-8") + for entry in config.get("defaults", "collections_paths").split(":"): + base = Path(entry).expanduser() + if not base.is_absolute(): + base = PROJECT_ROOT / base + candidate = base / "ansible_collections" / "community" / "general" + if (candidate / "plugins" / "modules" / "cloudflare_dns.py").is_file(): + return candidate + raise AssertionError("no collections_paths entry holds community.general") + + +def _argument_spec_defaults(module: Path) -> dict: + """ + Args: + module: path of an Ansible module source file. + + Returns: + ``{option: default}`` for every option of the module's + ``argument_spec`` that declares a literal default. + """ + tree = ast.parse(read_text(str(module))) + for node in ast.walk(tree): + if isinstance(node, ast.keyword) and node.arg == "argument_spec": + defaults = {} + for option in node.value.keywords: + fields = {k.arg: k.value for k in option.value.keywords} + if "default" in fields: + defaults[option.arg] = ast.literal_eval(fields["default"]) + return defaults + raise AssertionError(f"no argument_spec in {module}") + + +class TestModuleDefaultsMatchThePlugin(unittest.TestCase): + def test_the_module_defaults_the_plugin_predicts_match_the_resolved_collection( + self, + ): + collection = _resolved_community_general() + manifest = json.loads(read_text(str(collection / "MANIFEST.json"))) + defaults = _argument_spec_defaults( + collection / "plugins" / "modules" / "cloudflare_dns.py" + ) + + self.assertEqual( + manifest["collection_info"]["version"], plugin.REVIEWED_COMMUNITY_GENERAL + ) + self.assertEqual(defaults["priority"], plugin.MODULE_PRIORITY) + self.assertEqual(defaults["proxied"], plugin.MODULE_PROXIED) + + def test_a_new_community_general_pin_forces_a_review_of_the_plugin(self): + pins = dict( + declared_pins(PROJECT_ROOT / "requirements" / "requirements.galaxy.yml") + ) + + self.assertEqual(pins["community.general"], plugin.REVIEWED_COMMUNITY_GENERAL) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_proxy_pass.py b/tests/unit/python/plugins/lookup/test_proxy_pass.py index 50fef86655..0d6f30e8d3 100644 --- a/tests/unit/python/plugins/lookup/test_proxy_pass.py +++ b/tests/unit/python/plugins/lookup/test_proxy_pass.py @@ -29,6 +29,13 @@ def _apps() -> dict[str, Any]: }, }, }, + "web-svc-logout": { + "services": { + "logout": { + "ports": {"local": {"http": 8048}, "internal": {"http": 8000}}, + }, + }, + }, } @@ -194,6 +201,35 @@ class TestProxyPassLookup(unittest.TestCase): ) self.assertEqual(out[0], "proxy_pass http://127.0.0.1:8021/;") + def test_a_forced_scope_leaves_a_foreign_app_at_the_cluster_mode(self): + out = _run( + ["web-svc-logout", "logout", "http"], + variables={ + "DEPLOYMENT_MODE": "swarm", + "compose_mode_force": "compose", + "application_id": "web-app-baserow", + }, + tail="/logout", + ) + self.assertEqual( + out[0], + 'set $proxy_pass_upstream "logout:8000";\n' + " proxy_pass http://$proxy_pass_upstream/logout;", + ) + + def test_a_forced_scope_still_forces_its_own_app(self): + out = _run( + ["web-app-baserow", "application", "http"], + variables={ + "DEPLOYMENT_MODE": "swarm", + "compose_mode_force": "compose", + "application_id": "web-app-baserow", + }, + tail="request", + location="/", + ) + self.assertEqual(out[0], "proxy_pass http://127.0.0.1:8017/;") + def test_resolution_error_becomes_ansible_error(self): lm = LookupModule() lm._templar = _Templar({"DEPLOYMENT_MODE": "swarm"}) diff --git a/tests/unit/python/roles/sys-dns-cloudflare-records/__init__.py b/tests/unit/python/roles/sys-dns-cloudflare-records/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-dns-cloudflare-records/test_collect_polling.py b/tests/unit/python/roles/sys-dns-cloudflare-records/test_collect_polling.py new file mode 100644 index 0000000000..dc59c12755 --- /dev/null +++ b/tests/unit/python/roles/sys-dns-cloudflare-records/test_collect_polling.py @@ -0,0 +1,76 @@ +import unittest + +from jinja2 import Environment, StrictUndefined + +from plugins.lookup.timeout import scaled_timeout +from utils import PROJECT_ROOT +from utils.cache.yaml import load_yaml, load_yaml_any +from utils.roles.mapping import ROLE_FILE_DEFAULTS_MAIN + +ROLE = PROJECT_ROOT / "roles" / "sys-dns-cloudflare-records" + + +def _defaults() -> dict: + return load_yaml(str(ROLE / ROLE_FILE_DEFAULTS_MAIN)) + + +def _collect_task() -> dict: + return next( + task + for task in load_yaml_any(str(ROLE / "tasks" / "judge.yml")) + if "ansible.builtin.async_status" in task + ) + + +def _render(expression: str, variables: dict, factor: int): + """ + Args: + expression: one templated value of the role. + variables: the role defaults the expression may read. + factor: the ``TIMEOUT_FACTOR`` the ``timeout`` lookup scales by. + + Returns: + The rendered value as an integer. + """ + environment = Environment(undefined=StrictUndefined, autoescape=True) + environment.globals["lookup"] = lambda name, base: scaled_timeout(base, factor) + return int(environment.from_string(str(expression)).render(**variables)) + + +class TestCollectPolling(unittest.TestCase): + def test_collect_polls_at_the_role_interval_and_retries_by_it(self): + defaults = _defaults() + task = _collect_task() + + self.assertEqual(task["delay"], "{{ cloudflare_collect_interval | int }}") + self.assertEqual(task["retries"], "{{ cloudflare_collect_retries | int }}") + self.assertIn( + "cloudflare_collect_interval", defaults["cloudflare_collect_retries"] + ) + self.assertIn("_cf_collect_deadline", task["until"]) + + def test_the_polling_window_covers_the_attempt_timeout(self): + defaults = _defaults() + task = _collect_task() + for factor in (1, 2, 3): + for interval in (1, 2, 5, 7): + with self.subTest(factor=factor, interval=interval): + variables = dict(defaults, cloudflare_collect_interval=interval) + variables["cloudflare_collect_retries"] = _render( + defaults["cloudflare_collect_retries"], variables, factor + ) + retries = _render(task["retries"], variables, factor) + delay = _render(task["delay"], variables, factor) + attempt = scaled_timeout( + defaults["cloudflare_attempt_timeout"], factor + ) + + self.assertEqual(delay, interval) + self.assertGreaterEqual(retries * delay, attempt) + + def test_the_default_interval_is_one_second(self): + self.assertEqual(_defaults()["cloudflare_collect_interval"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py b/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py new file mode 100644 index 0000000000..7ddf59ce82 --- /dev/null +++ b/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py @@ -0,0 +1,298 @@ +from __future__ import annotations + +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from unittest import mock + +from ansible.errors import AnsibleUndefinedVariable +from ansible.parsing.dataloader import DataLoader +from ansible.plugins.loader import filter_loader, lookup_loader +from ansible.plugins.lookup import LookupBase +from ansible.template import Templar, trust_as_template + +from plugins.lookup.cdn import _cdn_paths, _to_url_tree +from plugins.lookup.tls import LookupModule as TlsLookup +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any, load_yaml_str +from utils.domains.default_primary import default_domain_primary +from utils.networks.reachability import CLEARNET, TOR, network_of +from utils.roles.mapping import ( + ROLE_FILE_DEFAULTS_MAIN, + ROLE_FILE_TASKS_MAIN, + ROLE_FILE_VARS_MAIN, +) + +filter_loader.add_directory(str(PROJECT_ROOT / "plugins" / "filter")) + +DESIGN_DIR = PROJECT_ROOT / "roles" / "sys-front-inj-design" +TASKS = DESIGN_DIR / ROLE_FILE_TASKS_MAIN +DOMAIN = default_domain_primary() +ONION = "a" * 56 + ".onion" +CDN_ROOT = "/nonexistent/infinito/cdn" +CDN_BASE = {CLEARNET: f"https://cdn.{DOMAIN}", TOR: f"http://cdn.{ONION}"} +APPS = ( + "web-svc-logout", + "web-app-openbao", + "web-app-xwiki", + "web-app-mastodon", + "web-app-wordpress", +) + +LEGACY_OVERLAY = load_yaml_str( + r""" +- vars: + _app_style_css: >- + {{ (lookup('template', _app_compose_src) | trim | replace(_cdn_origin, '/')) + if (app_body_css ~ app_logo_css) | length > 0 else '' }} + set_fact: + app_style_present: "{{ _app_style_css | length > 0 }}" +- vars: + _design_configured: "{{ 'INFINITO_DESIGN' in design_body_js }}" + _design_js: >- + {{ (lookup('template', _design_compose_src) | trim) + if _design_configured | bool else design_body_js }} + set_fact: + design_config_json: "{{ (lookup('template', _design_config_src) | trim) if _design_configured | bool else '' }}" + design_js_one_liner: "{{ (_design_js | to_one_liner) if _design_js | length > 0 else '' }}" +""" +) + + +class _Stub(LookupBase): + def __init__(self, answer): + super().__init__() + self._answer = answer + + def run(self, terms, variables=None, **kwargs): + return [self._answer(variables or {}, *terms)] + + +def _cdn(variables, application_id): + base = CDN_BASE[network_of(variables["domain"])] + paths = _cdn_paths(CDN_ROOT, application_id, "latest") + return {**paths, "urls": _to_url_tree(paths, paths["root"], base)} + + +def _design(logo): + def answer(variables, application_id): + base = _cdn(variables, application_id)["urls"]["role"]["release"]["img"] + return { + "logo": "/repo/logo.svg" if logo else False, + "title": "Brand" if logo else False, + "slots": {"header": {"width": 120, "height": 40}}, + "urls": { + "favicon_ico": f"{base}/design/favicon.ico", + "header": {"png": f"{base}/design/header.png"}, + }, + } + + return answer + + +def resolve_tasks(): + """Return the two resolve tasks of the role as loaded from disk. + + Returns: + ``[style_task, script_task]`` in file order. + """ + tasks = load_yaml_any(str(TASKS)) + return [t for t in tasks if str(t.get("name", "")).startswith("🔍 Resolve")] + + +def legacy_tasks(): + """Return the resolve tasks with their pre-change expressions restored. + + Returns: + ``[style_task, script_task]`` with the legacy vars and facts overlaid. + """ + legacy = [] + for task, overlay in zip(resolve_tasks(), LEGACY_OVERLAY, strict=True): + legacy.append( + { + **task, + "vars": {**task["vars"], **overlay["vars"]}, + "set_fact": {**task["set_fact"], **overlay["set_fact"]}, + } + ) + return legacy + + +def _trusted(value): + if isinstance(value, str): + return trust_as_template(value) + if isinstance(value, dict): + return {key: _trusted(item) for key, item in value.items()} + return value + + +def run_tasks(tasks, app, vhost, logo, root=PROJECT_ROOT): + """Template the set_fact arguments of both resolve tasks in order. + + Args: + tasks: the two resolve tasks, current or legacy. + app: the application_id being injected. + vhost: the vhost being rendered, clearnet or onion. + logo: whether the branding replaces the logo and title. + root: the playbook directory the role paths resolve against. + + Returns: + ``(facts, renders)``: the facts both tasks set and, per task, a + ``Counter`` of rendered template paths relative to ``root``. + """ + tree = {app: [f"x.app.{DOMAIN}", f"x.app.{ONION}"]} + stubs = { + "domains": lambda _v, *terms: tree[terms[0]] if terms else tree, + "cdn": _cdn, + "design": _design(logo), + } + renders: list[Counter] = [] + real_get = lookup_loader.get + + def get(name, *args, **kwargs): + if name == "tls": + lookup = TlsLookup() + lookup._loader = kwargs.get("loader") + lookup._templar = None + return lookup + if name in stubs: + return _Stub(stubs[name]) + plugin = real_get(name, *args, **kwargs) + if name == "template": + original = plugin.run + + def counted(terms, variables=None, **options): + renders[-1].update(str(Path(t).relative_to(root)) for t in terms) + return original(terms, variables=variables, **options) + + plugin.run = counted + return plugin + + loader = DataLoader() + variables = { + **loader.load_from_file( + str(DESIGN_DIR / ROLE_FILE_DEFAULTS_MAIN), trusted_as_template=True + ), + **loader.load_from_file( + str(DESIGN_DIR / ROLE_FILE_VARS_MAIN), trusted_as_template=True + ), + } + app_vars = PROJECT_ROOT / "roles" / app / ROLE_FILE_VARS_MAIN + if app == "web-app-xwiki": + xwiki = loader.load_from_file(str(app_vars), trusted_as_template=True) + variables.update(XWIKI_URL=xwiki["XWIKI_URL"], XWIKI_CORE_VERSION="0.0.0") + variables.update( + playbook_dir=str(root), + application_id=app, + domain=vhost, + TLS_ENABLED=True, + TLS_MODE="letsencrypt", + design_css_states={}, + ) + facts: dict = {} + with mock.patch.object(lookup_loader, "get", side_effect=get): + for task in tasks: + renders.append(Counter()) + scope = {**variables, **facts, **_trusted(task["vars"])} + templar = Templar(loader=DataLoader(), variables=scope) + facts.update(templar.template(_trusted(task["set_fact"]))) + return facts, renders + + +VARIANTS = [ + (app, vhost, logo) + for app in APPS + for vhost in (f"x.app.{DOMAIN}", f"x.app.{ONION}") + for logo in (True, False) +] + +STYLE = "roles/web-svc-logout/files/style.css" +APP_CSS = "roles/sys-front-inj-design/templates/css/app.css.j2" +SCRIPT = "roles/web-svc-logout/templates/design.js.j2" +DESIGN_JS = "roles/sys-front-inj-design/templates/js/design.js.j2" +CONFIG = "roles/sys-front-inj-design/templates/js/design-config.json.j2" + + +class TestFactsMatchThePreviousExpressions(unittest.TestCase): + def test_every_variant_sets_byte_identical_facts(self) -> None: + current, legacy = resolve_tasks(), legacy_tasks() + for app, vhost, logo in VARIANTS: + with self.subTest(app=app, vhost=vhost, logo=logo): + facts, _ = run_tasks(current, app, vhost, logo) + expected, _ = run_tasks(legacy, app, vhost, logo) + self.assertEqual(facts, expected) + self.assertEqual( + {k: type(v) for k, v in facts.items()}, + {k: type(v) for k, v in expected.items()}, + ) + + def test_the_variants_cover_sheet_logo_script_and_neither(self) -> None: + seen = {} + for app in APPS: + facts, _ = run_tasks(resolve_tasks(), app, f"x.app.{ONION}", True) + seen[app] = ( + facts["app_style_present"], + bool(facts["design_config_json"]), + bool(facts["design_js_one_liner"]), + ) + self.assertEqual(seen["web-app-wordpress"], (False, False, False)) + self.assertEqual(seen["web-app-mastodon"], (False, False, True)) + self.assertEqual(seen["web-svc-logout"], (True, True, True)) + self.assertTrue(seen["web-app-xwiki"][0]) + + def test_the_onion_sheet_names_no_clearnet_vhost(self) -> None: + facts, _ = run_tasks(resolve_tasks(), "web-app-xwiki", f"x.app.{ONION}", False) + self.assertIn(f"http://x.app.{ONION}/resources/icons/", facts["app_style_css"]) + self.assertNotIn(f"x.app.{DOMAIN}", facts["app_style_css"]) + + +class TestEachTemplateRendersOncePerFact(unittest.TestCase): + def test_the_composed_sheet_and_script_render_once(self) -> None: + _, renders = run_tasks( + resolve_tasks(), "web-svc-logout", f"x.app.{DOMAIN}", True + ) + self.assertEqual(renders[0], Counter({STYLE: 2, APP_CSS: 1})) + self.assertEqual(renders[1], Counter({SCRIPT: 2, DESIGN_JS: 1, CONFIG: 1})) + + def test_the_previous_expressions_render_repeatedly(self) -> None: + _, renders = run_tasks( + legacy_tasks(), "web-svc-logout", f"x.app.{DOMAIN}", True + ) + self.assertGreater(renders[0][APP_CSS], 1) + self.assertGreater(renders[0][STYLE], 2) + self.assertGreater(sum(renders[1].values()), 4) + + +class TestABrokenRoleSheetStaysLoud(unittest.TestCase): + def test_an_undefined_variable_fails_naming_it(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "roles" / "web-app-broken" / "files").mkdir(parents=True) + (root / "roles" / "web-app-broken" / "files" / "style.css").write_text( + "body { color: {{ undefined_in_sheet }}; }\n", encoding="utf-8" + ) + (root / "roles" / "sys-front-inj-design").mkdir(parents=True) + (root / "roles" / "sys-front-inj-design" / "templates").symlink_to( + DESIGN_DIR / "templates" + ) + for label, tasks in ( + ("current", resolve_tasks()), + ("legacy", legacy_tasks()), + ): + with ( + self.subTest(tasks=label), + self.assertRaisesRegex( + AnsibleUndefinedVariable, "undefined_in_sheet" + ), + ): + run_tasks(tasks, "web-app-broken", f"x.app.{DOMAIN}", True, root) + + def test_the_failing_task_names_its_application(self) -> None: + for task in resolve_tasks(): + with self.subTest(task=task["name"]): + self.assertIn("{{ application_id }}", task["name"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-opt-rdr-domains/__init__.py b/tests/unit/python/roles/web-opt-rdr-domains/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/__init__.py b/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/test_template_shallow.py b/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/test_template_shallow.py new file mode 100644 index 0000000000..50894cdf0d --- /dev/null +++ b/tests/unit/python/roles/web-opt-rdr-domains/lookup_plugins/test_template_shallow.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +from ansible.errors import AnsibleError +from ansible.parsing.dataloader import DataLoader +from ansible.plugins.loader import lookup_loader +from ansible.template import Templar, trust_as_template + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-opt-rdr-domains" +PROBE_PLUGIN = """ +from ansible.plugins.lookup import LookupBase + + +class LookupModule(LookupBase): + def run(self, terms, variables, **kwargs): + return [variables["domain"]] +""" +TEMPLATE = "{{ domain }} {{ lookup('rdr_probe_variables_domain') }}\n" + + +class _NoDeepCopy: + def __deepcopy__(self, memo): + raise AssertionError("the variables were deep-copied") + + +class TestTemplateShallow(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls._tmp = tempfile.TemporaryDirectory() + tmp = Path(cls._tmp.name) + (tmp / "plugins").mkdir() + (tmp / "plugins" / "rdr_probe_variables_domain.py").write_text(PROBE_PLUGIN) + (tmp / "templates").mkdir() + (tmp / "templates" / "vhost.j2").write_text(TEMPLATE) + lookup_loader.add_directory(str(ROLE / "lookup_plugins")) + lookup_loader.add_directory(str(tmp / "plugins")) + cls.search_path = [str(tmp)] + + @classmethod + def tearDownClass(cls) -> None: + cls._tmp.cleanup() + + def _variables(self) -> dict: + return {"domain": "play.example", "ansible_search_path": self.search_path} + + def _render(self, plugin: str, variables: dict) -> str: + return Templar(loader=DataLoader(), variables=variables).template( + trust_as_template( + "{{ lookup('" + plugin + "', 'vhost.j2', " + "template_vars={'domain': 'source.example'}) }}" + ) + ) + + def test_a_lookup_inside_the_template_reads_the_per_call_domain(self) -> None: + rendered = self._render("template_shallow", self._variables()) + self.assertEqual(rendered, "source.example source.example\n") + self.assertEqual(rendered, self._render("template", self._variables())) + + def test_the_caller_variables_keep_their_values(self) -> None: + variables = self._variables() + self._render("template_shallow", variables) + self.assertEqual(variables, self._variables()) + + def test_no_value_of_the_caller_is_deep_copied(self) -> None: + variables = {**self._variables(), "untouchable": _NoDeepCopy()} + self.assertEqual( + self._render("template_shallow", variables), + "source.example source.example\n", + ) + with self.assertRaises(AnsibleError) as raised: + self._render("template", variables) + causes = [] + error: BaseException | None = raised.exception + while error is not None: + causes.append(str(error)) + error = error.__cause__ + self.assertTrue(any("deep-copied" in cause for cause in causes), causes) + + +class TestRedirectLoopRendersShallow(unittest.TestCase): + def test_both_files_of_every_source_render_through_template_shallow( + self, + ) -> None: + tasks = load_yaml_any(str(ROLE / ROLE_FILE_TASKS_MAIN)) + [loop_task] = [ + task for task in tasks if "redirect_source" in task.get("vars", {}) + ] + files = loop_task["vars"]["redirect_source"]["files"] + self.assertEqual(files.count("lookup('template_shallow', "), 2) + self.assertNotIn("lookup('template', ", json.dumps(loop_task)) + + +if __name__ == "__main__": + unittest.main()