From ced411d0de89918d4fdbab9ce5adc25784abdbab Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 31 Oct 2026 18:58:00 +0100 Subject: [PATCH] fix(web-app-magento): toggle the two-factor modules only when their state is wrong Magento 2.4.8 wipes generated/ on every module:enable or module:disable, decided by the command name alone, and the role ran the toggle on every deploy. On CI Magento#0's update pass a Prometheus probe rendered a page during that wipe and wrote new generated classes into it, so rmdir failed and the deploy died. The role now reads module:status --enabled first and only flips the modules in the wrong state; on a fresh install the toggle runs before nginx starts routing to PHP, and a real flip also reloads nginx. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-magento/tasks/00_core.yml | 3 - roles/web-app-magento/tasks/01_setup.yml | 7 +- roles/web-app-magento/tasks/02_two_factor.yml | 16 +- .../python/roles/web-app-magento/__init__.py | 0 .../web-app-magento/test_two_factor_toggle.py | 138 ++++++++++++++++++ 5 files changed, 158 insertions(+), 6 deletions(-) create mode 100644 tests/unit/python/roles/web-app-magento/__init__.py create mode 100644 tests/unit/python/roles/web-app-magento/test_two_factor_toggle.py diff --git a/roles/web-app-magento/tasks/00_core.yml b/roles/web-app-magento/tasks/00_core.yml index 671cff08c0..34854d02c9 100644 --- a/roles/web-app-magento/tasks/00_core.yml +++ b/roles/web-app-magento/tasks/00_core.yml @@ -25,9 +25,6 @@ - name: "🏗️ Bootstrap and install Magento" include_tasks: 01_setup.yml - - name: "🔐 Align Magento's two-factor authentication with its flag" - include_tasks: 02_two_factor.yml - - name: "🎨 Apply the corporate design" include_tasks: 03_design.yml diff --git a/roles/web-app-magento/tasks/01_setup.yml b/roles/web-app-magento/tasks/01_setup.yml index 2931c16026..56ce3f88e1 100644 --- a/roles/web-app-magento/tasks/01_setup.yml +++ b/roles/web-app-magento/tasks/01_setup.yml @@ -130,6 +130,9 @@ register: magento_remote_storage changed_when: "'updated' in magento_remote_storage.stdout" +- name: "🔐 Align Magento's two-factor authentication with its flag before nginx routes requests to PHP" + include_tasks: 02_two_factor.yml + - name: "🔄 Reload nginx so it picks up Magento's vhost (compose)" ansible.builtin.shell: >- container exec {{ MAGENTO_NGINX_CONTAINER_ADDRESS }} nginx -s reload @@ -137,7 +140,7 @@ changed_when: magento_nginx_restart_compose.rc == 0 when: - IS_COMPOSE_MODE - - magento_nginx_conf is changed or magento_install is changed + - magento_nginx_conf is changed or magento_install is changed or magento_two_factor is changed - name: "🔄 Restart nginx so it picks up Magento's vhost (swarm)" ansible.builtin.command: >- @@ -148,4 +151,4 @@ timeout: "{{ lookup('timeout', 600) | int }}" when: - IS_SWARM_MODE - - magento_nginx_conf is changed or magento_install is changed + - magento_nginx_conf is changed or magento_install is changed or magento_two_factor is changed diff --git a/roles/web-app-magento/tasks/02_two_factor.yml b/roles/web-app-magento/tasks/02_two_factor.yml index 2fac13c2e1..894e6030c7 100644 --- a/roles/web-app-magento/tasks/02_two_factor.yml +++ b/roles/web-app-magento/tasks/02_two_factor.yml @@ -1,10 +1,24 @@ --- +- name: "🔍 Read which Magento modules are enabled" + ansible.builtin.shell: >- + container exec --user {{ MAGENTO_USER }} -w {{ MAGENTO_ROOT }} + {{ MAGENTO_PHP_CONTAINER_ADDRESS }} + bin/magento module:status --enabled + register: magento_enabled_modules + changed_when: false + - name: "🔐 Enable or disable Magento's two-factor modules" ansible.builtin.shell: cmd: >- container exec --user {{ MAGENTO_USER }} -w {{ MAGENTO_ROOT }} {{ MAGENTO_PHP_CONTAINER_ADDRESS }} bin/magento module:{{ MAGENTO_TWO_FACTOR_ENABLED | ternary('enable', 'disable') }} - {{ MAGENTO_TWO_FACTOR_MODULES | join(' ') }} + {{ magento_two_factor_misaligned | join(' ') }} + vars: + magento_two_factor_misaligned: >- + {{ MAGENTO_TWO_FACTOR_MODULES | reject('in', magento_enabled_modules.stdout_lines) | list + if MAGENTO_TWO_FACTOR_ENABLED | bool + else MAGENTO_TWO_FACTOR_MODULES | select('in', magento_enabled_modules.stdout_lines) | list }} register: magento_two_factor changed_when: "'No modules were changed' not in magento_two_factor.stdout" + when: magento_two_factor_misaligned | length > 0 diff --git a/tests/unit/python/roles/web-app-magento/__init__.py b/tests/unit/python/roles/web-app-magento/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-magento/test_two_factor_toggle.py b/tests/unit/python/roles/web-app-magento/test_two_factor_toggle.py new file mode 100644 index 0000000000..dc938f70d8 --- /dev/null +++ b/tests/unit/python/roles/web-app-magento/test_two_factor_toggle.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import unittest +from typing import Any, ClassVar + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml, load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +_ROLE = PROJECT_ROOT / "roles" / "web-app-magento" +_TWO_FACTOR = _ROLE / "tasks" / "02_two_factor.yml" +_SETUP = _ROLE / "tasks" / "01_setup.yml" +_TOGGLE = "🔐 Enable or disable Magento's two-factor modules" +_NGINX_REGISTERS = {"magento_nginx_restart_compose", "magento_nginx_restart_swarm"} +_PREFIX = "container exec --user app -w /var/www/html magento-php bin/magento" + + +def _status(*enabled: str) -> dict[str, Any]: + """Return the register of ``bin/magento module:status --enabled``. + + Args: + enabled: two-factor modules the command lists next to the always-on ones. + + Returns: + The register with ``stdout`` and ``stdout_lines`` as Ansible sets them. + """ + stdout = "\n".join(["Magento_Store", "Magento_Backend", *enabled]) + return {"rc": 0, "stdout": stdout, "stdout_lines": stdout.splitlines()} + + +def _included_file(task: dict[str, Any]) -> str | None: + include = task.get("include_tasks") + return include.get("file") if isinstance(include, dict) else include + + +class TestTwoFactorToggle(unittest.TestCase): + toggle: ClassVar[dict[str, Any]] + modules: ClassVar[list[str]] + + @classmethod + def setUpClass(cls) -> None: + tasks = DataLoader().load_from_file(str(_TWO_FACTOR), trusted_as_template=True) + cls.toggle = next(task for task in tasks if task["name"] == _TOGGLE) + cls.modules = load_yaml(_ROLE / ROLE_FILE_VARS_MAIN)[ + "MAGENTO_TWO_FACTOR_MODULES" + ] + + def _toggle(self, flag: bool, status: dict[str, Any]) -> str | None: + """Render the toggle task for one flag and module state. + + Args: + flag: ``MAGENTO_TWO_FACTOR_ENABLED``. + status: the ``magento_enabled_modules`` register. + + Returns: + The command the task runs, or ``None`` when its ``when`` skips it. + """ + variables: dict[str, Any] = { + "MAGENTO_TWO_FACTOR_ENABLED": flag, + "MAGENTO_TWO_FACTOR_MODULES": self.modules, + "MAGENTO_USER": "app", + "MAGENTO_ROOT": "/var/www/html", + "MAGENTO_PHP_CONTAINER_ADDRESS": "magento-php", + "magento_enabled_modules": status, + } + variables["magento_two_factor_misaligned"] = Templar( + loader=DataLoader(), variables=variables + ).template(self.toggle["vars"]["magento_two_factor_misaligned"]) + templar = Templar(loader=DataLoader(), variables=variables) + condition = self.toggle.get("when") + if condition is not None and not templar.template( + trust_as_template("{{ " + condition + " }}") + ): + return None + return templar.template(self.toggle["ansible.builtin.shell"]["cmd"]) + + def test_a_redeploy_with_the_modules_already_disabled_runs_no_toggle(self) -> None: + self.assertIsNone( + self._toggle(False, _status()), + "module:disable deletes generated/ before it reads any module state, so a " + "request PHP-FPM serves meanwhile regenerates classes into it and the " + "command dies on 'rmdir(/var/www/html/generated/code/Magento): Directory " + "not empty'", + ) + + def test_a_redeploy_with_the_modules_already_enabled_runs_no_toggle(self) -> None: + self.assertIsNone(self._toggle(True, _status(*self.modules))) + + def test_a_fresh_install_disables_every_two_factor_module(self) -> None: + self.assertEqual( + self._toggle(False, _status(*self.modules)), + f"{_PREFIX} module:disable {' '.join(self.modules)}", + ) + + def test_only_the_module_still_enabled_is_disabled(self) -> None: + self.assertEqual( + self._toggle(False, _status(self.modules[-1])), + f"{_PREFIX} module:disable {self.modules[-1]}", + ) + + def test_a_raised_flag_enables_the_disabled_modules(self) -> None: + self.assertEqual( + self._toggle(True, _status()), + f"{_PREFIX} module:enable {' '.join(self.modules)}", + ) + + def test_a_fresh_install_toggles_before_nginx_routes_requests_to_php(self) -> None: + tasks = load_yaml_any(str(_SETUP)) + toggle = next( + ( + index + for index, task in enumerate(tasks) + if _included_file(task) == _TWO_FACTOR.name + ), + None, + ) + self.assertIsNotNone( + toggle, f"{_SETUP.name} does not include {_TWO_FACTOR.name}" + ) + nginx = [ + index + for index, task in enumerate(tasks) + if task.get("register") in _NGINX_REGISTERS + ] + self.assertEqual(len(nginx), len(_NGINX_REGISTERS)) + self.assertLess( + toggle, + min(nginx), + "nginx only includes the Magento vhost after this reload, so a toggle " + "before it never races a request PHP-FPM serves", + ) + + +if __name__ == "__main__": + unittest.main()