diff --git a/plugins/lookup/container_extra_hosts.py b/plugins/lookup/container_extra_hosts.py index fd96e823ef..17c99c49c3 100644 --- a/plugins/lookup/container_extra_hosts.py +++ b/plugins/lookup/container_extra_hosts.py @@ -91,7 +91,7 @@ class LookupModule(LookupBase): "pass application_id= explicitly" ) - entries = self._sso_pins(application_id) + entries = self._sso_pins(application_id) + self._mail_pins(application_id) if _to_bool(self._render(kwargs.get("host_alias", False)), strict=False): entries.append( f"{DOCKER_INTERNAL_HOST}:{self._gateway_address(DOCKER_INTERNAL_HOST)}" @@ -128,6 +128,35 @@ class LookupModule(LookupBase): f"{provider_host}:{self._gateway_address(provider_host)}", ] + def _mail_pins(self, application_id: str) -> list[str]: + """The mail-provider pin, empty unless this is an onion node sending mail. + + Args: + application_id: the role whose ``services.email`` gate decides. + + The same unroutability as the SSO pin, one service down: an application + dials the relay by the provider's public name, which on an onion + deployment resolves only through Tor. ``sys-svc-mail-msmtp`` answers + that with a SOCKS proxy, but a client with no proxy setting at all -- + Ruby's ``Net::SMTP``, so GitLab queues the mail and reports success + while nothing leaves -- has no other route to the relay. + """ + if not bool( + self._lookup("config", application_id, "services.email.enabled", False) + ): + return [] + + mail_host = str( + (self._lookup("email", application_id) or {}).get("host") or "" + ).strip() + if not mail_host.endswith(".onion"): + return [] + + return [ + f"{DOCKER_INTERNAL_HOST}:{HOST_GATEWAY}", + f"{mail_host}:{self._gateway_address(mail_host)}", + ] + def _caller_entries(self, extra_hosts: Any) -> list[str]: """Normalise the ``extra_hosts=`` argument to a list of mappings. diff --git a/roles/web-app-gitlab/templates/compose.yml.j2 b/roles/web-app-gitlab/templates/compose.yml.j2 index 603f7d3411..2a5a544b54 100644 --- a/roles/web-app-gitlab/templates/compose.yml.j2 +++ b/roles/web-app-gitlab/templates/compose.yml.j2 @@ -20,6 +20,7 @@ GITLAB_MIGRATIONS_SERVICE_NAME: {'condition': 'service_completed_successfully'}, }) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% set service_name = GITLAB_WORKHORSE_SERVICE_NAME %} @@ -62,6 +63,7 @@ GITLAB_WEBSERVICE_SERVICE_NAME: {'condition': 'service_started'}, }) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% set service_name = GITLAB_GITALY_SERVICE_NAME %} diff --git a/roles/web-app-stalwart/tasks/01_wait_for_api.yml b/roles/web-app-stalwart/tasks/01_wait_for_api.yml index 14903caa0e..4f67962fa1 100644 --- a/roles/web-app-stalwart/tasks/01_wait_for_api.yml +++ b/roles/web-app-stalwart/tasks/01_wait_for_api.yml @@ -13,3 +13,24 @@ delay: 5 until: stalwart_api_check.rc == 0 changed_when: false + +# Exception: /healthz/ready answers 200 while Stalwart is still in bootstrap +# mode (measured against v0.16.12), where every x: method is refused with +# "The server is in bootstrap mode". Readiness for the management ops that +# follow is therefore a management call, not the health endpoint. +- name: "⏳ Wait until Stalwart accepts management calls" + ansible.builtin.shell: >- + container exec -i {{ STALWART_CONTAINER_ADDRESS }} + {{ 30 | curl }} -sS -f + -u {{ (STALWART_ADMIN_USER ~ ':' ~ STALWART_ADMIN_PASSWORD) | quote }} + -H "Content-Type:application/json" + --data-binary {{ STALWART_JMAP_APPLICATION_GET | quote }} + {{ STALWART_JMAP_URL }} + register: stalwart_manage_check + retries: 30 + delay: 5 + until: + - stalwart_manage_check.rc == 0 + - (stalwart_manage_check.stdout | from_json).methodResponses[0][0] != 'error' + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-stalwart/tasks/02_webadmin.yml b/roles/web-app-stalwart/tasks/02_webadmin.yml index fb66d174df..8b0790bf92 100644 --- a/roles/web-app-stalwart/tasks/02_webadmin.yml +++ b/roles/web-app-stalwart/tasks/02_webadmin.yml @@ -5,27 +5,30 @@ - name: "📖 List Stalwart Application records" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Application/get', {'ids': none}, 'c0']]} | to_json }} + stalwart_jmap_body: "{{ STALWART_JMAP_APPLICATION_GET }}" -- name: "🔍 Resolve the WebUI Application id" +- name: "🔍 Resolve the WebUI Application record" ansible.builtin.set_fact: - stalwart_webui_app_id: >- - {{ (stalwart_jmap.methodResponses[0][1].list - | selectattr('description', 'equalto', STALWART_WEBUI_APP_DESCRIPTION) - | map(attribute='id') | first) | default('') }} + stalwart_webui_apps: >- + {{ stalwart_jmap.methodResponses[0][1].list + | selectattr('description', 'equalto', STALWART_WEBUI_APP_DESCRIPTION) + | list }} - name: "✅ Ensure the WebUI Application record was found" ansible.builtin.assert: that: - - stalwart_webui_app_id | length > 0 + - stalwart_webui_apps | length > 0 fail_msg: >- No Stalwart Application record with description - '{{ STALWART_WEBUI_APP_DESCRIPTION }}' found — the JMAP schema changed; - re-validate 02_webadmin.yml against this Stalwart version. + '{{ STALWART_WEBUI_APP_DESCRIPTION }}' among the records this Stalwart + reports: + {{ stalwart_jmap.methodResponses[0][1].list | map(attribute='description') | list }} quiet: true +- name: "🔍 Resolve the WebUI Application id" + ansible.builtin.set_fact: + stalwart_webui_app_id: "{{ stalwart_webui_apps[0].id }}" + - name: "🔗 Point the WebUI Application at the locally-staged bundle" include_tasks: jmap_call.yml vars: diff --git a/roles/web-app-stalwart/tasks/jmap_call.yml b/roles/web-app-stalwart/tasks/jmap_call.yml index 37cab47ac7..0769b9d4ab 100644 --- a/roles/web-app-stalwart/tasks/jmap_call.yml +++ b/roles/web-app-stalwart/tasks/jmap_call.yml @@ -21,3 +21,17 @@ ansible.builtin.set_fact: stalwart_jmap: "{{ stalwart_jmap_raw.stdout | from_json }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +# Exception: JMAP reports method-level failures inside a 200 response, so the +# `-f` above cannot see them. Left unchecked the caller reads a field off the +# error object, gets undefined, and reports whatever its own fallback says +# instead of what Stalwart refused. +- name: "✅ Ensure Stalwart accepted the JMAP call" + ansible.builtin.assert: + that: + - stalwart_jmap.methodResponses[0][0] != 'error' + # Exception: assert finalizes fail_msg even when `that` holds, so this + # renders the response object whole rather than reaching for the error + # keys, which a successful response does not carry. + fail_msg: "Stalwart refused the JMAP call: {{ stalwart_jmap.methodResponses[0][1] }}" + quiet: true diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index f9955dedb1..6094befbca 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -11,6 +11,9 @@ STALWART_CONFIG_FILE: "{{ [ STALWART_CONFIG_DIR, 'config.json' ] | path_join }}" container_port: "{{ lookup('config', application_id, 'services.stalwart.ports.internal.http') }}" STALWART_LOCAL_BASE_URL: "http://localhost:{{ container_port }}" STALWART_JMAP_URL: "{{ STALWART_LOCAL_BASE_URL }}/jmap/" +STALWART_JMAP_APPLICATION_GET: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:Application/get', {'ids': none}, 'c0']]} | to_json }} STALWART_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'stalwart') }}" STALWART_DOMAIN: "{{ lookup('config', application_id, 'services.stalwart.domain') }}" diff --git a/tests/unit/python/plugins/lookup/test_container_extra_hosts.py b/tests/unit/python/plugins/lookup/test_container_extra_hosts.py index f914fa7c72..bf3812e37b 100644 --- a/tests/unit/python/plugins/lookup/test_container_extra_hosts.py +++ b/tests/unit/python/plugins/lookup/test_container_extra_hosts.py @@ -6,6 +6,7 @@ from ansible.errors import AnsibleError from plugins.lookup.container_extra_hosts import LookupModule ONION = "auth." + "b" * 56 + ".onion" +MAIL_ONION = "mail." + "c" * 56 + ".onion" class TestContainerExtraHostsLookup(unittest.TestCase): @@ -18,9 +19,13 @@ class TestContainerExtraHostsLookup(unittest.TestCase): def _run(terms, variables=None, **_kwargs): vars_ = variables or {} if name == "config": + if "services.email.enabled" in terms: + return [vars_.get("_email_enabled", False)] return [vars_.get("_sso_enabled", False)] if name == "tls": return [vars_.get("_provider_domain", "")] + if name == "email": + return [{"host": vars_.get("_mail_host", "")}] raise AssertionError(f"unexpected lookup '{name}'") plugin.run.side_effect = _run @@ -43,6 +48,51 @@ class TestContainerExtraHostsLookup(unittest.TestCase): kwargs = {} if extra_hosts is None else {"extra_hosts": extra_hosts} return self.lookup.run(None, variables=variables, **kwargs)[0] + def test_an_onion_mail_relay_is_pinned_so_a_proxyless_client_can_reach_it(self): + """GitLab's Net::SMTP takes no proxy, so an unpinned .onion relay + swallows every message: the send is queued and reported successful.""" + block = self._run( + _sso_enabled=False, _email_enabled=True, _mail_host=MAIL_ONION + ) + self.assertEqual( + block, + 'extra_hosts:\n - "host.docker.internal:host-gateway"\n' + f' - "{MAIL_ONION}:host-gateway"', + ) + + def test_a_clearnet_mail_relay_is_left_alone(self): + self.assertEqual( + self._run( + _sso_enabled=False, _email_enabled=True, _mail_host="mail.example.org" + ), + "", + ) + + def test_mail_disabled_emits_nothing(self): + self.assertEqual( + self._run(_sso_enabled=False, _email_enabled=False, _mail_host=MAIL_ONION), + "", + ) + + def test_swarm_pins_the_mail_relay_to_the_node_address(self): + block = self._run( + _sso_enabled=False, + _email_enabled=True, + _mail_host=MAIL_ONION, + DEPLOYMENT_MODE="swarm", + ansible_facts={"default_ipv4": {"address": "10.0.0.7"}}, + ) + self.assertIn(f' - "{MAIL_ONION}:10.0.0.7"', block) + + def test_the_sso_and_mail_pins_coexist_without_repeating_the_alias(self): + block = self._run(_email_enabled=True, _mail_host=MAIL_ONION) + self.assertEqual( + block, + 'extra_hosts:\n - "host.docker.internal:host-gateway"\n' + f' - "{ONION}:host-gateway"\n' + f' - "{MAIL_ONION}:host-gateway"', + ) + def test_compose_pins_the_provider_to_the_host_gateway(self): self.assertEqual( self._run(), @@ -129,7 +179,7 @@ class TestContainerExtraHostsLookup(unittest.TestCase): variables={"application_id": "web-app-joomla"}, application_id="web-app-penpot", ) - self.assertEqual(seen, ["web-app-penpot"]) + self.assertEqual(set(seen), {"web-app-penpot"}) def test_caller_entries_alone_emit_a_block_without_sso(self): self.assertEqual(