diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index d60c79c006..6f8bc9e177 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -79,6 +79,22 @@ users: - Overrides merge recursively on top of role-local defaults. - Overrides MUST NOT be written back into `roles/*/meta/users.yml`; that file is for defaults only. +## Forwards 📨 + +A user MAY name another canonical user key in `forward`, so mail to the user also reaches the named user: + +```yaml +# roles/user-administrator/meta/users.yml +platform_administrator: + accounts: [mailbox, identity] + forward: administrator +``` + +- `forward` is `''` unless declared, which forwards nothing. +- The named user MUST exist. The lookup raises for an unknown user, for a named user whose entry is no mapping, for a forward to the user itself and for a chain of forwards that loops. Role defaults and inventory overrides are checked alike; a `forward` that is still a Jinja expression is left to the mail provider, which reads it rendered. +- The lookup does not require a `mailbox` account on the named user, because it cannot tell whether the host runs a mail provider. The mail provider requires it. +- [Stalwart](../../../../../../roles/web-app-stalwart/README.md#aliases-and-forwards) honours the forward of every user it provisions an account for: the account keeps the mail and the named user's `email` receives a copy. Its deploy fails when the named user carries no `mailbox` account. A user without a Stalwart account gets no forward from Stalwart. + ## What Not To Do 🚫 - You MUST NOT create `group_vars/all/04_users.yml` or any similar generated users dictionary. @@ -91,7 +107,7 @@ users: | File | Purpose | |---|---| | [users.py](../../../../../../plugins/lookup/users.py) | Runtime entry point for the `users` lookup. | -| `utils/cache/users/` | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, and uniqueness validation. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py). | +| `utils/cache/users/` | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, uniqueness validation, and the validation of every `forward`. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py). | | [carrier.py](../../../../../../utils/cache/carrier.py) | The play-scoped carrier: fact name, `merged_users_cache_key`, and the reader that serves the carried payload. | | [test_users.py](../../../../../../tests/unit/python/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | diff --git a/roles/user-administrator/meta/users.yml b/roles/user-administrator/meta/users.yml index 1c42f7bc38..f9a170158f 100644 --- a/roles/user-administrator/meta/users.yml +++ b/roles/user-administrator/meta/users.yml @@ -8,6 +8,7 @@ platform_administrator: - administrator authorized_keys: [] accounts: [mailbox, identity] + forward: administrator administrator: description: System Administrator for {{ ORGANIZATION }} on {{ DOMAIN_PRIMARY }} diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 9dd23517e8..a6f77ccf49 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -252,9 +252,10 @@ applications: - Every other alias becomes a Stalwart mailing list described as `Infinito.Nexus alias`. The role creates, updates and removes only lists with that description; lists created in WebAdmin stay untouched, and declaring an address such a list already holds fails the deploy. - Destinations may lie outside the served domains; Stalwart relays those copies. - Alias domains must be served by Stalwart. -- A forward keeps the message in the account and sends a copy to every destination. The role writes the Sieve script `infinito-forward` (`redirect :copy`) into the account and activates it; a user script that was active is chained through `include`, so personal filters keep working. Removing a forward from the inventory leaves the script in place; delete `infinito-forward` in the account's filter settings to stop it. The role raises the user-script limits `maxRedirects` and `maxOutMessages` to the widest forward. +- A forward keeps the message in the account and sends a copy to every destination. The role writes the Sieve script `infinito-forward` (`redirect :copy`) into the account and activates it; a user script that was active is chained through `include`, so personal filters keep working. Removing a forward from the inventory leaves the script in place; delete `infinito-forward` in the account's filter settings to stop it. The role raises the user-script limits `maxRedirects` and `maxOutMessages` to the widest forward and reloads the settings; under SSO the restart of [`tasks/11_oidc_restart.yml`](tasks/11_oidc_restart.yml) applies them instead, because a reload opens the OIDC issuer and Keycloak deploys after Stalwart. +- Every user the role provisions an account for forwards the same way when its `forward` in the [users](../../docs/contributing/artefact/files/plugins/lookup/users.md) names another user: the account `@` keeps its mail and the `email` of the named user receives a copy. The named user MUST carry a `mailbox` account, otherwise the deploy fails. A forward declared under `services.stalwart.forwards` for the same account adds its destinations. The platform administrator forwards to the administrator, so the system mail addressed to `platformadmin` reaches the administrator's mailbox. -[`files/test/test.sh`](files/test/test.sh) sends through every declared alias, catch-all and forward and waits until each destination inside the mail domain holds its copy. An alias destination outside it counts once Stalwart queued the copy or the bounce naming it and the subject reaches the sender, which proves Stalwart expanded the alias and attempted the delivery. A forward destination outside it counts once the account's active Sieve script redirects a copy to it, because Stalwart sends no bounce for a message a Sieve script generated. Matrix **variant 1** declares one of each. +[`files/test/test.sh`](files/test/test.sh) sends through every declared alias, catch-all and forward, and waits until each destination inside the mail domain holds its copy. The forwards, those of the users included, are sent through only in the rounds that deploy Stalwart as a primary app. A transport error while sending or polling counts as not yet, within the same poll budget. An alias destination outside it counts once Stalwart queued the copy or the bounce naming it and the subject reaches the sender, which proves Stalwart expanded the alias and attempted the delivery. A forward destination outside it counts once the account's active Sieve script redirects a copy to it, because Stalwart sends no bounce for a message a Sieve script generated. Matrix **variant 1** declares one of each. ### Alias domains diff --git a/roles/web-app-stalwart/files/test/probe/stalwart.py b/roles/web-app-stalwart/files/test/probe/stalwart.py index 85d2b505a7..4fd6dd95a6 100755 --- a/roles/web-app-stalwart/files/test/probe/stalwart.py +++ b/roles/web-app-stalwart/files/test/probe/stalwart.py @@ -16,7 +16,8 @@ Args: run's copy for it or the bounce naming it and the subject reaches the sender. A forward destination outside MAIL_DOMAIN counts once the account's active Sieve script redirects a copy to it: Stalwart sends no - bounce for a message a Sieve script generated. + bounce for a message a Sieve script generated. A transport error while + sending or polling counts as not yet, within the same poll budget. Environment: STALWART_ADMIN_USER, STALWART_ADMIN_PASSWORD, STALWART_JMAP_URL, MAIL_DOMAIN and, for routing, ADMIN_EMAIL, STALWART_ALIASES_JSON, STALWART_FORWARDS_JSON. @@ -63,6 +64,7 @@ MONTHS = ( "Nov", "Dec", ) +TRANSIENT_ERRORS = (OSError, imaplib.IMAP4.error, smtplib.SMTPException) _FLAGS = re.compile(rb"FLAGS \(([^)]*)\)") _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) @@ -74,6 +76,10 @@ def env(name: str) -> str: return value +def describe(error: BaseException) -> str: + return f"{type(error).__name__}: {error}" + + def domain_of(address: str) -> str: return address.rpartition("@")[2] @@ -207,8 +213,18 @@ def send(sender: str, recipient: str, subject: str) -> None: mail["Date"] = email.utils.formatdate() mail["Message-ID"] = email.utils.make_msgid(domain=domain_of(sender)) mail.set_content(f"routing probe {subject}") - with smtplib.SMTP(HOST, SMTP_PORT, timeout=TIMEOUT) as smtp: - smtp.send_message(mail, from_addr=sender, to_addrs=[recipient]) + for attempt in range(1, POLL_ATTEMPTS + 1): + try: + with smtplib.SMTP(HOST, SMTP_PORT, timeout=TIMEOUT) as smtp: + smtp.send_message(mail, from_addr=sender, to_addrs=[recipient]) + break + except TRANSIENT_ERRORS as error: + if attempt == POLL_ATTEMPTS: + raise + print( + f"retry: {subject} -> {recipient}: {describe(error)}", file=sys.stderr + ) + time.sleep(POLL_DELAY) print(f"sent: {subject} -> {recipient}") @@ -258,12 +274,17 @@ def queued(destination: str, since: float) -> bool: def wait_for(description: str, probe) -> bool: + last_error = "" for _ in range(POLL_ATTEMPTS): - if probe(): - print(f"ok: {description}") - return True + try: + if probe(): + print(f"ok: {description}") + return True + except TRANSIENT_ERRORS as error: + last_error = describe(error) time.sleep(POLL_DELAY) - print(f"FAIL: {description}", file=sys.stderr) + suffix = f" (last error: {last_error})" if last_error else "" + print(f"FAIL: {description}{suffix}", file=sys.stderr) return False diff --git a/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py b/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py index 3b8bb1783f..66bf22624e 100644 --- a/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py +++ b/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py @@ -5,6 +5,7 @@ from typing import Any from ansible.errors import AnsibleFilterError +MAILBOX_ACCOUNT = "mailbox" _INCLUDE = re.compile(r'^include :personal "((?:[^"\\]|\\.)*)";$', re.MULTILINE) @@ -64,6 +65,54 @@ def stalwart_forwards(forwards: list[dict[str, Any]]) -> list[dict[str, Any]]: return normalised +def stalwart_user_forwards( + forwards: list[dict[str, Any]], users: dict[str, dict[str, Any]], domain: str +) -> list[dict[str, Any]]: + """Add the forward every Stalwart account's user declares. + + Args: + forwards: output of ``stalwart_forwards``. + users: the users Stalwart provisions an account for, keyed by user key; + a non-empty ``forward`` names the user whose ``email`` receives a + copy of the mail to ``@``, which MUST carry a + ``mailbox`` account. + domain: the mail domain the accounts live in. + + Returns: + ``forwards`` with each user's destination joined to the forward of its + account, normalised by ``stalwart_forwards``. + + Raises: + AnsibleFilterError: a forward to a user Stalwart provisions no account + for, to a user without a ``mailbox`` account, or any entry + ``stalwart_forwards`` refuses. + """ + merged = {forward["address"]: list(forward["destinations"]) for forward in forwards} + for key, user in sorted(users.items()): + target = user["forward"] + if not target: + continue + if target not in users: + raise AnsibleFilterError( + f"stalwart forwards: user {key} forwards to {target}, which is unknown " + f"or carries neither a mailbox account nor the bot role" + ) + accounts = users[target]["accounts"] + if not isinstance(accounts, (list, tuple)) or MAILBOX_ACCOUNT not in accounts: + raise AnsibleFilterError( + f"stalwart forwards: user {key} forwards to {target}, which carries " + f"no mailbox account (accounts={accounts!r})" + ) + address = f"{user['username']}@{domain}".lower() + merged.setdefault(address, []).append(users[target]["email"]) + return stalwart_forwards( + [ + {"address": address, "destinations": destinations} + for address, destinations in merged.items() + ] + ) + + def stalwart_forward_include( scripts: list[dict[str, Any]], own_name: str, own_content: str ) -> str: @@ -109,6 +158,7 @@ class FilterModule: def filters(self): return { "stalwart_forwards": stalwart_forwards, + "stalwart_user_forwards": stalwart_user_forwards, "stalwart_forward_include": stalwart_forward_include, "stalwart_forward_script": stalwart_forward_script, } diff --git a/roles/web-app-stalwart/tasks/16_forwards.yml b/roles/web-app-stalwart/tasks/16_forwards.yml index 1d5d584401..c98fb0817f 100644 --- a/roles/web-app-stalwart/tasks/16_forwards.yml +++ b/roles/web-app-stalwart/tasks/16_forwards.yml @@ -31,7 +31,11 @@ - name: "✅ Ensure every forwarding address is a Stalwart account" ansible.builtin.assert: that: stalwart_forward_missing | length == 0 - fail_msg: "Forwards are declared for addresses without a Stalwart account: {{ stalwart_forward_missing }}" + fail_msg: >- + Forwards are declared for addresses without a Stalwart account: {{ stalwart_forward_missing | join(', ') }}. + A forward comes from services.stalwart.forwards or from a user's `forward` in the users catalogue. + Under SSO, an account added after the switch is never created before its first OIDC sign-in + (see the accounts entry in roles/web-app-stalwart/TODO.md); sign that user in once, or drop its forward. quiet: true vars: stalwart_forward_missing: "{{ STALWART_FORWARDS | map(attribute='address') | reject('in', stalwart_forward_account_ids) | list }}" @@ -49,8 +53,10 @@ 'maxOutMessages': stalwart_sieve_limits.maxOutMessages | int }}}, 'c0']]} | to_json }} + # Under SSO a reload rebuilds the directories and opens the OIDC issuer before Keycloak runs, so x:Action answers notCreated; 11_oidc_restart.yml applies the limits then. - name: "🔄 Reload Stalwart's settings" include_tasks: jmap_call.yml + when: not (STALWART_SSO_ENABLED | bool) vars: stalwart_jmap_body: >- {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], diff --git a/roles/web-app-stalwart/templates/test.env.j2 b/roles/web-app-stalwart/templates/test.env.j2 index 1b93bba856..174070f899 100644 --- a/roles/web-app-stalwart/templates/test.env.j2 +++ b/roles/web-app-stalwart/templates/test.env.j2 @@ -26,7 +26,7 @@ STALWART_ADMIN_USER={{ STALWART_ADMIN_USER | quote }} STALWART_ALIASES_JSON={{ STALWART_ALIASES | to_json | quote }} -STALWART_FORWARDS_JSON={{ STALWART_FORWARDS | to_json | quote }} +STALWART_FORWARDS_JSON={{ (STALWART_FORWARDS if application_id in PRIMARY_APPS else []) | to_json | quote }} STALWART_IMPORT_WORKERS={{ STALWART_IMPORT_WORKERS | quote }} diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 7c135dfe52..8e33484388 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -140,7 +140,9 @@ STALWART_IMPORT_WORKERS: "{{ lookup('config', application_id, 'services.stalwart STALWART_ALIASES: "{{ lookup('config', application_id, 'services.stalwart.aliases') | stalwart_aliases }}" STALWART_ALIAS_DESCRIPTION: "Infinito.Nexus alias" -STALWART_FORWARDS: "{{ lookup('config', application_id, 'services.stalwart.forwards') | stalwart_forwards }}" +STALWART_FORWARDS: >- + {{ lookup('config', application_id, 'services.stalwart.forwards') | stalwart_forwards + | stalwart_user_forwards(STALWART_USERS, STALWART_DOMAIN) }} STALWART_FORWARD_SCRIPT_NAME: "infinito-forward" STALWART_ALIAS_DOMAINS: "{{ lookup('config', application_id, 'services.stalwart.alias_domains') }}" STALWART_RCPT_REWRITE: "{{ STALWART_ALIAS_DOMAINS | stalwart_rcpt_rewrite }}" diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_probe_stalwart.py b/tests/unit/python/roles/web-app-stalwart/files/test_probe_stalwart.py new file mode 100644 index 0000000000..dbc4799b72 --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/files/test_probe_stalwart.py @@ -0,0 +1,127 @@ +import contextlib +import imaplib +import importlib.util +import io +import smtplib +import ssl +import unittest +import unittest.mock as mock +import urllib.error + +from . import PROJECT_ROOT + + +def _load_module(): + path = PROJECT_ROOT / "roles/web-app-stalwart/files/test/probe/stalwart.py" + spec = importlib.util.spec_from_file_location("stalwart_probe", str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +_M = _load_module() + + +def _probe(*outcomes): + calls = iter(outcomes) + + def probe(): + outcome = next(calls) + if isinstance(outcome, BaseException): + raise outcome + return outcome + + return probe + + +class TestWaitFor(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(_M.time, "sleep") + self.sleep = patcher.start() + self.addCleanup(patcher.stop) + + def _run(self, probe): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + result = _M.wait_for("probe", probe) + return result, out.getvalue(), err.getvalue() + + def test_transport_error_counts_as_not_yet(self): + result, out, _ = self._run(_probe(ConnectionRefusedError("refused"), True)) + self.assertTrue(result) + self.assertIn("ok: probe", out) + + def test_imap_abort_counts_as_not_yet(self): + result, _, _ = self._run(_probe(imaplib.IMAP4.abort("socket error"), True)) + self.assertTrue(result) + + def test_imap_login_error_counts_as_not_yet(self): + result, _, _ = self._run(_probe(imaplib.IMAP4.error("LOGIN failed"), True)) + self.assertTrue(result) + + def test_tls_and_http_errors_count_as_not_yet(self): + probe = _probe(ssl.SSLError("EOF"), urllib.error.URLError("reset"), True) + result, _, _ = self._run(probe) + self.assertTrue(result) + + def test_smtp_error_counts_as_not_yet(self): + result, _, _ = self._run(_probe(smtplib.SMTPServerDisconnected("gone"), True)) + self.assertTrue(result) + + def test_exhausted_budget_fails_with_the_last_error(self): + outcomes = [False] * (_M.POLL_ATTEMPTS - 1) + [TimeoutError("timed out")] + result, _, err = self._run(_probe(*outcomes)) + self.assertFalse(result) + self.assertIn("FAIL: probe (last error: TimeoutError: timed out)", err) + + def test_errors_share_the_poll_budget(self): + probe = mock.Mock(side_effect=OSError("down")) + result, _, _ = self._run(probe) + self.assertFalse(result) + self.assertEqual(probe.call_count, _M.POLL_ATTEMPTS) + + def test_fail_without_error_names_none(self): + result, _, err = self._run(lambda: False) + self.assertFalse(result) + self.assertIn("FAIL: probe\n", err) + + def test_non_transport_error_propagates(self): + with self.assertRaises(KeyError): + self._run(_probe(KeyError("primaryAccounts"))) + + +class TestSend(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(_M.time, "sleep") + patcher.start() + self.addCleanup(patcher.stop) + + def _send(self, smtp): + out, err = io.StringIO(), io.StringIO() + with ( + mock.patch.object(_M.smtplib, "SMTP", smtp), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(err), + ): + _M.send("a@example.org", "b@example.org", "subject") + return out.getvalue(), err.getvalue() + + def test_send_retries_after_a_transport_error(self): + session = mock.MagicMock() + smtp = mock.Mock(side_effect=[ConnectionRefusedError("refused"), session]) + out, err = self._send(smtp) + self.assertEqual(smtp.call_count, 2) + session.__enter__.return_value.send_message.assert_called_once() + self.assertIn("retry: subject -> b@example.org", err) + self.assertIn("sent: subject -> b@example.org", out) + + def test_send_raises_once_the_budget_is_spent(self): + smtp = mock.Mock(side_effect=smtplib.SMTPServerDisconnected("gone")) + with self.assertRaises(smtplib.SMTPServerDisconnected): + self._send(smtp) + self.assertEqual(smtp.call_count, _M.POLL_ATTEMPTS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/filter_plugins/test_stalwart_forwards.py b/tests/unit/python/roles/web-app-stalwart/filter_plugins/test_stalwart_forwards.py index 704fc7c2c6..bcb984908b 100644 --- a/tests/unit/python/roles/web-app-stalwart/filter_plugins/test_stalwart_forwards.py +++ b/tests/unit/python/roles/web-app-stalwart/filter_plugins/test_stalwart_forwards.py @@ -54,6 +54,102 @@ class TestStalwartForwards(unittest.TestCase): ) +class TestStalwartUserForwards(unittest.TestCase): + def setUp(self): + self.user_forwards = _load().stalwart_user_forwards + + @staticmethod + def _users(**forwards): + return { + "platform_administrator": { + "username": "platformadmin", + "email": "platformadmin@example.org", + "accounts": ["mailbox", "identity"], + "forward": forwards.get("platform_administrator", ""), + }, + "administrator": { + "username": "administrator", + "email": "Administrator@example.org", + "accounts": ["host", "mailbox", "identity"], + "forward": forwards.get("administrator", ""), + }, + "submitter": { + "username": "submitter", + "email": "submitter@example.org", + "accounts": ["identity"], + "forward": forwards.get("submitter", ""), + }, + } + + def test_users_without_forward_add_nothing(self): + self.assertEqual(self.user_forwards([], self._users(), "example.org"), []) + + def test_forward_copies_the_account_mail_to_the_target_email(self): + users = self._users(platform_administrator="administrator") + self.assertEqual( + self.user_forwards([], users, "Example.org"), + [ + { + "address": "platformadmin@example.org", + "destinations": ["administrator@example.org"], + } + ], + ) + + def test_forward_address_is_the_account_not_the_email(self): + users = self._users(platform_administrator="administrator") + users["platform_administrator"]["email"] = "ops@elsewhere.example" + self.assertEqual( + self.user_forwards([], users, "mail.example")[0]["address"], + "platformadmin@mail.example", + ) + + def test_declared_forward_of_the_same_account_is_joined(self): + declared = [ + {"address": "platformadmin@example.org", "destinations": ["ops@x.org"]} + ] + users = self._users(platform_administrator="administrator") + self.assertEqual( + self.user_forwards(declared, users, "example.org"), + [ + { + "address": "platformadmin@example.org", + "destinations": ["administrator@example.org", "ops@x.org"], + } + ], + ) + + def test_declared_forwards_come_first(self): + declared = [{"address": "carol@example.org", "destinations": ["c@x.org"]}] + users = self._users(platform_administrator="administrator") + self.assertEqual( + [f["address"] for f in self.user_forwards(declared, users, "example.org")], + ["carol@example.org", "platformadmin@example.org"], + ) + + def test_forward_to_an_unknown_user_is_rejected(self): + users = self._users(platform_administrator="breakglass") + with self.assertRaisesRegex(AnsibleFilterError, "breakglass, which is unknown"): + self.user_forwards([], users, "example.org") + + def test_forward_to_a_user_without_mailbox_is_rejected(self): + users = self._users(platform_administrator="submitter") + with self.assertRaisesRegex(AnsibleFilterError, "carries no mailbox account"): + self.user_forwards([], users, "example.org") + + def test_forward_to_a_user_with_unlisted_accounts_is_rejected(self): + users = self._users(platform_administrator="administrator") + users["administrator"]["accounts"] = "mailbox" + with self.assertRaisesRegex(AnsibleFilterError, "carries no mailbox account"): + self.user_forwards([], users, "example.org") + + def test_forward_onto_the_own_account_is_rejected(self): + users = self._users(platform_administrator="administrator") + users["administrator"]["email"] = "platformadmin@example.org" + with self.assertRaises(AnsibleFilterError): + self.user_forwards([], users, "example.org") + + class TestForwardInclude(unittest.TestCase): def setUp(self): self.include = _load().stalwart_forward_include diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index c2f283ab95..b1d99e36fe 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -2,7 +2,7 @@ Pins the public API (`get_user_defaults`, `get_merged_users`) plus the internal helpers that only this module owns: `_load_user_defs`, -`_build_users`, `_compute_reserved_usernames`, `_load_store_users`, +`_build_users`, `_validate_forwards`, `_compute_reserved_usernames`, `_load_store_users`, `_resolve_tokens_file`, `_hydrate_users_tokens`, `_merge_users`, `_materialize_domain_label_reservations`. Module name is `test_users_module` to disambiguate from the existing `tests/unit/python/plugins/lookup/test_users.py` @@ -201,7 +201,7 @@ class TestBuildUsers(unittest.TestCase): ("plain", {}), ("botuser", {"roles": ["bot"]}), ("adminuser", {"roles": ["administrator"]}), - ("pinned", {"accounts": ["host"], "forward": "plain"}), + ("pinned", {"accounts": ["host"], "forward": "adminuser"}), ("empty", {"accounts": []}), ] ) @@ -214,7 +214,74 @@ class TestBuildUsers(unittest.TestCase): self.assertEqual(users["pinned"]["accounts"], ["host"]) self.assertEqual(users["empty"]["accounts"], []) self.assertEqual(users["plain"]["forward"], "") - self.assertEqual(users["pinned"]["forward"], "plain") + self.assertEqual(users["pinned"]["forward"], "adminuser") + + def test_forward_to_an_unknown_user_raises(self): + defs = OrderedDict([("pinned", {"accounts": [], "forward": "nobody"})]) + with self.assertRaisesRegex(ValueError, "'pinned' forwards to unknown user"): + cache_users._build_users( + defs, primary_domain="x.example", start_id=1001, become_pwd="pw" + ) + + +class TestValidateForwards(unittest.TestCase): + @staticmethod + def _user(forward="", accounts=("mailbox",)): + return {"forward": forward, "accounts": list(accounts)} + + def test_users_without_forward_pass(self): + cache_users._validate_forwards({"a": self._user(), "b": self._user()}) + + def test_forward_to_a_known_user_passes(self): + cache_users._validate_forwards( + {"a": self._user("b", accounts=()), "b": self._user()} + ) + + def test_chain_of_forwards_passes(self): + cache_users._validate_forwards( + {"a": self._user("b", accounts=()), "b": self._user("c"), "c": self._user()} + ) + + def test_forward_to_a_user_without_mailbox_passes(self): + cache_users._validate_forwards( + {"a": self._user("b"), "b": self._user(accounts=("host", "identity"))} + ) + + def test_forward_to_unknown_user_raises(self): + with self.assertRaisesRegex(ValueError, "'a' forwards to unknown user 'x'"): + cache_users._validate_forwards({"a": self._user("x")}) + + def test_unrendered_forward_is_left_to_the_consumer(self): + cache_users._validate_forwards({"a": self._user("{{ 'nobody' }}")}) + + def test_unrendered_statement_forward_is_left_to_the_consumer(self): + cache_users._validate_forwards({"a": self._user("{% if x %}nobody{% endif %}")}) + + def test_unrendered_forward_ends_the_chain(self): + cache_users._validate_forwards( + {"a": self._user("b"), "b": self._user("{{ 'a' }}")} + ) + + def test_forward_to_a_non_mapping_entry_raises_a_clear_error(self): + with self.assertRaisesRegex( + TypeError, "'a' forwards to 'b', whose entry is None" + ): + cache_users._validate_forwards({"a": self._user("b"), "b": None}) + + def test_forward_to_itself_raises(self): + with self.assertRaisesRegex(ValueError, "Forward loop: a -> a"): + cache_users._validate_forwards({"a": self._user("a")}) + + def test_forward_cycle_raises(self): + with self.assertRaisesRegex(ValueError, "Forward loop: a -> b -> a"): + cache_users._validate_forwards({"a": self._user("b"), "b": self._user("a")}) + + def test_non_string_forward_raises(self): + with self.assertRaisesRegex(TypeError, "a user key is required"): + cache_users._validate_forwards({"a": self._user(["b"]), "b": self._user()}) + + def test_non_mapping_user_is_skipped(self): + cache_users._validate_forwards({"a": None, "b": self._user()}) class TestMergeUsers(unittest.TestCase): @@ -376,6 +443,68 @@ class TestGetMergedUsersWithOverrides(unittest.TestCase): ) self.assertEqual(merged["foo"]["username"], "override-user") + def test_runtime_forward_to_an_unknown_user_raises(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp), "web-app-foo") + with self.assertRaisesRegex(ValueError, "'foo' forwards to unknown user"): + cache_users.get_merged_users( + variables={"users": {"foo": {"forward": "nobody"}}}, + roles_dir=roles, + templar=None, + ) + + def test_runtime_forward_to_an_inventory_mailbox_is_kept(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp), "web-app-foo") + merged = cache_users.get_merged_users( + variables={ + "users": { + "foo": {"forward": "inbox"}, + "inbox": {"accounts": ["mailbox"]}, + } + }, + roles_dir=roles, + templar=None, + ) + self.assertEqual(merged["foo"]["forward"], "inbox") + + def test_runtime_target_without_mailbox_keeps_the_lookup(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp), "web-app-foo") + merged = cache_users.get_merged_users( + variables={ + "users": { + "foo": {"forward": "workstation"}, + "workstation": {"accounts": ["host", "identity"]}, + } + }, + roles_dir=roles, + templar=None, + ) + self.assertEqual(merged["workstation"]["accounts"], ["host", "identity"]) + + def test_runtime_templated_forward_is_not_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp), "web-app-foo") + merged = cache_users.get_merged_users( + variables={"users": {"foo": {"forward": "{{ 'inbox' }}"}}}, + roles_dir=roles, + templar=None, + ) + self.assertEqual(merged["foo"]["forward"], "{{ 'inbox' }}") + + def test_runtime_null_target_raises_a_clear_error(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp), "web-app-foo") + with self.assertRaisesRegex( + TypeError, "'foo' forwards to 'inbox', whose entry" + ): + cache_users.get_merged_users( + variables={"users": {"foo": {"forward": "inbox"}, "inbox": None}}, + roles_dir=roles, + templar=None, + ) + class TestGetMergedUsersTokenSource(unittest.TestCase): def setUp(self) -> None: diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index 5fbb5aa923..7b89ae3918 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -74,6 +74,51 @@ def _apply_account_defaults(users: dict[str, Any]) -> dict[str, Any]: return users +def _validate_forwards(users: Mapping[str, Any]) -> None: + """Refuse a ``forward`` that names no user. + + Args: + users: users keyed by canonical key, before rendering; ``forward`` + names the key of the user that receives the mail sent to this + user, '' for none. A forward that is still a Jinja expression is + left to the consumer, which sees it rendered. + + Raises: + TypeError: a forward that is no string, or a forward to a user whose + entry is no mapping, as ``_load_user_defs`` raises for one. + ValueError: a forward to an unknown user, or a chain of forwards that + returns to a user it already passed. + """ + for key, user in users.items(): + if not isinstance(user, Mapping): + continue + chain = [key] + target = user["forward"] + while target: + if not isinstance(target, str): + raise TypeError( + f"User '{chain[-1]}' declares forward={target!r}; a user key is required" + ) + if "{{" in target or "{%" in target: + break + if target in chain: + raise ValueError( + f"Forward loop: {' -> '.join([*chain, target])} in merged users" + ) + if target not in users: + raise ValueError( + f"User '{chain[-1]}' forwards to unknown user '{target}'" + ) + receiver = users[target] + if not isinstance(receiver, Mapping): + raise TypeError( + f"User '{chain[-1]}' forwards to '{target}', whose entry is " + f"{receiver!r} instead of a mapping" + ) + chain.append(target) + target = receiver["forward"] + + def _compute_reserved_usernames(roles_dir: Path) -> list[str]: reserved: set[str] = set() for role_dir in roles_dir.iterdir(): @@ -208,6 +253,7 @@ def _build_users( seen_usernames.add(username) seen_emails.add(email) + _validate_forwards(users) return users @@ -445,6 +491,7 @@ def get_merged_users( overrides = _resolve_override_mapping(variables, "users", templar=templar) merged = _apply_account_defaults(_merge_users(defaults, overrides)) + _validate_forwards(merged) hydrated = _hydrate_users_tokens( merged, dict(snapshot) if snapshot is not None else _load_store_users(tokens_file),