diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 1df151b7c9..04ca54e35e 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -33,12 +33,12 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or a changed path or content of the tokens file). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or changed tokens in the store the users are hydrated from). - The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. - The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every persisted token in `roles/sys-token-store/tasks/write.yml`. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. -- The tokens file enters the key as the SHA-256 of its content, memoised per inode, mtime and size, so a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. +- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. - User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index b57393630b..b85b9639f6 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -13,9 +13,11 @@ instead of rendering:: ``tasks/stages/01_constructor.yml`` parks three of them: a block-scoped one for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when -``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and the -tokens file's path and content digest, so a carrier whose groups or tokens no -longer match is rejected and the reader renders afresh:: +``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and a +digest of the tokens the users are hydrated from (the tokens file, or the +``sys_token_store_users`` fact once the token store loaded; both key alike for +the same tokens), so a carrier whose groups or tokens no longer match is +rejected and the reader renders afresh:: - name: 🧊 Drop the merge-block carrier so later stages re-render applications_carrier: diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index fb9b1919fc..ba829a0a67 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -402,7 +402,53 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): "key": [key[0], list(key[1])], "applications": {"web-app-foo": {"carried": True}}, } - tokens.write_text("users: {}\n", encoding="utf-8") + tokens.write_text( + "users: {no-reply: {tokens: {web-app-stalwart: minted}}}\n", + encoding="utf-8", + ) + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertNotIn("carried", merged["web-app-foo"]) + + def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: + roles = _seed_minimal_roles(tmp) + tokens = tmp / "tokens.yml" + tokens.write_text( + f"users: {{no-reply: {{tokens: {{web-app-stalwart: {token}}}}}}}\n", + encoding="utf-8", + ) + variables = self._variables() + variables["FILE_TOKENS"] = str(tokens) + key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} + variables[APPLICATIONS_RENDERED_FACT] = { + "key": [key[0], list(key[1])], + "applications": carried, + } + return roles, variables, carried + + def test_the_store_fact_with_the_file_tokens_keeps_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + variables["sys_token_store_users"] = { + "no-reply": {"tokens": {"web-app-stalwart": "minted"}} + } + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertIs(merged, carried) + + def test_the_store_fact_with_other_tokens_than_the_file_rejects_the_carrier( + self, + ): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, _ = self._park_from_the_tokens_file(Path(tmp), "minted") + variables["sys_token_store_users"] = { + "no-reply": {"tokens": {"web-app-stalwart": "rotated"}} + } merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index 1e0753d985..0dc951ed81 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -20,6 +20,7 @@ from pathlib import Path from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base from utils.cache import users as cache_users +from utils.cache.users import store as cache_users_store from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS @@ -414,5 +415,89 @@ class TestGetMergedUsersTokenSource(unittest.TestCase): self.assertEqual(after["foo"]["tokens"]["web-app-foo"], "minted") +class TestStoreSignature(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _signature(store: dict) -> tuple: + with tempfile.TemporaryDirectory() as tmp: + return cache_users._store_signature( + {cache_users_store.STORE_FACT: store}, Path(tmp) / "tokens.yml" + ) + + @staticmethod + def _hydrated(store: dict) -> str: + users = {"foo": {"tokens": {"web-app-foo": ""}}} + return repr(cache_users._hydrate_users_tokens(users, store)) + + def test_the_tokens_file_signs_like_the_store_fact_with_the_same_tokens(self): + store = {"foo": {"tokens": {"web-app-foo": "minted"}}} + with tempfile.TemporaryDirectory() as tmp: + tokens_file = Path(tmp) / "tokens.yml" + tokens_file.write_text(dump_yaml_str({"users": store}), encoding="utf-8") + self.assertEqual( + cache_users._store_signature({}, tokens_file), + cache_users._store_signature( + {cache_users_store.STORE_FACT: store}, tokens_file + ), + ) + + def test_a_missing_tokens_file_signs_like_an_empty_store_fact(self): + with tempfile.TemporaryDirectory() as tmp: + absent = Path(tmp) / "tokens.yml" + self.assertEqual( + cache_users._store_signature({}, absent), + cache_users._store_signature( + {cache_users_store.STORE_FACT: {}}, absent + ), + ) + + def test_fields_and_padding_the_hydration_ignores_keep_the_signature(self): + plain = {"foo": {"tokens": {"web-app-foo": "minted"}}} + for variant in ( + {"foo": {"tokens": {"web-app-foo": " minted "}}}, + {"foo": {"tokens": {"web-app-foo": "minted"}, "note": "unread"}}, + {"foo": {"tokens": {"web-app-foo": "minted", "web-app-bar": None}}}, + {"foo": {"tokens": {"web-app-foo": "minted"}}, "bar": "not-a-mapping"}, + ): + with self.subTest(variant=variant): + self.assertEqual(self._hydrated(variant), self._hydrated(plain)) + self.assertEqual(self._signature(variant), self._signature(plain)) + + def test_the_store_order_enters_the_signature_because_the_hydration_keeps_it( + self, + ): + first = {"bar": {"tokens": {"x": "1"}}, "baz": {"tokens": {"y": "2"}}} + swapped = {"baz": {"tokens": {"y": "2"}}, "bar": {"tokens": {"x": "1"}}} + self.assertNotEqual(self._hydrated(first), self._hydrated(swapped)) + self.assertNotEqual(self._signature(first), self._signature(swapped)) + + def test_an_equal_signature_means_an_equal_hydration(self): + stores = [ + {"foo": {"tokens": {"web-app-foo": "minted"}}}, + {"foo": {"tokens": {"web-app-foo": " minted "}}}, + {"foo": {"tokens": {"web-app-foo": "rotated"}}}, + {"foo": {"tokens": {"web-app-foo": None}}}, + {"foo": {"tokens": {"web-app-foo": ""}}}, + {"foo": {"tokens": {}}}, + {"foo": {"tokens": "not-a-mapping"}}, + {"foo": {}}, + {"foo": "not-a-mapping"}, + {}, + {"bar": {"tokens": {"x": "1"}}}, + {"bar": {"tokens": {"x": 1}}}, + {"bar": {"tokens": {}}}, + {1: {"tokens": {"x": "1"}}}, + {"1": {"tokens": {"x": "1"}}}, + ] + for first in stores: + for second in stores: + if self._signature(first) != self._signature(second): + continue + with self.subTest(first=first, second=second): + self.assertEqual(self._hydrated(first), self._hydrated(second)) + + if __name__ == "__main__": unittest.main() diff --git a/utils/cache/README.md b/utils/cache/README.md index 6217997ab3..3be16f4ee2 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -11,7 +11,7 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` → `plan_dev_inventory_matrix` → `get_variants`) keeps working without ansible installed. | | [carrier.py](carrier.py) | The play-scoped carrier of the rendered applications payload: the fact name `_INFINITO_APPLICATIONS_RENDERED`, `merged_applications_cache_key`, and the reader `get_merged_applications` consults before it renders. | -| [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass). | +| [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users and carrier keys share). | | [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | | [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index d6d66dd4b7..a7a1a59527 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -22,13 +22,12 @@ from utils.cache.base import ( _RENDER_GUARD, _cache_key, _deep_merge, - _fingerprint_mapping, _render_with_templar, _resolve_override_mapping, _resolve_roles_dir, _stable_variables_signature, - _tokens_file_signature, ) +from utils.cache.users import store as _store from utils.cache.users.placeholders import ( substitute_primary_domain_placeholder as _substitute_primary_domain_placeholder, ) @@ -222,34 +221,20 @@ def _load_store_users(file_tokens: str | os.PathLike[str] | None) -> dict[str, A return users if isinstance(users, dict) else {} -STORE_FACT = "sys_token_store_users" - - -def _store_snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: - """Return the token store the play read from the stack host. - - Args: - variables: the play's variable scope. - - Returns: - The ``sys_token_store_users`` fact, or None outside a play that loaded - ``sys-token-store``. - """ - snapshot = (variables or {}).get(STORE_FACT) - return snapshot if isinstance(snapshot, Mapping) else None - - def _store_signature(variables: Mapping[str, Any] | None, tokens_file: Path) -> tuple: """Return the cache-key part of the store the users are hydrated from. Args: variables: the play's variable scope. tokens_file: the controller's tokens file, used when no snapshot exists. + + Returns: + ``(STORE_FACT, digest)``, equal for the tokens file and the + ``sys_token_store_users`` fact when both hold the same tokens. """ - snapshot = _store_snapshot(variables) - if snapshot is not None: - return (STORE_FACT, _fingerprint_mapping(snapshot)) - return _tokens_file_signature(tokens_file) + snapshot = _store.snapshot(variables) + store = snapshot if snapshot is not None else _load_store_users(tokens_file) + return (_store.STORE_FACT, _store.tokens_digest(store)) def _resolve_tokens_file(variables: Mapping[str, Any] | None) -> Path: @@ -446,7 +431,7 @@ def get_merged_users( resolved_roles_dir = _resolve_roles_dir(roles_dir=roles_dir) tokens_file = _resolve_tokens_file(variables) - snapshot = _store_snapshot(variables) + snapshot = _store.snapshot(variables) cache_key = ( _cache_key(resolved_roles_dir), _stable_variables_signature(source_variables), @@ -498,3 +483,4 @@ def get_merged_users( def _reset() -> None: _USERS_DEFAULTS_CACHE.clear() _MERGED_USERS_CACHE.clear() + _store._reset() diff --git a/utils/cache/users/store.py b/utils/cache/users/store.py new file mode 100644 index 0000000000..b779c0f698 --- /dev/null +++ b/utils/cache/users/store.py @@ -0,0 +1,68 @@ +"""The token store the users are hydrated from: the play fact and its digest.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from typing import Any + +STORE_FACT = "sys_token_store_users" + +_DIGESTS: dict[str, str] = {} + + +def snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: + """Return the token store the play read from the stack host. + + Args: + variables: the play's variable scope. + + Returns: + The ``sys_token_store_users`` fact, or None outside a play that loaded + ``sys-token-store``. + """ + value = (variables or {}).get(STORE_FACT) + return value if isinstance(value, Mapping) else None + + +def _tagged(value: Any) -> list: + return [True, str(value)] if isinstance(value, str) else [False, repr(value)] + + +def tokens_digest(store_users: Mapping[str, Any]) -> str: + """Digest exactly the part of a store that `_hydrate_users_tokens` reads. + + Args: + store_users: the store's ``users`` mapping. + + Returns: + The SHA-256 of every user entry with a tokens mapping, in store order, + and its non-empty stripped tokens, memoised per store content. + """ + memo_key = hashlib.md5( + repr(list(store_users.items())).encode("utf-8"), usedforsecurity=False + ).hexdigest() + digest = _DIGESTS.get(memo_key) + if digest is not None: + return digest + entries: list = [] + for user_key, user_data in store_users.items(): + if not isinstance(user_data, Mapping): + continue + tokens = user_data.get("tokens", {}) + if not isinstance(tokens, Mapping): + continue + kept = [] + for app_id, token in tokens.items(): + text = "" if token is None else str(token).strip() + if text: + kept.append([_tagged(app_id), text]) + entries.append([_tagged(user_key), kept]) + digest = hashlib.sha256(json.dumps(entries).encode("utf-8")).hexdigest() + _DIGESTS[memo_key] = digest + return digest + + +def _reset() -> None: + _DIGESTS.clear()