diff --git a/group_vars/all/14_about.yml b/group_vars/all/14_about.yml index f6c5b976eb..87c8091d7b 100644 --- a/group_vars/all/14_about.yml +++ b/group_vars/all/14_about.yml @@ -23,8 +23,7 @@ defaults_service_provider: email: "{{ lookup('users', 'contact').username ~ '@' ~ DOMAIN_PRIMARY if MAIL_PROVIDER in group_names else 'contact@infinito.nexus' }}" mastodon: "{{ '@' ~ lookup('users', 'contact').username ~ '@' ~ lookup('domain','web-app-mastodon') if 'web-app-mastodon' in group_names else '@infinito@microblog.infinito.nexus' }}" - matrix: "{{ '@' ~ lookup('users', 'contact').username ~ ':' ~ lookup('config','web-app-matrix', 'services.matrix.server_name') if 'web-app-matrix' in group_names - else '@contact:infinito.nexus' }}" + matrix: "{{ lookup('mxid', lookup('users', 'contact').username) if 'web-app-matrix' in group_names else '@contact:infinito.nexus' }}" peertube: "{{ '@' ~ lookup('users', 'contact').username ~ '@' ~ lookup('domain','web-app-peertube') if 'web-app-peertube' in group_names else 'infinito@video.infinito.nexus' }}" pixelfed: "{{ '@' ~ lookup('users', 'contact').username ~ '@' ~ lookup('domain','web-app-pixelfed') if 'web-app-pixelfed' in group_names else 'infinito@picture.infinito.nexus' diff --git a/plugins/filter/matrix.py b/plugins/filter/matrix.py new file mode 100644 index 0000000000..55304e6c3b --- /dev/null +++ b/plugins/filter/matrix.py @@ -0,0 +1,52 @@ +"""Build the Matrix identifiers whose shape several templates repeat. + +A Matrix user id is ``@:``. Six templates of +web-app-matrix assembled it by hand, which is how the MDAD flavor came to use a +different server name than the compose flavor. The shape lives here and the +server name stays in ``MATRIX_SERVER_NAME``, so a caller supplies only the +localpart and the homeserver it belongs to. +""" + +from __future__ import annotations + +from ansible.errors import AnsibleFilterError + +SIGIL = "@" +SEPARATOR = ":" +FORBIDDEN = (SIGIL, SEPARATOR, "/") + + +def mxid(localpart: str, server_name: str) -> str: + """Return the Matrix user id of ``localpart`` on ``server_name``. + + Args: + localpart: the user's name without sigil or server, e.g. ``alice``. A + leading ``@`` is accepted and dropped so a caller may pass either. + server_name: the homeserver's name, normally ``MATRIX_SERVER_NAME``. + + Returns: + ``@:``, lowercased: Synapse rejects a user id + that is not, and the callers read usernames from inventory. + + Raises: + AnsibleFilterError: either part is empty, or the localpart still + carries a sigil, a separator or a slash after the leading ``@``. + """ + name = str(localpart or "").strip().removeprefix(SIGIL) + server = str(server_name or "").strip() + if not name: + raise AnsibleFilterError("mxid: the localpart is empty") + if not server: + raise AnsibleFilterError(f"mxid: no server name for localpart '{name}'") + bad = [character for character in FORBIDDEN if character in name] + if bad: + raise AnsibleFilterError( + f"mxid: localpart '{name}' carries {' and '.join(bad)}; " + "pass the bare name, not a user id" + ) + return f"{SIGIL}{name}{SEPARATOR}{server}".lower() + + +class FilterModule: + def filters(self): + return {"mxid": mxid} diff --git a/plugins/lookup/matrix_server_name.py b/plugins/lookup/matrix_server_name.py new file mode 100644 index 0000000000..e474452d34 --- /dev/null +++ b/plugins/lookup/matrix_server_name.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +from typing import Any + +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.tls_common import is_onion_domain + +APPLICATION_ID = "web-app-matrix" +SERVER_NAME_PATH = "services.matrix.server_name" +TOR_NODE_PATH = "services.tor.node" +TOR_ROLE = "svc-net-tor" + + +def resolve_server_name(variables: dict[str, Any], loader: Any, templar: Any) -> str: + """Return the name the Matrix homeserver answers to. + + Args: + variables: the play's variable namespace. + loader: the calling lookup's loader. + templar: the calling lookup's templar. + + Returns: + The Tor node when the role is published under a ``.onion`` address, + where Synapse's server_name is that address and a clearnet name would + match no user id, otherwise the declared ``services.matrix.server_name``. + """ + + def _config(role: str, path: str, default: Any = None) -> Any: + terms = [role, path] if default is None else [role, path, default] + return lookup_loader.get("config", loader=loader, templar=templar).run( + terms, variables=variables + )[0] + + domain = lookup_loader.get("domain", loader=loader, templar=templar).run( + [APPLICATION_ID], variables=variables + )[0] + onion_node = str(_config(TOR_ROLE, TOR_NODE_PATH, "") or "").strip() + if onion_node and is_onion_domain(domain): + return onion_node + return str(_config(APPLICATION_ID, SERVER_NAME_PATH)) + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('matrix_server_name') }} + + The homeserver name every Matrix user id ends in. Onion deployments answer + under the Tor node rather than the declared clearnet name, so the choice + lives here and not in each caller. Takes no terms and needs no role var, so + group_vars and other roles can resolve it too. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + templar = getattr(self, "_templar", None) + variables = variables or getattr(templar, "available_variables", {}) or {} + return [resolve_server_name(variables, self._loader, templar)] diff --git a/plugins/lookup/mxid.py b/plugins/lookup/mxid.py new file mode 100644 index 0000000000..bb9c0c20b7 --- /dev/null +++ b/plugins/lookup/mxid.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from plugins.filter.matrix import mxid +from plugins.lookup.matrix_server_name import resolve_server_name + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('mxid', 'chatgptbot') }} + {{ lookup('mxid', lookup('users', 'contact').username) }} + + Matrix user id of a localpart on this deployment's homeserver. The server + name comes from lookup('matrix_server_name'), which answers the Tor node on + an onion deployment and the declared name otherwise, so a caller names only + the account and gets an id that matches whichever network is published. + Needs no role var, so group_vars and other roles can use it as well. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if len(terms or []) != 1: + raise AnsibleError( + "mxid: expected exactly 1 term: lookup('mxid', localpart)" + ) + templar = getattr(self, "_templar", None) + variables = variables or getattr(templar, "available_variables", {}) or {} + server = resolve_server_name(variables, self._loader, templar) + return [mxid(terms[0], server)] diff --git a/roles/web-app-matrix/files/flavor/ansible/runner/Dockerfile b/roles/web-app-matrix/files/flavor/ansible/runner/Dockerfile index b8f1959298..1c3ea1fcaf 100644 --- a/roles/web-app-matrix/files/flavor/ansible/runner/Dockerfile +++ b/roles/web-app-matrix/files/flavor/ansible/runner/Dockerfile @@ -27,6 +27,7 @@ RUN rm -rf /var/lib/apt/lists/* \ iptables \ openssh-client \ python3-venv \ + sudo \ systemd \ systemd-sysv \ && rm -rf /var/lib/apt/lists/* diff --git a/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml b/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml index 1150cf6d2b..40ba1ffbb3 100644 --- a/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml +++ b/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml @@ -19,7 +19,7 @@ psql -v ON_ERROR_STOP=1 -U {{ MATRIX_POSTGRES_USER | quote }} -d {{ MATRIX_POSTGRES_DATABASE | quote }} -v hash={{ (matrix_password_hash.stdout | trim) | quote }} - -v name={{ ('@' ~ realign_localpart ~ ':' ~ MATRIX_SERVER_NAME) | quote }} + -v name={{ lookup('mxid', realign_localpart) | quote }} -f - stdin: >- {{ lookup('file', 'sql/realign_user_password.sql') }} diff --git a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 index 7d92b191a3..e3046cb739 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 @@ -1,7 +1,8 @@ --- {% set _matrix_onion_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} {% set _matrix_is_onion = (_matrix_onion_node and lookup('domain', application_id) is search('\.onion$')) %} -matrix_domain: {{ _matrix_onion_node if _matrix_is_onion else DOMAIN_PRIMARY }} +matrix_domain: {{ MATRIX_SERVER_NAME }} +matrix_admin: "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}" matrix_playbook_ssl_enabled: {{ 'false' if _matrix_is_onion else 'true' }} matrix_homeserver_implementation: synapse matrix_playbook_docker_installation_enabled: false diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 index b584e7ba6b..d10da0da9a 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 @@ -91,7 +91,7 @@ bridge: permissions: "*": relay "{{ MATRIX_SERVER_NAME }}": user - "@{{ MATRIX_ADMINISTRATOR_USERNAME }}:{{ MATRIX_SERVER_NAME }}": admin + "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}": admin database: type: postgres diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 index 9ee88b43cf..c3ebfd7376 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 @@ -23,7 +23,7 @@ bridge: permissions: "*": relay "{{ MATRIX_SERVER_NAME }}": user - "@{{ MATRIX_ADMINISTRATOR_USERNAME }}:{{ MATRIX_SERVER_NAME }}": admin + "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}": admin database: type: postgres diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 index a89d2b6c20..a2b68045be 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 @@ -61,7 +61,7 @@ bridge: permissions: "*": relay "{{ MATRIX_SERVER_NAME }}": user - "@{{ MATRIX_ADMINISTRATOR_USERNAME }}:{{ MATRIX_SERVER_NAME }}": admin + "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}": admin matrix: message_status_events: false diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 index e3ad679693..ac74eb1141 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 @@ -43,7 +43,7 @@ bridge: "*": "relay" "public.{{ MATRIX_SERVER_NAME }}": "commands" "{{ MATRIX_SERVER_NAME }}": "user" - "@{{ MATRIX_ADMINISTRATOR_USERNAME }}:{{ MATRIX_SERVER_NAME }}": "admin" + "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}": "admin" database: type: postgres diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 index 13a910b171..7d4e356957 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 @@ -114,7 +114,7 @@ bridge: permissions: "*": relay "{{ MATRIX_SERVER_NAME }}": user - "@{{ MATRIX_ADMINISTRATOR_USERNAME }}:{{ MATRIX_SERVER_NAME }}": admin + "{{ lookup('mxid', MATRIX_ADMINISTRATOR_USERNAME) }}": admin database: type: postgres diff --git a/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 index e24e06d6f3..bcfa1b5809 100644 --- a/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 @@ -66,7 +66,7 @@ KEYV_BOT_ENCRYPTION: 'false' KEYV_BOT_STORAGE: 'true' MATRIX_HOMESERVER_URL: '{{ MATRIX_SYNAPSE_LOCAL_URL }}' - MATRIX_BOT_USERNAME: '@chatgptbot:{{ MATRIX_SERVER_NAME }}' + MATRIX_BOT_USERNAME: "{{ lookup('mxid', 'chatgptbot') }}" MATRIX_ACCESS_TOKEN: "{{ MATRIX_CHATGPT_ACCESS_TOKEN }}" MATRIX_BOT_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') }}" MATRIX_DEFAULT_PREFIX: '!chatgpt' diff --git a/roles/web-app-matrix/vars/main.yml b/roles/web-app-matrix/vars/main.yml index 0ac6c3f3aa..5059c7d727 100644 --- a/roles/web-app-matrix/vars/main.yml +++ b/roles/web-app-matrix/vars/main.yml @@ -5,9 +5,7 @@ compose_mode_force: "{{ 'compose' if lookup('config', application_id, 'services. location_upload: "~ ^/_matrix/media/v3/" -MATRIX_ONION_NODE: "{{ lookup('config', 'svc-net-tor', 'services.tor.node', '') }}" -MATRIX_SERVER_NAME: "{{ MATRIX_ONION_NODE if (MATRIX_ONION_NODE and lookup('domain', application_id) is search('\\.onion$')) else lookup('config', application_id, - 'services.matrix.server_name') }}" +MATRIX_SERVER_NAME: "{{ lookup('matrix_server_name') }}" MATRIX_ADMINISTRATOR_USERNAME: "{{ lookup('users', 'administrator').username }}" MATRIX_ADMINISTRATOR_PASSWORD: "{{ lookup('users', 'administrator').password }}" MATRIX_WELL_KNOWN_DIRECTORY: "{{ [ lookup('nginx','directories.data.well_known'), 'matrix' ] | path_join }}" diff --git a/tests/unit/python/plugins/filter/test_matrix.py b/tests/unit/python/plugins/filter/test_matrix.py new file mode 100644 index 0000000000..2718ce7992 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_matrix.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import unittest + +from ansible.errors import AnsibleFilterError + +from plugins.filter.matrix import FilterModule, mxid + +SERVER = "matrix.example.com" + + +class TestMxid(unittest.TestCase): + def test_a_localpart_and_a_server_become_a_user_id(self) -> None: + self.assertEqual(mxid("administrator", SERVER), "@administrator:" + SERVER) + + def test_a_leading_sigil_is_accepted_once_and_not_doubled(self) -> None: + self.assertEqual(mxid("@chatgptbot", SERVER), "@chatgptbot:" + SERVER) + + def test_the_result_is_lowercased_because_synapse_rejects_anything_else( + self, + ) -> None: + self.assertEqual( + mxid("Administrator", "Matrix.Example.COM"), + "@administrator:matrix.example.com", + ) + + def test_an_onion_server_keeps_its_name(self) -> None: + onion = "jq3cxczghznig7mzqbfy7jlznvi4pv7q53xul2ptvrnsosnfamkhjrid.onion" + self.assertEqual(mxid("biber", onion), "@biber:" + onion) + + def test_an_empty_localpart_is_refused(self) -> None: + with self.assertRaises(AnsibleFilterError): + mxid(" ", SERVER) + + def test_a_missing_server_name_is_refused(self) -> None: + with self.assertRaises(AnsibleFilterError) as caught: + mxid("administrator", "") + self.assertIn("administrator", str(caught.exception)) + + def test_a_full_user_id_passed_as_the_localpart_is_refused(self) -> None: + with self.assertRaises(AnsibleFilterError) as caught: + mxid("@administrator:other.example", SERVER) + self.assertIn("pass the bare name", str(caught.exception)) + + def test_the_filter_is_registered_under_its_name(self) -> None: + self.assertIs(FilterModule().filters()["mxid"], mxid) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_matrix_server_name.py b/tests/unit/python/plugins/lookup/test_matrix_server_name.py new file mode 100644 index 0000000000..cb25e04af1 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_matrix_server_name.py @@ -0,0 +1,80 @@ +"""Unit tests for the matrix_server_name lookup plugin. + +Pins the one choice every Matrix user id depends on: which network's name the +homeserver answers to. An onion deployment runs Synapse under the Tor node, so +a user id built on the clearnet name matches no account there, and the reverse +publishes an unreachable contact handle on a clearnet deployment. +""" + +from __future__ import annotations + +import importlib.util +import unittest +import unittest.mock as mock + +from . import PROJECT_ROOT + +MODULE = "lookup_matrix_server_name" +CLEARNET = "matrix.example.com" +ONION = "jq3cxczghznig7mzqbfy7jlznvi4pv7q53xul2ptvrnsosnfamkhjrid.onion" +TOR_NODE = "matrix." + ONION + + +def _load_lookup(): + spec = importlib.util.spec_from_file_location( + MODULE, str(PROJECT_ROOT / "plugins/lookup/matrix_server_name.py") + ) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +class _StubLookup: + def __init__(self, result): + self._result = result + + def run(self, terms, variables=None): + return [self._result] + + +class TestResolveServerName(unittest.TestCase): + def _resolve(self, module, domain, tor_node, server_name): + def get(name, loader=None, templar=None): + if name == "domain": + return _StubLookup(domain) + + class _Config: + def run(self, terms, variables=None): + role = terms[0] + return [tor_node if role == module.TOR_ROLE else server_name] + + return _Config() + + with mock.patch.object(module, "lookup_loader", mock.Mock(get=get)): + return module.resolve_server_name({}, None, None) + + def test_an_onion_deployment_answers_under_the_tor_node(self) -> None: + module = _load_lookup() + + self.assertEqual( + self._resolve(module, "matrix." + ONION, TOR_NODE, CLEARNET), TOR_NODE + ) + + def test_a_clearnet_deployment_keeps_the_declared_name(self) -> None: + module = _load_lookup() + + self.assertEqual(self._resolve(module, CLEARNET, TOR_NODE, CLEARNET), CLEARNET) + + def test_an_onion_domain_without_a_tor_node_falls_back_rather_than_empty( + self, + ) -> None: + module = _load_lookup() + + self.assertEqual( + self._resolve(module, "matrix." + ONION, "", CLEARNET), CLEARNET + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_mxid.py b/tests/unit/python/plugins/lookup/test_mxid.py new file mode 100644 index 0000000000..5be7c4123b --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_mxid.py @@ -0,0 +1,75 @@ +"""Unit tests for the mxid lookup plugin. + +The filter pins the user-id shape and matrix_server_name pins which network's +name is used. What only this lookup can get wrong is joining the two, so that +is what these pin, including that it needs no role variable in scope. +""" + +from __future__ import annotations + +import importlib.util +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + +MODULE = "lookup_mxid" +SERVER = "matrix.example.com" +ONION = "matrix.jq3cxczghznig7mzqbfy7jlznvi4pv7q53xul2ptvrnsosnfamkhjrid.onion" + + +def _load_lookup(): + spec = importlib.util.spec_from_file_location( + MODULE, str(PROJECT_ROOT / "plugins/lookup/mxid.py") + ) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +class TestMxidLookup(unittest.TestCase): + def _run(self, module, terms, server, variables=None): + instance = module.LookupModule() + instance._templar = None + instance._loader = None + with mock.patch.object(module, "resolve_server_name", return_value=server): + return instance.run( + terms, variables=variables if variables is not None else {} + ) + + def test_the_server_name_is_resolved_and_never_an_argument(self) -> None: + module = _load_lookup() + + self.assertEqual( + self._run(module, ["administrator"], SERVER), ["@administrator:" + SERVER] + ) + + def test_an_onion_deployment_yields_an_onion_user_id(self) -> None: + module = _load_lookup() + + self.assertEqual( + self._run(module, ["chatgptbot"], ONION), ["@chatgptbot:" + ONION] + ) + + def test_no_role_variable_has_to_be_in_scope(self) -> None: + module = _load_lookup() + + self.assertEqual( + self._run(module, ["contact"], SERVER, {}), ["@contact:" + SERVER] + ) + + def test_more_than_one_term_is_refused(self) -> None: + module = _load_lookup() + instance = module.LookupModule() + instance._templar = None + instance._loader = None + + with self.assertRaises(AnsibleError): + instance.run(["administrator", SERVER], variables={}) + + +if __name__ == "__main__": + unittest.main()