diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index 64efc9103c..6f8bc9e177 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -91,8 +91,9 @@ platform_administrator: ``` - `forward` is `''` unless declared, which forwards nothing. -- The named user MUST exist and MUST carry a `mailbox` account. The lookup raises otherwise, and also for a forward to the user itself or a chain of forwards that loops. Role defaults and inventory overrides are checked alike. -- [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. A user without a Stalwart account gets no forward from Stalwart. +- 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 🚫 diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 6fb75ba9ab..94e5c67591 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -252,10 +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. -- 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. 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. +- 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, the forwards of the users included, 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 2599c8082a..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) @@ -73,7 +74,8 @@ def stalwart_user_forwards( 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 ``@``. + copy of the mail to ``@``, which MUST carry a + ``mailbox`` account. domain: the mail domain the accounts live in. Returns: @@ -81,8 +83,9 @@ def stalwart_user_forwards( account, normalised by ``stalwart_forwards``. Raises: - AnsibleFilterError: a forward to a user Stalwart holds no account for, - or any entry ``stalwart_forwards`` refuses. + 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()): @@ -91,7 +94,14 @@ def stalwart_user_forwards( continue if target not in users: raise AnsibleFilterError( - f"stalwart forwards: user {key} forwards to {target}, which has no Stalwart account" + 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"]) 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/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 ba77e74618..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 @@ -64,13 +64,21 @@ class TestStalwartUserForwards(unittest.TestCase): "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): @@ -119,9 +127,20 @@ class TestStalwartUserForwards(unittest.TestCase): ["carol@example.org", "platformadmin@example.org"], ) - def test_forward_to_a_user_without_stalwart_account_is_rejected(self): + def test_forward_to_an_unknown_user_is_rejected(self): users = self._users(platform_administrator="breakglass") - with self.assertRaisesRegex(AnsibleFilterError, "has no Stalwart account"): + 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): diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index 66cfd9975d..b1d99e36fe 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -216,11 +216,9 @@ class TestBuildUsers(unittest.TestCase): self.assertEqual(users["plain"]["forward"], "") self.assertEqual(users["pinned"]["forward"], "adminuser") - def test_forward_to_a_user_without_mailbox_raises(self): - defs = OrderedDict( - [("plain", {}), ("pinned", {"accounts": [], "forward": "plain"})] - ) - with self.assertRaisesRegex(ValueError, "'plain', which carries no mailbox"): + 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" ) @@ -234,25 +232,41 @@ class TestValidateForwards(unittest.TestCase): def test_users_without_forward_pass(self): cache_users._validate_forwards({"a": self._user(), "b": self._user()}) - def test_forward_to_a_mailbox_passes(self): + 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_to_mailboxes_passes(self): + 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_forward_to_user_without_mailbox_raises(self): - with self.assertRaisesRegex(ValueError, "carries no mailbox account"): - cache_users._validate_forwards( - {"a": self._user("b"), "b": self._user(accounts=("identity",))} - ) + 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"): @@ -454,6 +468,43 @@ class TestGetMergedUsersWithOverrides(unittest.TestCase): ) 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 162b5e7f00..7b89ae3918 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -75,17 +75,19 @@ def _apply_account_defaults(users: dict[str, Any]) -> dict[str, Any]: def _validate_forwards(users: Mapping[str, Any]) -> None: - """Refuse a ``forward`` that leads to no mailbox. + """Refuse a ``forward`` that names no user. Args: - users: users keyed by canonical key; ``forward`` names the key of the - user that receives the mail sent to this user, '' for none. + 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. - ValueError: a forward to an unknown user or a user without a - ``mailbox`` account, or a chain of forwards that returns to a user - it already passed. + 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): @@ -97,6 +99,8 @@ def _validate_forwards(users: Mapping[str, Any]) -> None: 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" @@ -106,11 +110,10 @@ def _validate_forwards(users: Mapping[str, Any]) -> None: f"User '{chain[-1]}' forwards to unknown user '{target}'" ) receiver = users[target] - accounts = receiver["accounts"] - if not isinstance(accounts, (list, tuple)) or "mailbox" not in accounts: - raise ValueError( - f"User '{chain[-1]}' forwards to '{target}', which carries no " - f"mailbox account" + 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"]