diff --git a/cli/administration/inventory/provision/cli.py b/cli/administration/inventory/provision/cli.py index 05a8bfa4c6..c60e90df76 100644 --- a/cli/administration/inventory/provision/cli.py +++ b/cli/administration/inventory/provision/cli.py @@ -240,7 +240,7 @@ def main(argv: list[str] | None = None) -> int: print( f"[INFO] Pinning a password for every user the {len(application_ids)} " - "resolved applications declare..." + "resolved applications declare and every catalogue user holding an account..." ) pinned = generate_user_passwords( roles_dir=roles_dir, diff --git a/cli/administration/inventory/provision/reset.py b/cli/administration/inventory/provision/reset.py index 54e5bfba82..ea0f570aa5 100644 --- a/cli/administration/inventory/provision/reset.py +++ b/cli/administration/inventory/provision/reset.py @@ -160,7 +160,7 @@ def _drop_user_passwords( application_ids: list[str], exclude: set[str], ) -> int: - """Remove the pinned password of every user the resolved roles declare. + """Remove the pinned password of every user the deployment needs pinned. Args: document: the host_vars document. @@ -171,9 +171,9 @@ def _drop_user_passwords( Returns: How many passwords were removed. - Only declared users are dropped, because only those get a new password - pinned afterwards; a user that exists solely in the inventory would lose - its password with nothing to put it back. + Only the users ``required_user_policies`` names are dropped, because only + those get a new password pinned afterwards; a user that exists solely in + the inventory would lose its password with nothing to put it back. """ users = document.get("users") if not isinstance(users, CommentedMap): diff --git a/cli/administration/inventory/provision/users_generator.py b/cli/administration/inventory/provision/users_generator.py index 07f557ecb6..1164eb9eb6 100644 --- a/cli/administration/inventory/provision/users_generator.py +++ b/cli/administration/inventory/provision/users_generator.py @@ -1,4 +1,4 @@ -"""Pin a password on every user the resolved role set needs. +"""Pin a password on every user a deployment creates or authenticates. A user definition that declares no password falls back to ``{{ 42 | strong_password }}``. That is a template, not a value: it is @@ -10,8 +10,9 @@ that are already generated there. from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any +from utils.cache.users import get_user_defaults from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_USERS @@ -21,28 +22,19 @@ from .ruamel_io import dump_document, ensure_map, load_document, vault_value if TYPE_CHECKING: from pathlib import Path +BOT_ROLE = "bot" -def required_user_policies( - roles_dir: Path, application_ids: list[str] -) -> dict[str, dict[str, str | None]]: - """Return every declared username with the password policy it asks for. + +def _declarations( + roles_dir: Path, +) -> dict[str, list[tuple[Path, dict[str, Any]]]]: + """Return every role's declaration of every user, keyed by username. Args: roles_dir: directory the roles live in. - application_ids: the roles resolved into this inventory. - - A role that declares no users contributes none, so the result follows the - deployment rather than everything the repository could ever deploy. Two - roles sharing a user must agree on its policy: the account is one thing, so - silently picking one declaration would hand the other role a password its - application rejects. """ - policies: dict[str, dict[str, str | None]] = {} - sources: dict[str, Path] = {} - for application_id in application_ids: - users_file = roles_dir / application_id / ROLE_FILE_META_USERS - if not users_file.exists(): - continue + declarations: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for users_file in sorted(roles_dir.glob(f"*/{ROLE_FILE_META_USERS}")): declared = load_yaml_any(users_file) if not isinstance(declared, dict): continue @@ -51,26 +43,94 @@ def required_user_policies( raise SystemExit( f"Invalid definition for user {username!r} in {users_file}" ) - name = str(username) - declared = overrides.get("password") - policy = ( - { - "algorithm": declared.get("algorithm"), - "validation": declared.get("validation"), - } - if isinstance(declared, dict) - else {"algorithm": None, "validation": None} + declarations.setdefault(str(username), []).append((users_file, overrides)) + return declarations + + +def _policy( + username: str, declarations: list[tuple[Path, dict[str, Any]]] +) -> dict[str, str | None]: + """Return the password policy the declarations of one user agree on. + + Args: + username: the user the declarations belong to. + declarations: every role's declaration of that user. + + Two roles sharing a user must agree on its policy: the account is one + thing, so silently picking one declaration would hand the other role a + password its application rejects. A declaration without a policy agrees + with any. + """ + policy: dict[str, str | None] = {"algorithm": None, "validation": None} + source: Path | None = None + for users_file, overrides in declarations: + declared = overrides.get("password") + if not isinstance(declared, dict): + continue + candidate = { + "algorithm": declared.get("algorithm"), + "validation": declared.get("validation"), + } + if not any(candidate.values()): + continue + if source is not None and candidate != policy: + raise SystemExit( + f"user {username!r} carries conflicting password policies: " + f"{source} asks for {policy}, {users_file} for {candidate}" ) - known = policies.get(name) - if known is not None and known != policy and any(policy.values()): - raise SystemExit( - f"user {name!r} carries conflicting password policies: " - f"{sources[name]} asks for {known}, {users_file} for {policy}" - ) - if known is None or any(policy.values()): - policies[name] = policy - sources[name] = users_file - return dict(sorted(policies.items())) + policy, source = candidate, users_file + return policy + + +def _provisioned_users(roles_dir: Path) -> set[str]: + """Return every user that holds an account or is a bot, deployed role or not. + + Args: + roles_dir: directory the roles live in. + + The directory and the mail providers iterate ``lookup('users')``, the + catalogue of every role, so a bot whose declaring role this inventory never + deploys still gets a mailbox and a submission token. + """ + return { + username + for username, user in get_user_defaults(roles_dir=roles_dir).items() + if user["accounts"] or BOT_ROLE in user["roles"] + } + + +def required_user_policies( + roles_dir: Path, application_ids: list[str] +) -> dict[str, dict[str, str | None]]: + """Return every username the deployment needs pinned, with its policy. + + Args: + roles_dir: directory the roles live in. + application_ids: the roles resolved into this inventory. + + A user is needed when a resolved role declares it, or when it holds an + account or is a bot and no role states its password outright. + """ + resolved = { + roles_dir / application_id / ROLE_FILE_META_USERS + for application_id in application_ids + } + declarations = _declarations(roles_dir) + policies = { + username: _policy(username, declared) + for username, declared in declarations.items() + } + provisioned = _provisioned_users(roles_dir) + + required: dict[str, dict[str, str | None]] = {} + for username, declared in declarations.items(): + by_resolved_role = any(users_file in resolved for users_file, _ in declared) + stated = any( + isinstance(overrides.get("password"), str) for _, overrides in declared + ) + if by_resolved_role or (username in provisioned and not stated): + required[username] = policies[username] + return dict(sorted(required.items())) def generate_user_passwords( diff --git a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py index d503658a5c..ccbbaabb72 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py @@ -1,8 +1,10 @@ +import importlib.util import re import shutil import tempfile import unittest from pathlib import Path +from typing import ClassVar from unittest.mock import patch from ruamel.yaml import YAML @@ -20,7 +22,10 @@ from cli.administration.inventory.provision.users_generator import ( required_user_policies, ) from cli.administration.inventory.validate.users import compare_user_keys +from plugins.filter.reserved_users import non_reserved_users +from utils.cache import ROLES_DIR from utils.cache.files import read_text +from utils.cache.users import get_user_defaults from utils.roles.mapping import ROLE_FILE_META_USERS MODULE = "cli.administration.inventory.provision.users_generator" @@ -69,16 +74,81 @@ def _write_role_users(roles_dir: Path, application_id: str, body: str) -> None: class TestRequiredUserPolicies(unittest.TestCase): - def test_only_the_resolved_roles_contribute(self): + def test_a_reservation_of_an_unresolved_role_is_not_required(self): with tempfile.TemporaryDirectory() as tmpdir: roles_dir = Path(tmpdir) _write_role_users(roles_dir, "web-app-a", "alice: {}\n") - _write_role_users(roles_dir, "web-app-b", "bob: {}\n") + _write_role_users(roles_dir, "web-app-b", "bob:\n accounts: []\n") self.assertEqual( ["alice"], list(required_user_policies(roles_dir, ["web-app-a"])) ) + def test_a_reservation_of_a_resolved_role_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, "web-app-a", "stalwartadmin:\n accounts: []\n" + ) + + self.assertEqual( + ["stalwartadmin"], + list(required_user_policies(roles_dir, ["web-app-a"])), + ) + + def test_a_bot_of_an_unresolved_role_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "alice: {}\n") + _write_role_users( + roles_dir, + "web-app-b", + "no-reply:\n roles: [bot]\n accounts: [mailbox]\n", + ) + + self.assertIn("no-reply", required_user_policies(roles_dir, ["web-app-a"])) + + def test_a_bot_without_an_account_of_its_own_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, "web-app-b", "relay:\n roles: [bot]\n accounts: []\n" + ) + + self.assertEqual(["relay"], list(required_user_policies(roles_dir, []))) + + def test_an_identity_user_of_an_unresolved_role_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-b", "hermes: {}\n") + + self.assertEqual(["hermes"], list(required_user_policies(roles_dir, []))) + + def test_a_password_an_unresolved_role_states_outright_is_left_to_it(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-b", + "breakglass:\n password: '{{ ansible_become_password }}'\n", + ) + + self.assertEqual({}, required_user_policies(roles_dir, [])) + + def test_a_provisioned_user_takes_the_policy_of_its_unresolved_role(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-b", + "relay:\n roles: [bot]\n password:\n algorithm: alphanumeric\n", + ) + + self.assertEqual( + {"relay": {"algorithm": "alphanumeric", "validation": None}}, + required_user_policies(roles_dir, []), + ) + def test_a_user_declared_by_two_roles_appears_once(self): with tempfile.TemporaryDirectory() as tmpdir: roles_dir = Path(tmpdir) @@ -158,15 +228,30 @@ class TestGenerateUserPasswords(unittest.TestCase): node = doc["users"][username]["password"] self.assertEqual("!vault", getattr(node, "tag", None)) - def test_a_user_of_an_unresolved_role_is_not_pinned(self): + def test_a_reservation_of_an_unresolved_role_is_not_pinned(self): count, doc = self._run( - {"web-app-a": "alice: {}\n", "web-app-b": "bob: {}\n"}, ["web-app-a"] + {"web-app-a": "alice: {}\n", "web-app-b": "bob:\n accounts: []\n"}, + ["web-app-a"], ) self.assertEqual(1, count) self.assertIn("alice", doc["users"]) self.assertNotIn("bob", doc["users"]) + def test_a_bot_of_an_unresolved_role_is_pinned(self): + count, doc = self._run( + { + "web-app-a": "alice:\n accounts: []\n", + "web-app-b": "no-reply:\n roles: [bot]\n accounts: [mailbox]\n", + }, + ["web-app-a"], + ) + + self.assertEqual(2, count) + self.assertEqual( + "!vault", getattr(doc["users"]["no-reply"]["password"], "tag", None) + ) + def test_an_existing_password_is_never_overwritten(self): existing = CommentedMap() users = CommentedMap() @@ -239,7 +324,7 @@ class TestGenerateUserPasswords(unittest.TestCase): self.assertIs(True, doc["TLS_ENABLED"]) def test_no_required_users_writes_no_file(self): - count, doc = self._run({"web-app-a": "alice: {}\n"}, []) + count, doc = self._run({"web-app-a": "alice:\n accounts: []\n"}, []) self.assertEqual(0, count) self.assertIsNone(doc) @@ -514,6 +599,23 @@ class TestDeclaredPasswordPolicy(unittest.TestCase): ], ) + def test_a_role_that_asks_for_nothing_first_does_not_conflict(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "bot: {}\n") + _write_role_users( + roles_dir, + "web-app-b", + "bot:\n password:\n algorithm: strong_password\n", + ) + + self.assertEqual( + "strong_password", + required_user_policies(roles_dir, ["web-app-a", "web-app-b"])["bot"][ + "algorithm" + ], + ) + def test_the_generated_value_satisfies_the_declared_regex(self): password = generate_declared_user_password( "bot", "strong_password", "[^A-Za-z0-9]" @@ -530,5 +632,56 @@ class TestDeclaredPasswordPolicy(unittest.TestCase): self.assertRegex(password, r"[-_.]") +def _role_plugin(role: str, name: str): + path = ROLES_DIR / role / "lookup_plugins" / f"{name}.py" + spec = importlib.util.spec_from_file_location(f"_users_generator_{name}", path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestRepositoryCatalogue(unittest.TestCase): + """The roles of the local Stalwart stack whose bots re-rendered per deploy.""" + + STALWART_STACK: ClassVar[list[str]] = [ + "svc-bkp-secrets-2-local", + "svc-bkp-volume-2-local", + "svc-net-tor-smtp", + "web-app-stalwart", + ] + + def test_every_user_a_provider_creates_on_the_fallback_is_pinned(self): + stalwart = _role_plugin("web-app-stalwart", "stalwart_users") + mailu = _role_plugin("web-app-mailu", "mailu_users") + catalogue = get_user_defaults(roles_dir=ROLES_DIR) + directory = non_reserved_users(catalogue) + required = required_user_policies(ROLES_DIR, self.STALWART_STACK) + + for username, user in catalogue.items(): + created = ( + stalwart.provisioned_by_stalwart(user) + or mailu.provisioned_by_mailu(user) + or username in directory + ) + if created and "strong_password" in str(user["password"]): + with self.subTest(username=username): + self.assertIn(username, required) + + def test_the_bots_stalwart_provisions_are_pinned(self): + required = required_user_policies(ROLES_DIR, self.STALWART_STACK) + + for username in ( + "blackhole", + "bounce", + "contact", + "helpdesk", + "newsletter", + "no-reply", + ): + with self.subTest(username=username): + self.assertIn(username, required) + + if __name__ == "__main__": unittest.main()