diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index d60c79c006..64efc9103c 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -79,6 +79,21 @@ 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 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. + ## What Not To Do 🚫 - You MUST NOT create `group_vars/all/04_users.yml` or any similar generated users dictionary. @@ -91,7 +106,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 62f7b6c21e..6fb75ba9ab 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -253,8 +253,9 @@ applications: - 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. -[`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, 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. ### Alias domains diff --git a/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py b/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py index 3b8bb1783f..2599c8082a 100644 --- a/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py +++ b/roles/web-app-stalwart/filter_plugins/stalwart_forwards.py @@ -64,6 +64,45 @@ 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 ``@``. + 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 holds no account for, + 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 has no Stalwart account" + ) + 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 +148,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/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 41a92f9b1e..9eefc72ed3 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -138,7 +138,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/filter_plugins/test_stalwart_forwards.py b/tests/unit/python/roles/web-app-stalwart/filter_plugins/test_stalwart_forwards.py index 704fc7c2c6..ba77e74618 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,83 @@ 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", + "forward": forwards.get("platform_administrator", ""), + }, + "administrator": { + "username": "administrator", + "email": "Administrator@example.org", + "forward": forwards.get("administrator", ""), + }, + } + + 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_a_user_without_stalwart_account_is_rejected(self): + users = self._users(platform_administrator="breakglass") + with self.assertRaisesRegex(AnsibleFilterError, "has no Stalwart 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..66cfd9975d 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,60 @@ 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_a_user_without_mailbox_raises(self): + defs = OrderedDict( + [("plain", {}), ("pinned", {"accounts": [], "forward": "plain"})] + ) + with self.assertRaisesRegex(ValueError, "'plain', which carries no mailbox"): + 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_mailbox_passes(self): + cache_users._validate_forwards( + {"a": self._user("b", accounts=()), "b": self._user()} + ) + + def test_chain_of_forwards_to_mailboxes_passes(self): + cache_users._validate_forwards( + {"a": self._user("b", accounts=()), "b": self._user("c"), "c": self._user()} + ) + + 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_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 +429,31 @@ 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") + class TestGetMergedUsersTokenSource(unittest.TestCase): def setUp(self) -> None: diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index 5fbb5aa923..162b5e7f00 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -74,6 +74,48 @@ 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 leads to no mailbox. + + Args: + users: users keyed by canonical key; ``forward`` names the key of the + user that receives the mail sent to this user, '' for none. + + 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. + """ + 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 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] + 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" + ) + 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 +250,7 @@ def _build_users( seen_usernames.add(username) seen_emails.add(email) + _validate_forwards(users) return users @@ -445,6 +488,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),