diff --git a/library/stack_host_contents.py b/library/stack_host_contents.py new file mode 100644 index 0000000000..bba77471f9 --- /dev/null +++ b/library/stack_host_contents.py @@ -0,0 +1,62 @@ +"""Write many files on the stack host in one module call. + +Args: + files: list of ``{path, content}``; each path is written atomically when + its content differs. + mode: file mode applied to every path. + +Returns: + changed_paths: the paths whose content or attributes changed. +""" + +import tempfile +from pathlib import Path + +from ansible.module_utils.basic import AnsibleModule + +ARGUMENT_SPEC = { + "files": { + "type": "list", + "elements": "dict", + "required": True, + "options": { + "path": {"type": "path", "required": True}, + "content": {"type": "str", "required": True}, + }, + }, + "mode": {"type": "raw", "required": True}, +} + + +def write_file(module, path, content, mode): + target = Path(path) + current = None + if target.exists(): + current = target.read_text( + encoding="utf-8" + ) # nocheck: cache-read runs on the managed host, where utils.cache does not exist + changed = current != content + if module.check_mode and current is None: + return changed + if changed and not module.check_mode: + with tempfile.NamedTemporaryFile( + "w", encoding="utf-8", dir=target.parent, delete=False + ) as handle: + handle.write(content) + module.atomic_move(handle.name, str(target)) + file_args = module.load_file_common_arguments({"path": str(target), "mode": mode}) + return module.set_fs_attributes_if_different(file_args, changed) + + +def main(): + module = AnsibleModule(argument_spec=ARGUMENT_SPEC, supports_check_mode=True) + changed_paths = [ + entry["path"] + for entry in module.params["files"] + if write_file(module, entry["path"], entry["content"], module.params["mode"]) + ] + module.exit_json(changed=bool(changed_paths), changed_paths=changed_paths) + + +if __name__ == "__main__": + main() diff --git a/plugins/action/stack_host_contents.py b/plugins/action/stack_host_contents.py new file mode 100644 index 0000000000..8b8a9face4 --- /dev/null +++ b/plugins/action/stack_host_contents.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Any + +from ansible.module_utils.parsing.convert_bool import boolean as _to_bool +from ansible.plugins.action import ActionBase +from ansible.template import trust_as_template + +_IS_STACK_HOST_EXPR = trust_as_template("{{ IS_STACK_HOST | bool }}") + + +class ActionModule(ActionBase): + TRANSFERS_FILES = False + + def run( + self, tmp: Any = None, task_vars: dict[str, Any] | None = None + ) -> dict[str, Any]: + if task_vars is None: + task_vars = {} + + self._templar.available_variables = task_vars + if not _to_bool(self._templar.template(_IS_STACK_HOST_EXPR)): + return { + "changed": False, + "skipped": True, + "skip_reason": "IS_STACK_HOST is false; this host does not own the destination", + } + + result = super().run(tmp, task_vars) + result.update( + self._execute_module( + module_name="stack_host_contents", + module_args=dict(self._task.args), + task_vars=task_vars, + ) + ) + return result diff --git a/roles/sys-front-tls/defaults/main.yml b/roles/sys-front-tls/defaults/main.yml deleted file mode 100644 index fda37c0262..0000000000 --- a/roles/sys-front-tls/defaults/main.yml +++ /dev/null @@ -1,2 +0,0 @@ ---- -HTTPS_REDIRECT_ENABLED: true # If set to false HTTP redirect is disabled diff --git a/roles/sys-front-tls/tasks/01_http.yml b/roles/sys-front-tls/tasks/01_http.yml index 597f04c321..eb3bce0a01 100644 --- a/roles/sys-front-tls/tasks/01_http.yml +++ b/roles/sys-front-tls/tasks/01_http.yml @@ -11,4 +11,3 @@ src: "http.conf.j2" dest: "{{ lookup('nginx', 'files.domain', domain, protocol='http') }}" notify: reload-openresty - when: HTTPS_REDIRECT_ENABLED | bool diff --git a/roles/web-opt-rdr-domains/tasks/main.yml b/roles/web-opt-rdr-domains/tasks/main.yml index 28e34d81a5..a90999de37 100644 --- a/roles/web-opt-rdr-domains/tasks/main.yml +++ b/roles/web-opt-rdr-domains/tasks/main.yml @@ -7,9 +7,62 @@ vars: compose_handlers_flush: true -- name: "📂 Include domains redirects" - include_tasks: redirect-domain.yml - vars: - domain: "{{ item.source }}" - target: "{{ item.target }}" +- name: 🧩 Start the list of redirect sources + ansible.builtin.set_fact: + redirect_sources: [] + +- name: 🧩 Resolve the tls state and render the configuration of every redirect source + ansible.builtin.set_fact: + redirect_sources: "{{ redirect_sources + [redirect_source] }}" loop: "{{ redirect_domain_mappings }}" + vars: + redirect_source_tls: "{{ lookup('tls', item.source, 'enabled') | bool }}" + redirect_source: + domain: "{{ item.source }}" + enabled: "{{ redirect_source_tls }}" + mode: "{{ lookup('tls', item.source, 'mode') }}" + certs: + - "{{ lookup('cert', item.source, 'files.cert') }}" + - "{{ lookup('cert', item.source, 'files.key') }}" + files: >- + {{ [{'path': lookup('nginx', 'files.domain', item.source), + 'content': lookup('template', 'redirect-domain.conf.j2', + template_vars={'domain': item.source, 'target': item.target})}] + + ([{'path': lookup('nginx', 'files.domain', item.source, protocol='http'), + 'content': lookup('template', lookup('path_absolute', 'roles/sys-front-tls/templates/http.conf.j2'), + template_vars={'domain': item.source})}] + if redirect_source_tls else []) }} + +- name: 📂 Include dependency 'sys-ctl-mtn-cert-renew' + include_role: + name: sys-ctl-mtn-cert-renew + when: + - run_once_sys_ctl_mtn_cert_renew is not defined + - redirect_sources | selectattr('enabled') | selectattr('mode', 'equalto', 'letsencrypt') | list | length > 0 + +- name: 📜 TLS | Ensure the certificates of the redirect sources + when: redirect_sources | selectattr('enabled') | list | length > 0 + block: + - name: 🔎 TLS | Find the certificates of the redirect sources + ansible.builtin.find: + paths: "{{ redirect_sources | selectattr('enabled') | map(attribute='certs') | flatten | map('dirname') | unique }}" + patterns: "{{ redirect_sources | selectattr('enabled') | map(attribute='certs') | flatten | map('basename') | unique }}" + follow: true + register: redirect_certs_found + + - name: 📌 TLS | Apply the tls layer for redirect sources without a certificate + include_role: + name: sys-front-tls + vars: + domain: "{{ item }}" + application_id: "{{ item }}" + loop: >- + {{ redirect_sources | selectattr('enabled') + | rejectattr('certs', 'subset', redirect_certs_found.files | map(attribute='path') | list) + | map(attribute='domain') | list }} + +- name: 🌐 Deploy the NGINX redirect and HTTP handler configuration of every source + stack_host_contents: + files: "{{ redirect_sources | map(attribute='files') | flatten }}" + mode: "0644" + notify: reload-openresty diff --git a/roles/web-opt-rdr-domains/tasks/redirect-domain.yml b/roles/web-opt-rdr-domains/tasks/redirect-domain.yml deleted file mode 100644 index 827224ed57..0000000000 --- a/roles/web-opt-rdr-domains/tasks/redirect-domain.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- -- name: "📌 TLS | Apply tls layer" - include_role: - name: sys-front-tls - when: lookup('tls', domain, 'enabled') | bool - vars: - application_id: "{{ domain }}" - -- name: "🌐 Deploying NGINX redirect configuration for '{{ domain }}'" - stack_host_template: - src: redirect-domain.conf.j2 - dest: "{{ lookup('nginx', 'files.domain', domain) }}" - notify: reload-openresty - vars: - application_id: "{{ domain }}" diff --git a/tests/unit/python/library/test_stack_host_contents.py b/tests/unit/python/library/test_stack_host_contents.py new file mode 100644 index 0000000000..c6fbf29eed --- /dev/null +++ b/tests/unit/python/library/test_stack_host_contents.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import importlib.util +import stat +import sys +import tempfile +import unittest +from pathlib import Path +from typing import TYPE_CHECKING + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.testing import patch_module_args + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from types import ModuleType + +sys.path.insert(0, str(PROJECT_ROOT)) + +MODULE_PATH = PROJECT_ROOT / "library" / "stack_host_contents.py" + + +def _load_stack_host_contents() -> ModuleType: + spec = importlib.util.spec_from_file_location( + "library_stack_host_contents", str(MODULE_PATH) + ) + if spec is None or spec.loader is None: + raise ImportError(f"Could not load: {MODULE_PATH}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) # type: ignore[attr-defined] + return mod + + +_MOD = _load_stack_host_contents() + + +class WriteFileTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.path = Path(self._tmp.name) / "redirect.conf" + + def tearDown(self): + self._tmp.cleanup() + + def _module(self, *, check_mode=False): + args = {"files": [], "mode": "0644", "_ansible_check_mode": check_mode} + with patch_module_args(args): + return AnsibleModule( + argument_spec=_MOD.ARGUMENT_SPEC, supports_check_mode=True + ) + + def _write(self, content, *, check_mode=False): + return _MOD.write_file( + self._module(check_mode=check_mode), str(self.path), content, "0644" + ) + + def _mode(self): + return stat.S_IMODE(self.path.stat().st_mode) + + def _content(self): + return self.path.read_text( + encoding="utf-8" + ) # nocheck: cache-read the file under test changes between reads + + def test_creates_missing_file_with_mode(self): + self.assertTrue(self._write("server {}\n")) + self.assertEqual(self._content(), "server {}\n") + self.assertEqual(self._mode(), 0o644) + + def test_unchanged_content_reports_no_change(self): + self._write("server {}\n") + self.assertFalse(self._write("server {}\n")) + + def test_replaces_differing_content(self): + self._write("server {}\n") + self.assertTrue(self._write("server { listen 80; }\n")) + self.assertEqual(self._content(), "server { listen 80; }\n") + + def test_repairs_mode_drift(self): + self._write("server {}\n") + self.path.chmod(0o600) + self.assertTrue(self._write("server {}\n")) + self.assertEqual(self._mode(), 0o644) + + def test_check_mode_reports_without_writing(self): + self.assertTrue(self._write("server {}\n", check_mode=True)) + self.assertFalse(self.path.exists()) + self._write("server {}\n") + self.assertTrue(self._write("other\n", check_mode=True)) + self.assertEqual(self._content(), "server {}\n") + + def test_leaves_no_staging_file_behind(self): + self._write("server {}\n") + self._write("other\n") + self.assertEqual([p.name for p in self.path.parent.iterdir()], [self.path.name]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/action/test_stack_host_contents.py b/tests/unit/python/plugins/action/test_stack_host_contents.py new file mode 100644 index 0000000000..ffbf39da75 --- /dev/null +++ b/tests/unit/python/plugins/action/test_stack_host_contents.py @@ -0,0 +1,62 @@ +import unittest +from unittest.mock import MagicMock, patch + +from plugins.action.stack_host_contents import ActionModule + + +class _FakeTask: + def __init__(self, *, args=None): + self.args = {} if args is None else dict(args) + + +class _FakeTemplar: + def __init__(self, *, is_stack_host=True): + self._is_stack_host = is_stack_host + self.available_variables: dict[str, object] = {} + + def template(self, raw): + return self._is_stack_host + + +_ARGS = {"files": [{"path": "/etc/x.conf", "content": "x"}], "mode": "0644"} + + +def _make_action(task, templar): + action = object.__new__(ActionModule) + action._task = task + action._templar = templar + action._execute_module = MagicMock( + return_value={"changed": True, "changed_paths": ["/etc/x.conf"]} + ) + return action + + +class TestStackHostContents(unittest.TestCase): + def test_skips_silently_on_non_stack_host(self): + action = _make_action(_FakeTask(args=_ARGS), _FakeTemplar(is_stack_host=False)) + + result = action.run(task_vars={}) + + self.assertTrue(result["skipped"]) + self.assertFalse(result["changed"]) + self.assertIn("IS_STACK_HOST", result["skip_reason"]) + action._execute_module.assert_not_called() + + def test_writes_every_file_in_one_module_call_on_stack_host(self): + action = _make_action(_FakeTask(args=_ARGS), _FakeTemplar(is_stack_host=True)) + + with patch( + "plugins.action.stack_host_contents.ActionBase.run", return_value={} + ): + result = action.run(task_vars={"IS_STACK_HOST": True}) + + action._execute_module.assert_called_once_with( + module_name="stack_host_contents", + module_args=_ARGS, + task_vars={"IS_STACK_HOST": True}, + ) + self.assertEqual(result["changed_paths"], ["/etc/x.conf"]) + + +if __name__ == "__main__": + unittest.main()