diff --git a/roles/user/README.md b/roles/user/README.md index 65724314a9..51b8a2a7d9 100644 --- a/roles/user/README.md +++ b/roles/user/README.md @@ -13,6 +13,16 @@ This role executes common tasks for user environment configuration. - **Automated provisioning:** Configured by Ansible without manual steps. +## Reserved usernames 🔒 + +`meta/users.yml` lists the usernames that MUST NOT be registered in the identity +directory. An entry is marked reserved by carrying `accounts: []`; consumers read +the set through the `reserved_usernames` filter. + +One further reservation per label of `DOMAIN_PRIMARY` is generated at runtime and +keyed `domain_label_`. A deployment on `label-a.tld.test` therefore reserves +`label-a`, `tld` and `test`, at any domain depth. + ## User data resolution User data is resolved via `lookup('users', user_key)` and referenced via `user_key`. diff --git a/roles/user/meta/users.yml b/roles/user/meta/users.yml index aef00cb57f..2c260f89b6 100644 --- a/roles/user/meta/users.yml +++ b/roles/user/meta/users.yml @@ -1,12 +1,4 @@ --- -sld: - description: Auto Generated Account to reserve the SLD - username: "{{ DOMAIN_PRIMARY.split('.')[0] }}" - accounts: [] -tld: - description: Auto Generated Account to reserve the TLD - username: "{{ DOMAIN_PRIMARY.split('.')[1] if (DOMAIN_PRIMARY is defined and (DOMAIN_PRIMARY.split('.') | length) > 1) else (DOMAIN_PRIMARY ~ '_tld ') }}" - accounts: [] root: username: root uid: 0 diff --git a/roles/user/vars/main.yml b/roles/user/vars/main.yml index 443c5b6a00..975c39a7cb 100644 --- a/roles/user/vars/main.yml +++ b/roles/user/vars/main.yml @@ -1,12 +1,5 @@ --- -# Effective user config for this role invocation. user_config_effective: "{{ user_config | default(lookup('users', user_key, {})) }}" - -# Actual system username (can differ from key) user_username: "{{ user_config_effective.username | default(user_key) }}" - -# Primary group (convention: same as username) user_group: "{{ user_username }}" - -# Home directory (root special case) user_home: "{{ (user_username == 'root') | ternary('/root', '/home/' ~ user_username) }}" diff --git a/tests/unit/python/plugins/lookup/test_users.py b/tests/unit/python/plugins/lookup/test_users.py index 19f83592c5..4744f8a465 100644 --- a/tests/unit/python/plugins/lookup/test_users.py +++ b/tests/unit/python/plugins/lookup/test_users.py @@ -141,7 +141,7 @@ class TestUsersLookup(unittest.TestCase): ) result = self.lookup.run( - ["sld"], + ["domain_label_0"], variables={"SYSTEM_EMAIL_DOMAIN": "mail.example.org"}, roles_dir=str(self._tmp / "roles"), )[0] @@ -165,14 +165,14 @@ class TestUsersLookup(unittest.TestCase): self.lookup._templar = None result = self.lookup.run( - ["sld"], + ["domain_label_0"], variables={"DOMAIN_PRIMARY": "portal.example.org"}, roles_dir=str(self._tmp / "roles"), )[0] self.assertEqual(result["username"], "portal") - def test_materializes_sld_from_role_domain_when_global_domain_is_missing( + def test_role_domain_no_longer_stands_in_for_the_primary_domain( self, ) -> None: _write_users( @@ -188,15 +188,14 @@ class TestUsersLookup(unittest.TestCase): _reset_cache_for_tests() self.lookup._templar = None - result = self.lookup.run( - ["sld"], - variables={"domain": "auth.infinito.test"}, - roles_dir=str(self._tmp / "roles"), - )[0] + with self.assertRaises(AnsibleError): + self.lookup.run( + ["domain_label_0"], + variables={"domain": "auth.infinito.test"}, + roles_dir=str(self._tmp / "roles"), + ) - self.assertEqual(result["username"], "infinito") - - def test_materializes_sld_from_env_backed_domain_primary(self) -> None: + def test_reserves_domain_labels_from_env_backed_domain_primary(self) -> None: _write_users( self._tmp, "templated", @@ -212,7 +211,7 @@ class TestUsersLookup(unittest.TestCase): with patch.dict(os.environ, {"DOMAIN": "infinito.localhost"}, clear=False): result = self.lookup.run( - ["sld"], + ["domain_label_0"], variables={ "DOMAIN_PRIMARY": "{{ lookup('env', 'DOMAIN') | default('infinito.localhost', true) }}" }, diff --git a/tests/unit/python/utils/cache/test_data.py b/tests/unit/python/utils/cache/test_data.py index c8ce41ad14..463b4aa8ac 100644 --- a/tests/unit/python/utils/cache/test_data.py +++ b/tests/unit/python/utils/cache/test_data.py @@ -19,7 +19,7 @@ from utils.cache.users import ( _compute_reserved_usernames, _hydrate_users_tokens, _load_user_defs, - _materialize_builtin_user_aliases, + _materialize_domain_label_reservations, _merge_users, get_user_defaults, ) @@ -297,25 +297,32 @@ class TestHydrateUsersTokens(unittest.TestCase): class TestMaterializeBuiltinUserAliases(unittest.TestCase): - def test_rewrites_sld_and_tld_usernames(self): - users = { - "sld": {"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}"}, - "tld": {"username": "{{ DOMAIN_PRIMARY.split('.')[1] }}"}, - } - result = _materialize_builtin_user_aliases( - users, {"DOMAIN_PRIMARY": "example.com"} + def test_reserves_one_username_per_domain_label(self): + result = _materialize_domain_label_reservations( + {}, {"DOMAIN_PRIMARY": "example.com"} + ) + self.assertEqual( + [result[key]["username"] for key in sorted(result)], + ["example", "com"], + ) + + def test_reserves_every_label_of_a_deep_primary_domain(self): + result = _materialize_domain_label_reservations( + {}, {"DOMAIN_PRIMARY": "label-a.tld.test"} + ) + self.assertEqual( + [result[key]["username"] for key in sorted(result)], + ["label-a", "tld", "test"], ) - self.assertEqual(result["sld"]["username"], "example") - self.assertEqual(result["tld"]["username"], "com") def test_no_domain_primary_is_passthrough(self): - users = {"sld": {"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}"}} - result = _materialize_builtin_user_aliases(users, {}) + users = {"alice": {"username": "alice"}} + result = _materialize_domain_label_reservations(users, {}) self.assertEqual(result, users) def test_non_placeholder_username_untouched(self): users = {"sld": {"username": "literal"}} - result = _materialize_builtin_user_aliases( + result = _materialize_domain_label_reservations( users, {"DOMAIN_PRIMARY": "example.com"} ) self.assertEqual(result["sld"]["username"], "literal") diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index 3506e3eb25..425d1349f5 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -4,7 +4,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`, `_resolve_tokens_file`, `_hydrate_users_tokens`, `_merge_users`, -`_materialize_builtin_user_aliases`. Module name is `test_users_module` +`_materialize_domain_label_reservations`. Module name is `test_users_module` to disambiguate from the existing `tests/unit/python/plugins/lookup/test_users.py` which targets the lookup plugin. """ @@ -306,21 +306,22 @@ class TestLoadStoreUsers(unittest.TestCase): class TestMaterializeBuiltinUserAliases(unittest.TestCase): def test_no_primary_domain_returns_users_unchanged(self): users = {"alice": {"username": "alice"}} - out = cache_users._materialize_builtin_user_aliases( + out = cache_users._materialize_domain_label_reservations( users, variables={}, templar=None ) self.assertEqual(out, users) - def test_sld_alias_username_resolved_from_domain_primary(self): - users = { - "sld": {"username": "{{ DOMAIN_PRIMARY.split('.') | first }}"}, - } - out = cache_users._materialize_builtin_user_aliases( - users, - variables={"DOMAIN_PRIMARY": "infinito.test"}, + def test_every_domain_label_becomes_a_reserved_username(self): + out = cache_users._materialize_domain_label_reservations( + {}, + variables={"DOMAIN_PRIMARY": "main.infinito.test"}, templar=None, ) - self.assertEqual(out["sld"]["username"], "infinito") + self.assertEqual( + [out[key]["username"] for key in sorted(out)], + ["main", "infinito", "test"], + ) + self.assertTrue(all(out[key]["accounts"] == [] for key in out)) class TestGetUserDefaults(unittest.TestCase): diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index dbc64697cb..2bf8e95f72 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -310,11 +310,22 @@ def _hydrate_users_tokens( return out -def _materialize_builtin_user_aliases( +def _materialize_domain_label_reservations( users: Mapping[str, Any] | None, variables: Mapping[str, Any] | None, templar: Any = None, ) -> dict[str, Any]: + """Reserve one username per label of the deployment's primary domain. + + Args: + users: the users resolved so far. + variables: play variables; ``DOMAIN_PRIMARY`` wins over + ``SYSTEM_EMAIL_DOMAIN``. + templar: optional templar used to render a templated candidate. + + Returns: + A copy of ``users`` with one ``domain_label_`` entry per label. + """ from utils.templating.ansible import _templar_render_best_effort def _normalize_domain_candidate(value: Any) -> str: @@ -330,49 +341,25 @@ def _materialize_builtin_user_aliases( text = parsed.hostname or text return text.split("/", 1)[0].split(":", 1)[0].strip() - def _to_primary_domain(value: Any) -> str: - text = _normalize_domain_candidate(value) - if not text: - return "" - labels = [label for label in text.split(".") if label] - if len(labels) >= 2: - return ".".join(labels[-2:]) - return text - out: dict[str, Any] = copy.deepcopy(dict(users or {})) variables = variables or {} primary_domain = "" - for candidate_key, extractor in ( - ("DOMAIN_PRIMARY", _normalize_domain_candidate), - ("SYSTEM_EMAIL_DOMAIN", _normalize_domain_candidate), - ("KEYCLOAK_DOMAIN", _to_primary_domain), - ("domain", _to_primary_domain), - ): - primary_domain = extractor(variables.get(candidate_key)) + for candidate_key in ("DOMAIN_PRIMARY", "SYSTEM_EMAIL_DOMAIN"): + primary_domain = _normalize_domain_candidate(variables.get(candidate_key)) if primary_domain: break - if not primary_domain: - return out - labels = [label for label in primary_domain.split(".") if label] - alias_values = { - "sld": labels[0] if labels else primary_domain, - "tld": (labels[1] if len(labels) > 1 else (primary_domain + "_tld ")), - } - - for alias_key, alias_value in alias_values.items(): - raw_user = out.get(alias_key) - if not isinstance(raw_user, Mapping): - continue - - raw_username = str(raw_user.get("username", "")) - if "DOMAIN_PRIMARY.split" not in raw_username: - continue - - updated_user = copy.deepcopy(dict(raw_user)) - updated_user["username"] = alias_value - out[alias_key] = updated_user + for index, label in enumerate( + label for label in primary_domain.split(".") if label + ): + out[f"domain_label_{index}"] = { + "description": ( + f"Auto generated account reserving the domain label '{label}'" + ), + "username": label, + "accounts": [], + } return out @@ -441,7 +428,7 @@ def get_merged_users( _RENDER_GUARD.users = True try: - materialized = _materialize_builtin_user_aliases( + materialized = _materialize_domain_label_reservations( hydrated, variables, templar=templar,