diff --git a/roles/web-app-espocrm/README.md b/roles/web-app-espocrm/README.md index 52d9316945..975eb56b17 100644 --- a/roles/web-app-espocrm/README.md +++ b/roles/web-app-espocrm/README.md @@ -36,6 +36,7 @@ Both name surfaces EspoCRM ships itself, so their payload stays with [`templates - **Health Checks & Logging:** Monitor service health and logs with built-in checks and journald 📈 - **Version Upgrades:** The first start of a new image migrates the data through EspoCRM's `migrate` command, and the deploy waits until the data reports the image version; data written by a newer EspoCRM than the image stops the start. - **Currency List:** Before and after each install or migration, the entrypoint adds the default and base currency to `currencyList` when they are missing from it. +- **Network Siblings:** [`templates/config-override.php.j2`](./templates/config-override.php.j2) becomes `data/config-override.php`, which answers `siteUrl` with the onion sibling's base URL when a request arrives on that host, so the OIDC `redirect_uri` EspoCRM derives from `siteUrl` returns the login to the host it started on. `data/config.php` keeps the canonical URL, so the CLI and the clearnet host read it unchanged. - **Modular Role Composition:** Leverages central roles for database and NGINX, ensuring consistency across deployments 🔄 ## AI Assistance diff --git a/roles/web-app-espocrm/tasks/02_manager_ops.yml b/roles/web-app-espocrm/tasks/02_manager_ops.yml index dcbfb34d18..435073a963 100644 --- a/roles/web-app-espocrm/tasks/02_manager_ops.yml +++ b/roles/web-app-espocrm/tasks/02_manager_ops.yml @@ -60,6 +60,17 @@ delay: 10 delegate_to: "{{ ESPOCRM_HOST_NODE }}" +- name: "🌐 Answer siteUrl with the network sibling the request arrived on" + ansible.builtin.shell: + cmd: >- # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i --user {{ ESPOCRM_USER }} {{ ESPOCRM_LOCAL_CID | quote }} + sh -c 'cat >"$1.new" && if cmp -s "$1.new" "$1"; then rm "$1.new"; else mv "$1.new" "$1" && echo CHANGED; fi' + config_override {{ ESPOCRM_CONFIG_OVERRIDE_FILE | quote }} + stdin: "{{ lookup('template', 'config-override.php.j2') }}" + register: espocrm_config_override + changed_when: "'CHANGED' in espocrm_config_override.stdout" + delegate_to: "{{ ESPOCRM_HOST_NODE }}" + - name: ▶️ Run flag setter as root (fallback) shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node diff --git a/roles/web-app-espocrm/templates/config-override.php.j2 b/roles/web-app-espocrm/templates/config-override.php.j2 new file mode 100644 index 0000000000..989588beeb --- /dev/null +++ b/roles/web-app-espocrm/templates/config-override.php.j2 @@ -0,0 +1,14 @@ + $siteUrl]; + } + } + return []; +})([ +{% for url in ESPOCRM_SIBLING_SITE_URLS %} + '{{ url }}', +{% endfor %} +]); diff --git a/roles/web-app-espocrm/vars/main.yml b/roles/web-app-espocrm/vars/main.yml index fae932d166..7572fbe380 100644 --- a/roles/web-app-espocrm/vars/main.yml +++ b/roles/web-app-espocrm/vars/main.yml @@ -27,9 +27,11 @@ ESPOCRM_SCRIPT_SIDECAR_HOST_REL: "volumes/{{ ESPOCRM_SCRIPT_SIDECAR_FILE }}" ESPOCRM_SCRIPT_SIDECAR_DOCKER: "{{ [ ESPOCRM_BIN_DIR, ESPOCRM_SCRIPT_SIDECAR_FILE ] | path_join }}" ESPOCRM_CONFIG_FILE_PRIVATE: "{{ [ ESPOCRM_APP_DIR, 'data/config-internal.php' ] | path_join }}" +ESPOCRM_CONFIG_OVERRIDE_FILE: "{{ [ ESPOCRM_APP_DIR, 'data/config-override.php' ] | path_join }}" ESPOCRM_LOG_DIR_RELATIVE: "data/logs" ESPOCRM_LOG_PATH_RELATIVE: "{{ [ ESPOCRM_LOG_DIR_RELATIVE, 'espo.log' ] | path_join }}" ESPOCRM_URL: "{{ lookup('tls', application_id, 'url.base') }}" +ESPOCRM_SIBLING_SITE_URLS: "{{ lookup('network_urls', ESPOCRM_URL)[1:] }}" ESPOCRM_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" ESPOCRM_OIDC_ONION_ISSUER: "{{ (lookup('tls', 'web-app-keycloak', 'domain') | network_of) == 'tor' }}" ESPOCRM_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if ESPOCRM_OIDC_ONION_ISSUER | bool else '' }}" diff --git a/tests/unit/python/roles/web-app-espocrm/__init__.py b/tests/unit/python/roles/web-app-espocrm/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-espocrm/templates/__init__.py b/tests/unit/python/roles/web-app-espocrm/templates/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-espocrm/templates/test_config_override_php.py b/tests/unit/python/roles/web-app-espocrm/templates/test_config_override_php.py new file mode 100644 index 0000000000..12bc02fd1e --- /dev/null +++ b/tests/unit/python/roles/web-app-espocrm/templates/test_config_override_php.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +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-espocrm" +CLEARNET = "https://espo.crm.example.test/" +ONION = "http://espo.crm." + "a" * 56 + ".onion/" + + +def _sibling_site_urls(network_urls: list[str]) -> list[str]: + """ + Args: + network_urls: the answer of lookup('network_urls', ESPOCRM_URL) on the host. + + Returns: + ESPOCRM_SIBLING_SITE_URLS as vars/main.yml resolves it. + """ + + def lookup(*terms: str) -> list[str]: + if terms != ("network_urls", CLEARNET): + raise AssertionError(f"the sibling URLs render an unexpected lookup{terms}") + return network_urls + + expression = load_yaml(ROLE / ROLE_FILE_VARS_MAIN)["ESPOCRM_SIBLING_SITE_URLS"] + return Environment( + undefined=StrictUndefined, autoescape=select_autoescape() + ).compile_expression(expression.strip().removeprefix("{{").removesuffix("}}"))( + lookup=lookup, ESPOCRM_URL=CLEARNET + ) + + +def _render(network_urls: list[str]) -> str: + """ + Args: + network_urls: the answer of lookup('network_urls', ESPOCRM_URL) on the host. + + Returns: + data/config-override.php as the deploy writes it. + """ + env = Environment( + loader=FileSystemLoader(str(ROLE / "templates")), + undefined=StrictUndefined, + trim_blocks=True, + keep_trailing_newline=True, + autoescape=select_autoescape(), + ) + return env.get_template("config-override.php.j2").render( + ESPOCRM_SIBLING_SITE_URLS=_sibling_site_urls(network_urls) + ) + + +def _answered(php: str) -> list[str]: + return re.findall(r"^ '([^']+)',$", php, re.MULTILINE) + + +class TestConfigOverride(unittest.TestCase): + def test_the_onion_sibling_is_answered_with_its_plaintext_base_url(self) -> None: + self.assertEqual( + _answered(_render([CLEARNET, ONION])), + [ONION], + "EspoCRM builds the OIDC redirect_uri from siteUrl, so an onion login " + "returns to the clearnet callback unless the onion host answers its own URL", + ) + + def test_the_canonical_host_keeps_the_stored_site_url(self) -> None: + self.assertNotIn(CLEARNET, _answered(_render([CLEARNET, ONION]))) + + def test_a_host_without_siblings_overrides_nothing(self) -> None: + self.assertEqual(_answered(_render([CLEARNET])), []) + + def test_the_request_host_selects_the_site_url_parameter(self) -> None: + php = _render([CLEARNET, ONION]) + self.assertTrue(php.startswith(" $siteUrl];", php) + + def test_the_deploy_writes_the_file_espocrm_reads_as_its_override(self) -> None: + self.assertIn( + "'data/config-override.php'", + load_yaml(ROLE / ROLE_FILE_VARS_MAIN)["ESPOCRM_CONFIG_OVERRIDE_FILE"], + ) + writers = [ + task + for task in load_yaml_any(ROLE / "tasks" / "02_manager_ops.yml") + if "config-override.php.j2" in str(task.get("ansible.builtin.shell", {})) + ] + self.assertEqual(len(writers), 1) + self.assertIn( + "ESPOCRM_CONFIG_OVERRIDE_FILE", writers[0]["ansible.builtin.shell"]["cmd"] + ) + + +if __name__ == "__main__": + unittest.main()