From 3f823f4ebea684014420c8cd5268117441427f49 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:05:53 +0200 Subject: [PATCH 01/16] Share secret masking between API and conductor Extract secret detection and masking logic into a shared module osism/utils/secrets.py to eliminate duplication between osism/api.py and osism/tasks/conductor/utils.py. The module provides: - is_secret_key(key) -> bool: detects secret keys by name pattern - is_vault_value(value) -> bool: detects vault-encrypted values - mask_structure(data, mask="***") -> dict: recursively masks by key name and vault value - replace_literals(text, secret_values, mask="***", min_length=0): replaces known secret values in text - replace_literals_deep(obj, secret_values, mask="***", min_length=0): deep copy of obj with literal replacement The conductor's mask_secrets and _mask_secrets_inplace functions keep their original behavior and output; _is_secret_key is re-exported from the shared module to maintain compatibility with existing tests (mask="xxx" default). The API's masking functions are simplified to call mask_structure, preserving their "***" mask and recursive behavior at every nesting depth. All 219 existing tests pass unchanged. Assisted-by: Claude:claude-haiku-4-5-20251001 Signed-off-by: Roger Luethi --- osism/api.py | 28 ++--------- osism/tasks/conductor/utils.py | 8 +-- osism/utils/secrets.py | 85 ++++++++++++++++++++++++++++++++ tests/unit/utils/test_secrets.py | 75 ++++++++++++++++++++++++++++ 4 files changed, 164 insertions(+), 32 deletions(-) create mode 100644 osism/utils/secrets.py create mode 100644 tests/unit/utils/test_secrets.py diff --git a/osism/api.py b/osism/api.py index bf529c69e..b6482eabb 100644 --- a/osism/api.py +++ b/osism/api.py @@ -31,34 +31,12 @@ from osism.services.listener import BaremetalEvents from osism.services.websocket_manager import websocket_manager from osism.services.event_bridge import event_bridge -from osism.tasks.conductor.utils import _is_secret_key +from osism.utils.secrets import mask_structure def _mask_inventory_secrets(data: dict) -> dict: - """Mask secret values in inventory data before returning via API. - - Masks values for keys matching secret patterns (password, secret, - ironic_osism_*) and values that are Ansible Vault encrypted, at any - nesting depth inside dicts and lists. - """ - masked: dict = {} - for key, value in data.items(): - if _is_secret_key(key): - masked[key] = "***" - else: - masked[key] = _mask_inventory_value(value) - return masked - - -def _mask_inventory_value(value): - """Mask secrets in a single inventory value, recursing into containers.""" - if isinstance(value, str) and value.strip().startswith("$ANSIBLE_VAULT;"): - return "***" - if isinstance(value, dict): - return _mask_inventory_secrets(value) - if isinstance(value, list): - return [_mask_inventory_value(item) for item in value] - return value + """Mask secret values in inventory data before returning via API.""" + return mask_structure(data, mask="***") class NotificationBaremetal(BaseModel): diff --git a/osism/tasks/conductor/utils.py b/osism/tasks/conductor/utils.py index 25908397a..9641d446d 100644 --- a/osism/tasks/conductor/utils.py +++ b/osism/tasks/conductor/utils.py @@ -8,6 +8,7 @@ from loguru import logger from osism import utils +from osism.utils.secrets import is_secret_key as _is_secret_key # noqa: F401 import sushy import urllib3 import yaml @@ -294,13 +295,6 @@ def check_task_lock_and_exit(): return utils.check_task_lock_and_exit() -def _is_secret_key(key): - if not isinstance(key, str): - return False - lower = key.lower() - return "password" in lower or "secret" in lower or lower.startswith("ironic_osism_") - - def mask_secrets(obj, mask="xxx", secret_values=None): """Return a deep copy of obj with secret values masked. diff --git a/osism/utils/secrets.py b/osism/utils/secrets.py new file mode 100644 index 000000000..6728cd4d7 --- /dev/null +++ b/osism/utils/secrets.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Secret detection and masking shared by the CLI, the API and the conductor. + +The key rule and structural masking moved here from +``osism.tasks.conductor.utils`` and ``osism.api``. Their callers keep +their output. ``replace_literals`` is the literal half of masking: it +replaces known secret values inside arbitrary text. +""" + +import copy +from typing import Any, Iterable + +VAULT_PREFIX = "$ANSIBLE_VAULT;" + + +def is_secret_key(key: Any) -> bool: + if not isinstance(key, str): + return False + lower = key.lower() + return "password" in lower or "secret" in lower or lower.startswith("ironic_osism_") + + +def is_vault_value(value: Any) -> bool: + """True for a vault-encrypted value as Ansible tools present it. + + A vaulted file's value is a string with the vault header. An inline + ``!vault`` value comes out of ``ansible-inventory`` as + ``{"__ansible_vault": ""}``. + """ + if isinstance(value, str): + return value.strip().startswith(VAULT_PREFIX) + if isinstance(value, dict) and set(value) == {"__ansible_vault"}: + return True + return False + + +def mask_structure(data: dict, mask: str = "***") -> dict: + """Mask by key name and by vault value, recursively. The API's rule.""" + masked: dict = {} + for key, value in data.items(): + masked[key] = mask if is_secret_key(key) else _mask_value(value, mask) + return masked + + +def _mask_value(value: Any, mask: str) -> Any: + if is_vault_value(value): + return mask + if isinstance(value, dict): + return mask_structure(value, mask) + if isinstance(value, list): + return [_mask_value(item, mask) for item in value] + return value + + +def replace_literals( + text: str, secret_values: Iterable[str], mask: str = "***", min_length: int = 0 +) -> str: + """Replace every occurrence of each secret value, longest first.""" + values = sorted( + {v for v in secret_values if isinstance(v, str) and v and len(v) >= min_length}, + key=len, + reverse=True, + ) + for value in values: + text = text.replace(value, mask) + return text + + +def replace_literals_deep( + obj: Any, secret_values: Iterable[str], mask: str = "***", min_length: int = 0 +) -> Any: + values = list(secret_values) + result = copy.deepcopy(obj) + + def walk(node: Any) -> Any: + if isinstance(node, str): + return replace_literals(node, values, mask, min_length) + if isinstance(node, dict): + return {k: walk(v) for k, v in node.items()} + if isinstance(node, list): + return [walk(v) for v in node] + return node + + return walk(result) diff --git a/tests/unit/utils/test_secrets.py b/tests/unit/utils/test_secrets.py new file mode 100644 index 000000000..87f2e8ca0 --- /dev/null +++ b/tests/unit/utils/test_secrets.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from osism.utils.secrets import ( + is_secret_key, + is_vault_value, + mask_structure, + replace_literals, + replace_literals_deep, +) + + +@pytest.mark.parametrize( + "key", ["password", "DB_PASSWORD", "my_secret", "ironic_osism_x"] +) +def test_is_secret_key_matches(key): + assert is_secret_key(key) is True + + +@pytest.mark.parametrize("key", ["host", "osism_ironic", None, 3]) +def test_is_secret_key_does_not_match(key): + assert is_secret_key(key) is False + + +def test_is_vault_value_string_prefix(): + assert is_vault_value("$ANSIBLE_VAULT;1.1;AES256\n6162") is True + assert is_vault_value(" $ANSIBLE_VAULT;1.1") is True + + +def test_is_vault_value_inline_vault_dict(): + # ansible-inventory renders an inline !vault value as this dict + # (observed with ansible-core 2.19.11, 2026-10-07). + assert is_vault_value({"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n63"}) is True + + +def test_is_vault_value_plain(): + assert is_vault_value("plain") is False + assert is_vault_value({"a": 1}) is False + + +def test_mask_structure_matches_api_behaviour(): + data = { + "db_password": "x", + "nested": {"secret_key": "y", "ok": "$ANSIBLE_VAULT;1.1"}, + "lst": ["$ANSIBLE_VAULT;1.1", "keep"], + "plain": "z", + } + assert mask_structure(data) == { + "db_password": "***", + "nested": {"secret_key": "***", "ok": "***"}, + "lst": ["***", "keep"], + "plain": "z", + } + + +def test_replace_literals_threshold(): + assert replace_literals("a-abcdef-b", ["abcdef"], min_length=6) == "a-***-b" + assert replace_literals("a-abcde-b", ["abcde"], min_length=6) == "a-abcde-b" + + +def test_replace_literals_overmasks_substrings_by_design(): + # Review focus 3: an unrelated value containing a secret is masked too. + assert replace_literals("xabcdefx", ["abcdef"], min_length=6) == "x***x" + + +def test_replace_literals_longest_first(): + assert replace_literals("abcdefgh", ["abcdef", "abcdefgh"]) == "***" + + +def test_replace_literals_deep_copies(): + obj = {"a": ["xx-secret1-yy", 3]} + out = replace_literals_deep(obj, ["secret1"]) + assert out == {"a": ["xx-***-yy", 3]} + assert obj == {"a": ["xx-secret1-yy", 3]} From 2109497ad40ae8d7b9325c4718ebb497dd8ced85 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:09:57 +0200 Subject: [PATCH 02/16] Extract variable references from templates Add a pure module that finds which variables a raw Ansible/Jinja value refers to, without rendering it. It parses the value with jinja2.Environment().parse() and walks the syntax tree itself. jinja2.meta.find_undeclared_variables does not fit: it raises on unknown filters and does not report subscript targets. - Refs records static references (names), cross-host references (hostvars), dynamic keys, and whether the value is unanalysable. - DynamicKey holds the expression of a subscript key that is not a constant, with a cross_host flag. - references() recurses into dicts, lists and template strings. - Names bound in the template ({% set %} targets and for loop variables) are tracked per scope in statement order, so earlier references are not hidden by later bindings. - vars['X'], vars.X, hostvars[H]['X'], hostvars[H].X and hostvars.H.X are handled, and same-host references are told apart from cross-host ones. - lookup/query/q() calls of the vars lookup are analysed for their targets. - Unknown filters do not break the analysis. Unmodelled scopes (Macro, CallBlock, With, FilterBlock) and a TemplateSyntaxError make the value unanalysable. Assisted-by: Claude:claude-haiku-4-5-20251001 Signed-off-by: Roger Luethi --- osism/utils/template_deps.py | 227 +++++++++++++++++++++++++ tests/unit/utils/test_template_deps.py | 118 +++++++++++++ 2 files changed, 345 insertions(+) create mode 100644 osism/utils/template_deps.py create mode 100644 tests/unit/utils/test_template_deps.py diff --git a/osism/utils/template_deps.py b/osism/utils/template_deps.py new file mode 100644 index 000000000..d77a586cc --- /dev/null +++ b/osism/utils/template_deps.py @@ -0,0 +1,227 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Which variables a raw Ansible value refers to, found without rendering it. + +Uses ``jinja2.Environment().parse()`` and walks the tree. Do not use +``jinja2.meta.find_undeclared_variables``: it runs the code generator, +which raises on any filter the Environment does not know (every Ansible +filter), and it reports ``vars``/``hostvars`` instead of the subscript +target. + +Names bound inside the template (loop targets, ``{% set %}``) are tracked +per scope and in statement order. A later binding never hides an earlier +reference. +""" + +from dataclasses import dataclass, field +from typing import Any + +from jinja2 import Environment, nodes +from jinja2.exceptions import TemplateSyntaxError + +_ENV = Environment() +_GLOBALS = frozenset( + { + "vars", + "hostvars", + "groups", + "group_names", + "inventory_hostname", + "omit", + "lookup", + "query", + "q", + "range", + "dict", + "lipsum", + "cycler", + "joiner", + "namespace", + "true", + "false", + "none", + "True", + "False", + "None", + } +) +_LOOKUPS = frozenset({"lookup", "query", "q"}) +# Statements whose scoping this walker does not model; their presence makes +# the value unanalysable (masked), which is the safe direction. +_UNMODELLED = (nodes.Macro, nodes.CallBlock, nodes.With, nodes.FilterBlock) + + +@dataclass(frozen=True) +class DynamicKey: + expression: str | None + cross_host: bool + + +@dataclass(frozen=True) +class Refs: + names: frozenset = field(default_factory=frozenset) + cross_host_names: frozenset = field(default_factory=frozenset) + dynamic_keys: tuple = () + unanalysable: bool = False + + +class _Acc: + def __init__(self) -> None: + self.names: set = set() + self.cross: set = set() + self.dynamic: list = [] + self.unanalysable = False + + +def references(raw: Any) -> Refs: + acc = _Acc() + _collect(raw, acc) + return Refs( + names=frozenset(acc.names), + cross_host_names=frozenset(acc.cross), + dynamic_keys=tuple(acc.dynamic), + unanalysable=acc.unanalysable, + ) + + +def _collect(raw: Any, acc: _Acc) -> None: + if isinstance(raw, dict): + for value in raw.values(): + _collect(value, acc) + elif isinstance(raw, list): + for value in raw: + _collect(value, acc) + elif isinstance(raw, str) and ("{{" in raw or "{%" in raw): + try: + tree = _ENV.parse(raw) + except TemplateSyntaxError: + acc.unanalysable = True + return + _walk_body(tree.body, acc, frozenset()) + + +def _target_names(target: nodes.Node) -> set: + found = {n.name for n in target.find_all(nodes.Name)} + if isinstance(target, nodes.Name): + found.add(target.name) + return found + + +def _walk_body(body: list, acc: _Acc, bound: frozenset) -> None: + """Statements in order: a {% set %} binds only for what follows it.""" + current = set(bound) + for stmt in body: + if isinstance(stmt, nodes.Assign): + _walk(stmt.node, acc, frozenset(current)) + current |= _target_names(stmt.target) + elif isinstance(stmt, nodes.AssignBlock): + _walk_body(stmt.body, acc, frozenset(current)) + current |= _target_names(stmt.target) + else: + _walk(stmt, acc, frozenset(current)) + + +def _hostvars_host(base: nodes.Node): + """For hostvars[H] / hostvars.H return (True, cross_host); else (False, None).""" + if isinstance(base, nodes.Getitem) and _is_name(base.node, "hostvars"): + return True, not _is_name(base.arg, "inventory_hostname") + if isinstance(base, nodes.Getattr) and _is_name(base.node, "hostvars"): + return True, True + return False, None + + +def _is_name(node: nodes.Node, name: str) -> bool: + return isinstance(node, nodes.Name) and node.name == name + + +def _walk(node: nodes.Node, acc: _Acc, bound: frozenset) -> None: + if isinstance(node, _UNMODELLED): + acc.unanalysable = True + return + if isinstance(node, nodes.For): + _walk(node.iter, acc, bound) + inner = bound | _target_names(node.target) | {"loop"} + if node.test is not None: + _walk(node.test, acc, inner) + _walk_body(node.body, acc, inner) + _walk_body(node.else_, acc, bound) + return + if isinstance(node, nodes.If): + _walk(node.test, acc, bound) + _walk_body(node.body, acc, bound) + for elif_ in node.elif_: + _walk(elif_, acc, bound) + _walk_body(node.else_, acc, bound) + return + if isinstance(node, (nodes.Getitem, nodes.Getattr)): + base = node.node + is_hostvars, cross = _hostvars_host(base) + if _is_name(base, "vars") or is_hostvars: + if is_hostvars and isinstance(base, nodes.Getitem): + _walk(base.arg, acc, bound) + if isinstance(node, nodes.Getattr): + (acc.cross if cross else acc.names).add(node.attr) + else: + _target(node.arg, acc, bool(cross), bound) + return + if isinstance(node, nodes.Call) and isinstance(node.node, nodes.Name): + if node.node.name in _LOOKUPS and node.args and _const(node.args[0]) == "vars": + for arg in node.args[1:]: + _target(arg, acc, False, bound) + return + if isinstance(node, nodes.Name) and node.ctx == "load": + if node.name not in _GLOBALS and node.name not in bound: + acc.names.add(node.name) + return + for child in node.iter_child_nodes(): + _walk(child, acc, bound) + + +def _const(node: nodes.Node) -> Any: + return node.value if isinstance(node, nodes.Const) else None + + +def _target(key: nodes.Node, acc: _Acc, cross: bool, bound: frozenset) -> None: + value = _const(key) + if isinstance(value, str): + (acc.cross if cross else acc.names).add(value) + return + # A key that uses a template-bound name ({% set %}, a loop target) cannot + # be resolved as a standalone expression: it would read the host's + # variable of that name instead of the local binding. Unresolvable. + uses_bound = bool(_target_names(key) & bound) + expression = None if uses_bound else _unparse(key) + acc.dynamic.append(DynamicKey(expression=expression, cross_host=cross)) + _walk(key, acc, bound) + + +def _unparse(node: nodes.Node) -> str | None: + if isinstance(node, nodes.Const): + return repr(node.value) + if isinstance(node, nodes.Name): + return node.name + if isinstance(node, nodes.Getattr): + inner = _unparse(node.node) + return None if inner is None else f"{inner}.{node.attr}" + if isinstance(node, nodes.Getitem) and isinstance(node.arg, nodes.Const): + inner = _unparse(node.node) + return None if inner is None else f"{inner}[{node.arg.value!r}]" + if isinstance(node, nodes.Add): + left, right = _unparse(node.left), _unparse(node.right) + return None if left is None or right is None else f"{left} + {right}" + if isinstance(node, nodes.Concat): + parts = [_unparse(p) for p in node.nodes] + return ( + None + if any(p is None for p in parts) + else " ~ ".join(parts) # type: ignore[arg-type] + ) + if ( + isinstance(node, nodes.Filter) + and node.node is not None + and not node.args + and not node.kwargs + ): + inner = _unparse(node.node) + return None if inner is None else f"{inner} | {node.name}" + return None diff --git a/tests/unit/utils/test_template_deps.py b/tests/unit/utils/test_template_deps.py new file mode 100644 index 000000000..2e9665c3e --- /dev/null +++ b/tests/unit/utils/test_template_deps.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: Apache-2.0 + +from osism.utils.template_deps import references + + +def test_plain_names(): + r = references("{{ a }}-{{ b | default('x') }}") + assert r.names == {"a", "b"} and not r.unanalysable + + +def test_unknown_filters_do_not_break_analysis(): + r = references("{{ s | b64encode }} {{ 'api' | kolla_address(host) }}") + assert r.names == {"s", "host"} and not r.unanalysable + + +def test_constant_vars_subscript_yields_target(): + assert references("{{ vars['Y'] }}").names == {"Y"} + + +def test_constant_hostvars_subscript_same_host(): + r = references("{{ hostvars[inventory_hostname]['Y'] }}") + assert r.names == {"Y"} and r.cross_host_names == frozenset() + + +def test_constant_hostvars_subscript_other_host_is_cross_host(): + r = references("{{ hostvars[h]['Y'] }}") + assert "Y" in r.cross_host_names and "h" in r.names + + +def test_dynamic_key_is_unparsed(): + r = references( + "{{ hostvars[inventory_hostname]['ansible_' + management_interface]['ipv4'] }}" + ) + assert [k.expression for k in r.dynamic_keys] == [ + "'ansible_' + management_interface" + ] + assert "management_interface" in r.names + + +def test_dynamic_key_unparseable_expression_is_none(): + r = references("{{ vars[x.split('-') | first] }}") + assert r.dynamic_keys[0].expression is None + + +def test_lookup_vars_constant_and_dynamic(): + assert "Y" in references("{{ lookup('vars', 'Y') }}").names + assert references("{{ lookup('vars', n) }}").dynamic_keys + + +def test_loop_and_set_names_are_not_references(): + r = references( + "{% for host in groups['x'] %}{{ hostvars[host]['id'] }}{% endfor %}" + "{% set z = 1 %}{{ z }}" + ) + assert "host" not in r.names and "z" not in r.names + assert "id" in r.cross_host_names + + +def test_recurses_into_structures(): + # Review focus 2 + r = references({"a": ["{{ redis_master_password }}", 2], "b": "lit"}) + assert r.names == {"redis_master_password"} + + +def test_attribute_forms_are_references(): + assert references("{{ vars.db_password | b64encode }}").names == {"db_password"} + r = references("{{ hostvars[h].endpoint }}") + assert r.cross_host_names == {"endpoint"} and r.names == {"h"} + assert references("{{ hostvars.node2.endpoint }}").cross_host_names == {"endpoint"} + assert references("{{ hostvars[inventory_hostname].Y }}").names == {"Y"} + + +def test_later_binding_does_not_hide_earlier_reference(): + r = references( + "{{ db_password }}{% for db_password in [] %}{{ db_password }}{% endfor %}" + ) + assert r.names == {"db_password"} + + +def test_set_binds_only_after_itself(): + assert references("{{ z }}{% set z = 1 %}{{ z }}").names == {"z"} + assert references("{% set z = 1 %}{{ z }}").names == frozenset() + + +def test_if_branches_are_walked(): + r = references("{% if a %}{{ b }}{% elif c %}{{ d }}{% else %}{{ e }}{% endif %}") + assert r.names == {"a", "b", "c", "d", "e"} + + +def test_dynamic_key_using_bound_name_is_unresolvable(): + assert [ + k.expression + for k in references( + "{% set n = 'db_password' %}{{ vars[n] | b64encode }}" + ).dynamic_keys + ] == [None] + assert [ + k.expression + for k in references( + "{% for n in ['a'] %}{{ vars[n] }}{% endfor %}" + ).dynamic_keys + ] == [None] + assert [k.expression for k in references("{{ vars[n] }}").dynamic_keys] == ["n"] + + +def test_macro_is_unanalysable(): + assert ( + references("{% macro m() %}{{ x }}{% endmacro %}{{ m() }}").unanalysable is True + ) + + +def test_syntax_error_is_unanalysable(): + assert references("{{ a ").unanalysable is True + + +def test_non_template_string_has_no_refs(): + r = references("plain") + assert r.names == frozenset() and not r.dynamic_keys From ebfdc5a826630ba069601612e934ad27a7054488 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:13:17 +0200 Subject: [PATCH 03/16] Evaluate variables in one run per stack Effective values of an environment depend on the extra-vars files that `osism apply` passes, and dependency closures contain dynamic keys such as vars[n]. Resolving such a key can reach a variable that holds another dynamic key, so a closure cannot be computed up front without repeated Ansible runs. Add an evaluation core (osism.utils.evaluate) that walks a closure and resolves every dynamic key through a callback, and a renderer (osism.utils.render) that runs it inside a single controller-side Ansible invocation per host and stack. A small action plugin passes Ansible's templar as the callback, so chained key resolution, values and secret hits all come out of one run. The renderer also builds the stack of files for an environment in the order the standard run scripts use, and loads them vault-aware: whole file vaults are decrypted, inline !vault values keep their provenance as an encrypted marker. Errors name the file and line but never carry file content. ENVIRONMENTS_DIRECTORY sets the root of the environments. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Roger Luethi --- osism/settings.py | 5 + osism/utils/evaluate.py | 98 +++++++++ osism/utils/render.py | 247 ++++++++++++++++++++++ tests/integration/test_hostvars_render.py | 104 +++++++++ tests/unit/utils/test_evaluate.py | 107 ++++++++++ tests/unit/utils/test_render.py | 149 +++++++++++++ 6 files changed, 710 insertions(+) create mode 100644 osism/utils/evaluate.py create mode 100644 osism/utils/render.py create mode 100644 tests/integration/test_hostvars_render.py create mode 100644 tests/unit/utils/test_evaluate.py create mode 100644 tests/unit/utils/test_render.py diff --git a/osism/settings.py b/osism/settings.py index 774427744..0fc25af9d 100644 --- a/osism/settings.py +++ b/osism/settings.py @@ -30,6 +30,11 @@ def read_secret(secret_name): "ANSIBLE_VAULT_KEYFILE", "/share/ansible_vault_password.key" ) +# Root of the configuration repository's environments, as `osism apply` sees it. +ENVIRONMENTS_DIRECTORY = os.getenv( + "ENVIRONMENTS_DIRECTORY", "/opt/configuration/environments" +) + NETBOX_URL = os.getenv("NETBOX_API", os.getenv("NETBOX_URL")) NETBOX_TOKEN = str( diff --git a/osism/utils/evaluate.py b/osism/utils/evaluate.py new file mode 100644 index 000000000..b8bbc01e8 --- /dev/null +++ b/osism/utils/evaluate.py @@ -0,0 +1,98 @@ +# osism/utils/evaluate.py +# SPDX-License-Identifier: Apache-2.0 + +"""Evaluate one render request: dependency closures and values, in one pass. + +Runs inside the ``osism_render`` action plugin, so that dynamic keys +discovered while walking a closure are resolved by Ansible's own templar +in the same invocation (one Ansible run per stack). ``resolve`` templates +one expression and returns ``{"value": ...}`` or ``{"error": str}``; unit +tests pass a fake. + +Request: + names -- variables to report + secrets -- the secret set S of this stack; always rendered, for the + literal net + raw -- name -> raw value for the queried host, stack files already + applied over the inventory + raw_all -- name -> list of raw values across all hosts (and the stack + value), for cross-host references + +Result: + values -- name -> {"value": v} | {"error": str}, for names and secrets + closures -- name -> {"names": [...], "unanalysable": bool, + "undefined": [...], "secret_hits": [...], + "uses_default": bool} +""" + +from typing import Callable + +from osism.utils.template_deps import references + +Resolve = Callable[[str], dict] + + +def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dict: + raw, raw_all = request["raw"], request["raw_all"] + seen: set = set() + names: set = set() + undefined: set = set() + unanalysable = False + uses_default = False + work = [(name, "host")] + while work: + current, scope = work.pop() + if (current, scope) in seen: + continue + seen.add((current, scope)) + if current != name: + names.add(current) + sources = [raw[current]] if scope == "host" and current in raw else [] + if scope == "all": + sources = list(raw_all.get(current, [])) + if current in raw: + sources.append(raw[current]) + if not sources: + if current != name: + undefined.add(current) + continue + for value in sources: + refs = references(value) + if refs.unanalysable: + unanalysable = True + if isinstance(value, str) and "default(" in value.replace(" ", ""): + uses_default = True + for n in refs.names: + work.append((n, scope)) + for n in refs.cross_host_names: + work.append((n, "all")) + for key in refs.dynamic_keys: + if key.expression is None: + unanalysable = True + continue + if key.expression not in key_cache: + key_cache[key.expression] = resolve(key.expression) + result = key_cache[key.expression] + if "error" in result or not isinstance(result.get("value"), str): + unanalysable = True + continue + work.append((result["value"], "all" if key.cross_host else scope)) + secrets = set(request["secrets"]) + return { + "names": sorted(names), + "unanalysable": unanalysable, + "undefined": sorted(undefined), + "secret_hits": sorted(names & secrets), + "uses_default": uses_default, + } + + +def evaluate_request(resolve: Resolve, request: dict) -> dict: + key_cache: dict = {} + closures = {n: _closure(n, request, resolve, key_cache) for n in request["names"]} + values: dict = {} + for n in list(request["names"]) + sorted( + set(request["secrets"]) - set(request["names"]) + ): + values[n] = resolve(n) + return {"values": values, "closures": closures} diff --git a/osism/utils/render.py b/osism/utils/render.py new file mode 100644 index 000000000..385842856 --- /dev/null +++ b/osism/utils/render.py @@ -0,0 +1,247 @@ +# osism/utils/render.py +# SPDX-License-Identifier: Apache-2.0 + +"""Render variables the way `osism apply` would see them in an environment. + +One controller-side Ansible run per (host, stack). The stack is the +inventory plus the extra-vars files the standard run scripts pass +(osism-ansible files/scripts/run-*.sh, kolla-ansible +files/scripts//run.sh), in their order. The action plugin runs +osism.utils.evaluate.evaluate_request with Ansible's templar as the +resolver, so dependency closures, dynamic keys and values all come out of +that one run. +""" + +import json +import os +import subprocess +import tempfile +from dataclasses import dataclass +from typing import cast + +import yaml + +from osism import settings + +_PLUGIN = """\ +import json +from ansible.plugins.action import ActionBase +from ansible.template import trust_as_template + + +class ActionModule(ActionBase): + TRANSFERS_FILES = False + + def run(self, tmp=None, task_vars=None): + from osism.utils.evaluate import evaluate_request + + result = super().run(tmp, task_vars) + + def resolve(expr): + try: + value = self._templar.template(trust_as_template("{{ %s }}" % expr)) + json.dumps(value, default=str) + return {"value": value} + except Exception as exc: + return {"error": f"{type(exc).__name__}: {exc}"} + + with open(self._task.args["request"]) as fp: + request = json.load(fp) + with open(self._task.args["dest"], "w") as fp: + json.dump(evaluate_request(resolve, request), fp, default=str) + result["changed"] = False + return result +""" + + +class RenderError(Exception): + """Ansible could not run, or the stack cannot be applied or read. + + ``safe`` is True for messages composed here (missing file, invalid YAML + at a line, cannot decrypt), which never carry values. It is False for + Ansible's own output, which may quote secrets. Callers withhold it + unless --show-secrets. + """ + + def __init__(self, message: str, safe: bool = True): + super().__init__(message) + self.safe = safe + + +@dataclass(frozen=True) +class Stack: + environment: str | None + files: tuple + missing: tuple + + +class _VaultSafeLoader(yaml.SafeLoader): + """SafeLoader that keeps an inline !vault value as the encrypted marker.""" + + +def _construct_vault(loader: yaml.SafeLoader, node: yaml.Node) -> dict: + return {"__ansible_vault": loader.construct_scalar(cast(yaml.ScalarNode, node))} + + +_VaultSafeLoader.add_constructor("!vault", _construct_vault) + + +def list_environments(root: str | None = None) -> list: + root = root or settings.ENVIRONMENTS_DIRECTORY + try: + entries = os.listdir(root) + except OSError: + return [] + return sorted( + e + for e in entries + if not e.startswith(".") and os.path.isdir(os.path.join(root, e)) + ) + + +def environment_files(environment: str, root: str | None = None) -> tuple: + root = root or settings.ENVIRONMENTS_DIRECTORY + return tuple( + os.path.join(root, environment, f) + for f in ("secrets.yml", "images.yml", "configuration.yml") + ) + + +def build_stack(environment: str | None, root: str | None = None) -> Stack: + root = root or settings.ENVIRONMENTS_DIRECTORY + files = [os.path.join(root, "configuration.yml"), os.path.join(root, "secrets.yml")] + if environment: + files += list(environment_files(environment, root)) + return Stack( + environment, tuple(files), tuple(f for f in files if not os.path.isfile(f)) + ) + + +def _check(stack: Stack) -> None: + if stack.missing: + raise RenderError( + f"{stack.missing[0]} missing; this environment cannot be applied" + ) + + +def load_yaml(path: str, vault_password: str) -> dict: + from ansible.constants import DEFAULT_VAULT_ID_MATCH + from ansible.parsing.vault import VaultLib, VaultSecret + + vault = VaultLib([(DEFAULT_VAULT_ID_MATCH, VaultSecret(vault_password.encode()))]) + with open(path, "rb") as fp: + data = fp.read() + if vault.is_encrypted(data): + try: + data = vault.decrypt(data) + except Exception as exc: + raise RenderError(f"cannot decrypt {path} ({type(exc).__name__})") from exc + try: + loaded = yaml.load(data, Loader=_VaultSafeLoader) or {} + except yaml.YAMLError as exc: + mark = getattr(exc, "problem_mark", None) + line = mark.line + 1 if mark is not None else "?" + raise RenderError( + f"{path}: invalid YAML at line {line} ({type(exc).__name__})" + ) from None + if not isinstance(loaded, dict): + raise RenderError(f"{path} is not a mapping") + return loaded + + +def load_stack_files( + stack: Stack, vault_password: str, allow_missing: bool = False +) -> list: + if not allow_missing: + _check(stack) + return [ + (p, load_yaml(p, vault_password)) for p in stack.files if p not in stack.missing + ] + + +def stack_file_names( + stack: Stack, vault_password: str, allow_missing: bool = False +) -> dict: + names: dict = {} + for path, loaded in load_stack_files(stack, vault_password, allow_missing): + for key in loaded: + names[key] = path + return names + + +def environment_local_names( + environment: str, vault_password: str, root: str | None = None +) -> set: + names: set = set() + for path in environment_files(environment, root): + if os.path.isfile(path): + names |= set(load_yaml(path, vault_password)) + return names + + +def render_batch( + host, request, inventory_path, stack, vault_password, facts=None, timeout=300 +): + _check(stack) + with tempfile.TemporaryDirectory(prefix="osism-render-") as workdir: + with open(os.path.join(workdir, "osism_render.py"), "w") as fp: + fp.write(_PLUGIN) + vault_file = os.path.join(workdir, "vault") + with open(os.open(vault_file, os.O_WRONLY | os.O_CREAT, 0o600), "w") as fp: + fp.write(vault_password) + request_file = os.path.join(workdir, "request.json") + with open(request_file, "w") as fp: + json.dump(request, fp) + dest = os.path.join(workdir, "out.json") + command = [ + "ansible", + host, + "-i", + inventory_path, + "-c", + "local", + "-m", + "osism_render", + "-a", + json.dumps({"request": request_file, "dest": dest}), + "--vault-password-file", + vault_file, + ] + for path in stack.files: + command += ["-e", f"@{path}"] + if facts: + facts_path = os.path.join(workdir, "facts.json") + with open(facts_path, "w") as fp: + json.dump(facts, fp) + command += ["-e", f"@{facts_path}"] + env = os.environ.copy() + env.update( + ANSIBLE_GATHERING="explicit", + ANSIBLE_NOCOLOR="1", + ANSIBLE_RETRY_FILES_ENABLED="False", + ) + env["ANSIBLE_ACTION_PLUGINS"] = os.pathsep.join( + p for p in (workdir, env.get("ANSIBLE_ACTION_PLUGINS")) if p + ) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=timeout, + env=env, + cwd=workdir, + stdin=subprocess.DEVNULL, + ) + except subprocess.TimeoutExpired as exc: + raise RenderError(f"ansible timed out after {timeout}s") from exc + if result.returncode != 0: + detail = (result.stdout or "").strip() or (result.stderr or "").strip() + raise RenderError( + detail or f"ansible exited {result.returncode}", safe=False + ) + try: + with open(dest) as fp: + return json.load(fp) + except OSError as exc: + raise RenderError("ansible wrote no result") from exc diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py new file mode 100644 index 000000000..6eb49a80b --- /dev/null +++ b/tests/integration/test_hostvars_render.py @@ -0,0 +1,104 @@ +# tests/integration/test_hostvars_render.py +# SPDX-License-Identifier: Apache-2.0 + +"""render_batch end to end against real Ansible; the plugin imports osism.""" + +import os +import shutil +import subprocess + +import pytest + +from osism.utils.render import ( + build_stack, + environment_local_names, + load_yaml, + render_batch, +) + +pytestmark = pytest.mark.integration + + +@pytest.fixture(scope="module", autouse=True) +def _require_ansible(): + if shutil.which("ansible"): + return + if os.environ.get("OSISM_REQUIRE_ANSIBLE"): + pytest.fail("OSISM_REQUIRE_ANSIBLE is set but 'ansible' is not on PATH") + pytest.skip("ansible not on PATH") + + +@pytest.fixture +def setup(tmp_path): + pw = tmp_path / "pw" + pw.write_text("probe-vault-pw") + inline = subprocess.run( + [ + "ansible-vault", + "encrypt_string", + "--vault-password-file", + str(pw), + "inline-secret-xyz", + "--name", + "inline_pw", + ], + check=True, + capture_output=True, + text=True, + stdin=subprocess.DEVNULL, + ).stdout + inv = tmp_path / "hosts.yml" + inv.write_text("all:\n hosts:\n node1:\n ansible_host: 192.0.2.10\n") + root = tmp_path / "environments" + (root / "kolla").mkdir(parents=True) + (root / "configuration.yml").write_text( + "n: k1\nk1: '{{ vars[m] }}'\nm: db_password\nd: '{{ vars[n] | b64encode }}'\n" + ) + (root / "secrets.yml").write_text("db_password: long-secret-1\n") + subprocess.run( + [ + "ansible-vault", + "encrypt", + "--vault-password-file", + str(pw), + str(root / "secrets.yml"), + ], + check=True, + capture_output=True, + stdin=subprocess.DEVNULL, + ) + (root / "kolla" / "secrets.yml").write_text("{}\n") + (root / "kolla" / "images.yml").write_text("{}\n") + (root / "kolla" / "configuration.yml").write_text( + inline + "svc_url: 'https://u:{{ inline_pw }}@h'\n" + ) + return str(inv), str(root) + + +def test_one_run_resolves_chains_and_vaults(setup): + inv, root = setup + stack = build_stack("kolla", root) + raw = {} + for path in stack.files: + raw.update(load_yaml(path, "probe-vault-pw")) + request = { + "names": ["d", "svc_url", "zz"], + "secrets": ["db_password", "inline_pw"], + "raw": raw, + "raw_all": {}, + } + out = render_batch("node1", request, inv, stack, "probe-vault-pw") + assert out["closures"]["d"]["secret_hits"] == ["db_password"] + assert out["closures"]["svc_url"]["secret_hits"] == ["inline_pw"] + assert out["values"]["svc_url"] == {"value": "https://u:inline-secret-xyz@h"} + assert out["values"]["db_password"] == {"value": "long-secret-1"} + assert "undefined" in out["values"]["zz"]["error"] + assert raw["inline_pw"].keys() == {"__ansible_vault"} + + +def test_environment_local_names_reads_inline_vault(setup): + _, root = setup + assert environment_local_names("kolla", "probe-vault-pw", root) == { + "inline_pw", + "svc_url", + } diff --git a/tests/unit/utils/test_evaluate.py b/tests/unit/utils/test_evaluate.py new file mode 100644 index 000000000..33f23c7f5 --- /dev/null +++ b/tests/unit/utils/test_evaluate.py @@ -0,0 +1,107 @@ +# tests/unit/utils/test_evaluate.py +# SPDX-License-Identifier: Apache-2.0 + +from osism.utils.evaluate import evaluate_request + + +def _resolver(table, calls=None): + def resolve(expr): + if calls is not None: + calls.append(expr) + if expr in table: + return {"value": table[expr]} + return {"error": f"AnsibleUndefinedVariable: '{expr}' is undefined"} + + return resolve + + +def _req(names, raw, secrets=(), raw_all=None): + return { + "names": names, + "secrets": list(secrets), + "raw": raw, + "raw_all": raw_all or {}, + } + + +def test_static_closure_and_secret_hits(): + r = evaluate_request( + _resolver({"c": "v", "redis_master_password": "s3cr3t-value-1"}), + _req( + ["c"], + { + "c": "redis://{{ redis_master_password }}@h", + "redis_master_password": "x", + }, + secrets=["redis_master_password"], + ), + ) + assert r["closures"]["c"]["secret_hits"] == ["redis_master_password"] + + +def test_chained_dynamic_keys_resolve_in_one_evaluation(): + calls = [] + raw = { + "d": "{{ vars[n] | b64encode }}", + "n": "k1", + "k1": "{{ vars[m] }}", + "m": "db_password", + "db_password": "x", + } + r = evaluate_request( + _resolver( + {"n": "k1", "m": "db_password", "d": "ZZ", "db_password": "long-secret-1"}, + calls, + ), + _req(["d"], raw, secrets=["db_password"]), + ) + assert r["closures"]["d"]["secret_hits"] == ["db_password"] + assert not r["closures"]["d"]["unanalysable"] + assert calls.count("n") == 1 and calls.count("m") == 1 + + +def test_all_secrets_are_rendered_even_when_unreached(): + # Review round 3, point 3: the literal net needs every value in S. + r = evaluate_request( + _resolver({"a": "1", "db_password": "long-secret-1"}), + _req(["a"], {"a": "1"}, secrets=["db_password"]), + ) + assert r["values"]["db_password"] == {"value": "long-secret-1"} + + +def test_unresolvable_key_is_unanalysable(): + r = evaluate_request( + _resolver({}), _req(["d"], {"d": "{{ vars[x.split('-') | first] }}"}) + ) + assert r["closures"]["d"]["unanalysable"] + + +def test_key_render_error_is_unanalysable(): + r = evaluate_request(_resolver({}), _req(["d"], {"d": "{{ vars[n] }}"})) + assert r["closures"]["d"]["unanalysable"] + + +def test_cross_host_uses_every_hosts_definition(): + raw = { + "ep": "{{ hostvars[other]['endpoint'] }}", + "endpoint": "plain", + "other": "node2", + } + r = evaluate_request( + _resolver({}), + _req( + ["ep"], + raw, + secrets=["redis_master_password"], + raw_all={"endpoint": ["plain", "x{{ redis_master_password }}"]}, + ), + ) + assert r["closures"]["ep"]["secret_hits"] == ["redis_master_password"] + + +def test_undefined_and_default_are_reported(): + r = evaluate_request( + _resolver({"e": "fb"}), _req(["e"], {"e": "{{ nope | default('fb') }}"}) + ) + assert r["closures"]["e"]["undefined"] == ["nope"] + assert r["closures"]["e"]["uses_default"] is True diff --git a/tests/unit/utils/test_render.py b/tests/unit/utils/test_render.py new file mode 100644 index 000000000..f1fc4cf3f --- /dev/null +++ b/tests/unit/utils/test_render.py @@ -0,0 +1,149 @@ +# tests/unit/utils/test_render.py +# SPDX-License-Identifier: Apache-2.0 + +import json + +import pytest + +from osism.utils import render +from osism.utils.render import ( + RenderError, + build_stack, + environment_local_names, + list_environments, + load_yaml, + render_batch, +) + + +def _envs(tmp_path, *names, files=("configuration.yml", "images.yml", "secrets.yml")): + root = tmp_path / "environments" + root.mkdir() + (root / "configuration.yml").write_text("a: 1\n") + (root / "secrets.yml").write_text("s: x\n") + (root / "images.yml").write_text("i: 1\n") + (root / "ansible.cfg").write_text("") + (root / ".hidden").mkdir() + for n in names: + d = root / n + d.mkdir() + for f in files: + (d / f).write_text(f"{n}_{f.split('.')[0]}: 1\n") + return str(root) + + +def test_list_environments_directories_only(tmp_path): + assert list_environments(_envs(tmp_path, "kolla", "ceph")) == ["ceph", "kolla"] + + +def test_global_stack_order_and_excludes_top_level_images(tmp_path): + s = build_stack(None, _envs(tmp_path, "kolla")) + assert [p.rsplit("/", 1)[1] for p in s.files] == [ + "configuration.yml", + "secrets.yml", + ] + + +def test_environment_stack_order(tmp_path): + root = _envs(tmp_path, "kolla") + assert [p.replace(root + "/", "") for p in build_stack("kolla", root).files] == [ + "configuration.yml", + "secrets.yml", + "kolla/secrets.yml", + "kolla/images.yml", + "kolla/configuration.yml", + ] + + +def test_missing_environment_file_is_recorded(tmp_path): + # Review focus 4 + root = _envs(tmp_path, "kolla", files=("configuration.yml", "secrets.yml")) + assert build_stack("kolla", root).missing == (f"{root}/kolla/images.yml",) + + +def test_environment_local_names_excludes_global(tmp_path): + # Review round 3, point 6 + root = _envs(tmp_path, "kolla") + assert environment_local_names("kolla", "pw", root) == { + "kolla_configuration", + "kolla_images", + "kolla_secrets", + } + + +def test_load_yaml_inline_vault_keeps_provenance(tmp_path): + f = tmp_path / "c.yml" + f.write_text("p: !vault |\n $ANSIBLE_VAULT;1.1;AES256\n 6162\nq: plain\n") + assert load_yaml(str(f), "pw") == { + "p": {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n6162\n"}, + "q": "plain", + } + + +def test_load_yaml_error_has_no_excerpt(tmp_path): + f = tmp_path / "c.yml" + f.write_text("db_password: s3cr3t\nbad: [\n") + with pytest.raises(RenderError) as exc: + load_yaml(str(f), "pw") + assert "invalid YAML at line" in str(exc.value) and "s3cr3t" not in str(exc.value) + + +def test_render_batch_refuses_missing_files(tmp_path): + root = _envs(tmp_path, "kolla", files=("configuration.yml", "secrets.yml")) + with pytest.raises( + RenderError, match="images.yml missing; this environment cannot be applied" + ): + render_batch("h", {"names": []}, "/inv", build_stack("kolla", root), "pw") + + +def test_render_batch_is_one_argv_run_with_neutral_cwd(tmp_path, mocker): + # Review focus 5 and the one-run-per-stack requirement. + root = _envs(tmp_path, "kolla") + runs = [] + + def fake_run(cmd, **kwargs): + runs.append((cmd, kwargs)) + args = json.loads(cmd[cmd.index("-a") + 1]) + with open(args["dest"], "w") as fp: + json.dump({"values": {}, "closures": {}}, fp) + return mocker.Mock(returncode=0, stdout="", stderr="") + + mocker.patch.object(render.subprocess, "run", side_effect=fake_run) + render_batch( + "node;rm -rf /", + {"names": ["a"], "secrets": [], "raw": {}, "raw_all": {}}, + "/inv", + build_stack("kolla", root), + "pw", + ) + assert len(runs) == 1 + cmd, kwargs = runs[0] + assert isinstance(cmd, list) and cmd[1] == "node;rm -rf /" and "shell" not in kwargs + assert kwargs["cwd"] not in ("/ansible", None) + extra = [cmd[i + 1] for i, a in enumerate(cmd) if a == "-e"] + assert [e.replace("@" + root + "/", "") for e in extra] == [ + "configuration.yml", + "secrets.yml", + "kolla/secrets.yml", + "kolla/images.yml", + "kolla/configuration.yml", + ] + + +def test_render_batch_ansible_failure_raises_unsafe(tmp_path, mocker): + root = _envs(tmp_path) + mocker.patch.object( + render.subprocess, + "run", + return_value=mocker.Mock(returncode=4, stdout="", stderr="boom"), + ) + with pytest.raises(RenderError, match="boom") as exc: + render_batch("h", {"names": []}, "/inv", build_stack(None, root), "pw") + assert exc.value.safe is False + + +def test_own_render_errors_are_safe(tmp_path): + root = _envs(tmp_path, "kolla", files=("configuration.yml", "secrets.yml")) + with pytest.raises(RenderError) as exc: + render_batch("h", {"names": []}, "/inv", build_stack("kolla", root), "pw") + assert exc.value.safe is True From 69cfc3af191777e786fd26c5838172461d4e8ac2 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:20:58 +0200 Subject: [PATCH 04/16] Compute effective hostvars rows `osism dump inventory` is to show the values a play would see. This adds effective_rows, which turns per-stack render results into output rows: - shown names: the variable asked for, or the union of the host's raw names, the stack files' names and, without --environment, each environment's own names, so environment-only variables appear; - one render per stack: the primary stack, plus each environment whose own files define a shown variable or a name in its dependency closure; for an unanalysable variable every environment is rendered and its row kept only if the value differs from the global one; - an environment with a missing file, or whose files cannot be read, gives failed rows for its candidates only; - the secret set S per stack: names in secrets.yml, names matching the key rule, and names whose value is vault-encrypted on any host. Masking, unless --show-secrets: a variable in S or whose closure reaches S is masked and the note names the secrets; an unanalysable one is masked; otherwise every rendered secret value of 6 or more characters is replaced in the value. The same replacement runs over error and fallback notes. Error detail of a tainted or unanalysable variable is withheld, as is Ansible's own output when a whole stack fails, since that stack's secret values are then unknown. An unknown --environment is rejected before any path is built from it. Masking and row construction live in hostvars_rows. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/hostvars.py | 224 ++++++++++++++ osism/utils/hostvars_rows.py | 167 ++++++++++ tests/unit/utils/test_hostvars.py | 493 ++++++++++++++++++++++++++++++ 3 files changed, 884 insertions(+) create mode 100644 osism/utils/hostvars.py create mode 100644 osism/utils/hostvars_rows.py create mode 100644 tests/unit/utils/test_hostvars.py diff --git a/osism/utils/hostvars.py b/osism/utils/hostvars.py new file mode 100644 index 000000000..f61fc3875 --- /dev/null +++ b/osism/utils/hostvars.py @@ -0,0 +1,224 @@ +# osism/utils/hostvars.py +# SPDX-License-Identifier: Apache-2.0 + +"""Effective hostvars: the values `osism apply` would see, as output rows. + +One render per stack: the primary stack (global, or the one given with +--environment) and, without --environment, each environment whose own +files can change a shown variable. Masking and row construction live in +osism.utils.hostvars_rows. When a whole stack fails, its secret values +are unknown, so Ansible's own output is withheld unless --show-secrets. +""" + +from dataclasses import dataclass +from typing import Any, Callable + +from osism.utils.hostvars_rows import ( + Rendered, + Row, + closure_of, + secret_set, + secret_values, + stack_rows, +) +from osism.utils.render import ( + RenderError, + Stack, + build_stack, + environment_local_names, + list_environments, + load_stack_files, + render_batch, +) + +__all__ = ["HostvarsError", "Row", "effective_rows"] + +STACK_WITHHELD = ( + "render failed (Ansible failed for this stack; detail withheld; " + "use --show-secrets)" +) + + +class HostvarsError(Exception): + pass + + +@dataclass +class _Ctx: + host: str + show_secrets: bool + inventory_path: str + vault_password: str + facts: Any + raw_hostvars: dict + all_raw_hostvars: dict + root: str | None + renderer: Callable + + +# Step 1 +def _primary_stack(environment: str | None, root: str | None) -> Stack: + if environment is not None: + # Validated before any path is built from it. + available = list_environments(root) + if environment not in available: + raise HostvarsError( + f"unknown environment {environment}; " + f"available: {', '.join(available)}" + ) + return build_stack(environment, root=root) + + +# Step 2 +def _merged_raw(stack: Stack, ctx: _Ctx) -> tuple: + files = load_stack_files(stack, ctx.vault_password, allow_missing=True) + raw = dict(ctx.raw_hostvars) + for _, loaded in files: + raw.update(loaded) + return files, raw + + +def _raw_all(all_raw_hostvars: dict) -> dict: + raw_all: dict = {} + for host_vars in all_raw_hostvars.values(): + for name, value in host_vars.items(): + raw_all.setdefault(name, []).append(value) + return raw_all + + +# Step 3 +def _environment_locals(ctx: _Ctx) -> dict: + """Each environment's own names, or the RenderError reading them.""" + env_local: dict = {} + for e in list_environments(ctx.root): + try: + env_local[e] = set( + environment_local_names(e, ctx.vault_password, root=ctx.root) + ) + except RenderError as exc: + env_local[e] = exc + return env_local + + +def _shown_names(variable, files: list, ctx: _Ctx, env_local: dict) -> list: + if variable is not None: + return [variable] + names = set(ctx.raw_hostvars) + for _, loaded in files: + names |= set(loaded) + for local in env_local.values(): + if not isinstance(local, RenderError): + names |= local + return sorted(names) + + +# Steps 4 and 5 +def _render(stack: Stack, names: list, ctx: _Ctx, merged=None) -> Rendered: + files, raw = merged or _merged_raw(stack, ctx) + secrets = secret_set(files, raw, ctx.all_raw_hostvars) + request = { + "names": list(names), + "secrets": sorted(secrets), + "raw": raw, + "raw_all": _raw_all(ctx.all_raw_hostvars), + } + result = ctx.renderer( + ctx.host, request, ctx.inventory_path, stack, ctx.vault_password, ctx.facts + ) + values = result.get("values") or {} + closures = result.get("closures") or {} + return Rendered(values, closures, secrets, secret_values(values, secrets)) + + +# Step 7 +def _candidates(names: list, local, closures: dict) -> tuple: + """(candidates, measured). Measured names are candidates only by being + unanalysable; they keep their row only if the value differs.""" + if isinstance(local, RenderError): + return list(names), set() + candidates, measured = [], set() + for name in names: + closure = closure_of(closures, name) + if name in local or set(closure["names"]) & local: + candidates.append(name) + elif closure["unanalysable"]: + candidates.append(name) + measured.add(name) + return candidates, measured + + +def _environment_rows(e: str, local, names: list, primary: Rendered, ctx: _Ctx): + candidates, measured = _candidates(names, local, primary.closures) + if not candidates: + return {} + if isinstance(local, RenderError): + return _failed_rows(candidates, e, _stack_failure_note(local, ctx), ctx) + stack = build_stack(e, root=ctx.root) + if stack.missing: + note = ( + f"render failed: {stack.missing[0]} missing; " + "this environment cannot be applied" + ) + return _failed_rows(candidates, e, note, ctx) + try: + rendered = _render(stack, candidates, ctx) + except RenderError as exc: + return _failed_rows(candidates, e, _stack_failure_note(exc, ctx), ctx) + rows = stack_rows(ctx.host, candidates, e, rendered, ctx.show_secrets) + for name in measured & set(rows): + if rendered.values.get(name) == primary.values.get(name): + del rows[name] + return rows + + +def _failed_rows(names: list, environment, note: str, ctx: _Ctx) -> dict: + return {n: Row(ctx.host, n, environment, None, False, [note], True) for n in names} + + +# Step 9 +def _stack_failure_note(exc: RenderError, ctx: _Ctx) -> str: + if exc.safe or ctx.show_secrets: + return f"render failed: {exc}" + return STACK_WITHHELD + + +def effective_rows( + host, + variable, + environment, + show_secrets, + *, + inventory_path, + vault_password, + facts, + raw_hostvars, + all_raw_hostvars, + root=None, + renderer=render_batch, +) -> list: + ctx = _Ctx( + host, + show_secrets, + inventory_path, + vault_password, + facts, + raw_hostvars, + all_raw_hostvars, + root, + renderer, + ) + stack = _primary_stack(environment, root) + env_local = _environment_locals(ctx) if environment is None else {} + try: + merged = _merged_raw(stack, ctx) + names = _shown_names(variable, merged[0], ctx, env_local) + primary = _render(stack, names, ctx, merged) + except RenderError as exc: + # from None: an unsafe message must not ride along as __context__ + # into a printed traceback. + raise HostvarsError(_stack_failure_note(exc, ctx)) from None + per_env = [(None, stack_rows(host, names, None, primary, show_secrets))] + for e, local in env_local.items(): + per_env.append((e, _environment_rows(e, local, names, primary, ctx))) + # Step 8: an absent variable yields no rows, hence []. + return [rows[n] for n in names for _, rows in per_env if n in rows] diff --git a/osism/utils/hostvars_rows.py b/osism/utils/hostvars_rows.py new file mode 100644 index 000000000..81b61209e --- /dev/null +++ b/osism/utils/hostvars_rows.py @@ -0,0 +1,167 @@ +# osism/utils/hostvars_rows.py +# SPDX-License-Identifier: Apache-2.0 + +"""Masking and row construction for one stack's render result. + +Used by osism.utils.hostvars. Every value and every error text that +reaches a Row passes here first: + +- taint: a variable in the secret set S, or whose dependency closure + reaches S, is masked; an unanalysable one is masked too; +- literal net: every rendered secret value of 6 or more characters is + replaced wherever it occurs, in values and in notes; +- the error detail of a tainted or unanalysable variable is withheld. + +show_secrets disables all of it. +""" + +import os +import re +from dataclasses import dataclass, field +from typing import Any + +from osism.utils.secrets import ( + is_secret_key, + is_vault_value, + replace_literals, + replace_literals_deep, +) + +MASK = "***" +MIN_SECRET_LENGTH = 6 +WITHHELD = "render failed (detail withheld; use --show-secrets)" +_UNDEFINED = re.compile(r"^AnsibleUndefinedVariable: '([^']*)' is undefined") +# A closure, or a key of one, that did not come back counts as the worst case. +_UNKNOWN_CLOSURE: dict[str, Any] = { + "names": [], + "unanalysable": True, + "undefined": [], + "secret_hits": [], + "uses_default": False, +} + + +@dataclass +class Row: + host: str + variable: str + environment: str | None + value: Any + masked: bool + notes: list = field(default_factory=list) + failed: bool = False + + +@dataclass +class Rendered: + """One stack's render: its result, secret set S and secret values.""" + + values: dict + closures: dict + secrets: set + secret_values: list + + +def closure_of(closures: dict, name: str) -> dict[str, Any]: + return {**_UNKNOWN_CLOSURE, **(closures.get(name) or {})} + + +def secret_set(files: list, raw: dict, all_raw_hostvars: dict) -> set: + """Step 4: the secret set S of a stack.""" + secrets: set = set() + for path, loaded in files: + if os.path.basename(path) == "secrets.yml": + secrets |= set(loaded) + for name, value in raw.items(): + if is_secret_key(name) or is_vault_value(value): + secrets.add(name) + for host_vars in all_raw_hostvars.values(): + secrets |= {n for n, v in host_vars.items() if is_vault_value(v)} + return secrets + + +def secret_values(values: dict, secrets: set) -> list: + """Rendered strings of S (6+ characters), and every string inside + a list or dict value of S.""" + found: list = [] + + def collect(node: Any, top: bool) -> None: + if isinstance(node, str): + if not top or len(node) >= MIN_SECRET_LENGTH: + found.append(node) + elif isinstance(node, dict): + for item in node.values(): + collect(item, False) + elif isinstance(node, list): + for item in node: + collect(item, False) + elif isinstance(node, (int, float)) and not isinstance(node, bool): + collect(str(node), top) + + for name in secrets: + result = values.get(name) or {} + if "value" in result: + collect(result["value"], True) + return found + + +def _clean(text: Any, rendered: Rendered, show_secrets: bool) -> str: + if show_secrets: + return str(text) + return replace_literals(str(text), rendered.secret_values, MASK, MIN_SECRET_LENGTH) + + +def _row( + host: str, name: str, environment, rendered: Rendered, show_secrets: bool +) -> Row | None: + result = rendered.values.get(name) or {"error": "no result for this variable"} + closure = closure_of(rendered.closures, name) + tainted = name in rendered.secrets or bool(closure["secret_hits"]) + if "value" not in result: + error = str(result.get("error")) + match = _UNDEFINED.match(error) + if match and match.group(1) == name: + return None + if not show_secrets and (tainted or closure["unanalysable"]): + note = WITHHELD + else: + note = "render failed: " + _clean(error, rendered, show_secrets) + return Row(host, name, environment, None, False, [note], True) + value, masked, notes = result["value"], False, [] + if not show_secrets: + if tainted: + hits = sorted(closure["secret_hits"]) + sources = name if name in rendered.secrets else ", ".join(hits) + value, masked = MASK, True + notes.append(f"masked: derived from {sources}") + elif closure["unanalysable"]: + value, masked = MASK, True + notes.append("masked: could not analyse dependencies") + else: + cleaned = replace_literals_deep( + value, rendered.secret_values, MASK, MIN_SECRET_LENGTH + ) + value, masked = cleaned, cleaned != value + if closure["uses_default"]: + # A dynamic key resolved to a value can land in `undefined`. + notes += [ + _clean( + f"fallback: {n} undefined here, a role may define it", + rendered, + show_secrets, + ) + for n in sorted(closure["undefined"]) + ] + return Row(host, name, environment, value, masked, notes, False) + + +def stack_rows( + host: str, names: list, environment, rendered: Rendered, show_secrets: bool +) -> dict: + """Step 6: name -> Row; a name undefined in this stack gets none.""" + rows = {} + for name in names: + row = _row(host, name, environment, rendered, show_secrets) + if row is not None: + rows[name] = row + return rows diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py new file mode 100644 index 000000000..10e7ad7ba --- /dev/null +++ b/tests/unit/utils/test_hostvars.py @@ -0,0 +1,493 @@ +# tests/unit/utils/test_hostvars.py +# SPDX-License-Identifier: Apache-2.0 + +import base64 + +import pytest + +from osism.utils import hostvars as hv +from osism.utils.evaluate import evaluate_request +from osism.utils.render import Stack + + +@pytest.fixture +def world(mocker): + def make( + raw, + values, + *, + global_files=None, + env_local=None, + missing=None, + all_raw=None, + secrets_names=(), + ): + """values: {None: {...}, 'kolla': {...}} rendered per stack (env table overrides global).""" + calls = [] + env_local = env_local or {} + mocker.patch.object(hv, "list_environments", return_value=sorted(env_local)) + mocker.patch.object( + hv, + "build_stack", + side_effect=lambda e, root=None: Stack( + e, ("G",) if e is None else ("G", e), tuple((missing or {}).get(e, ())) + ), + ) + gf = dict(global_files or {}) + sec = {n: "x" for n in secrets_names} + + def load_stack_files(stack, pw, allow_missing=False): + files = [("G/configuration.yml", gf), ("G/secrets.yml", sec)] + if stack.environment: + files.append( + ( + f"{stack.environment}/configuration.yml", + env_local.get(stack.environment, {}), + ) + ) + return files + + mocker.patch.object(hv, "load_stack_files", side_effect=load_stack_files) + mocker.patch.object( + hv, + "environment_local_names", + side_effect=lambda e, pw, root=None: set(env_local.get(e, {})), + ) + + def renderer(host, request, inv, stack, pw, facts=None, timeout=300): + calls.append(stack.environment) + table = {**values.get(None, {}), **values.get(stack.environment, {})} + + def resolve(expr): + if expr not in table: + return {"error": f"AnsibleUndefinedVariable: '{expr}' is undefined"} + value = table[expr] + if isinstance(value, Exception): + return {"error": f"{type(value).__name__}: {value}"} + return {"value": value} + + return evaluate_request(resolve, request) + + def rows(variable=None, environment=None, show=False): + return hv.effective_rows( + "node1", + variable, + environment, + show, + inventory_path="/inv", + vault_password="pw", + facts=None, + raw_hostvars=raw, + all_raw_hostvars=all_raw or {"node1": raw}, + renderer=renderer, + ) + + rows.calls = calls + return rows + + return make + + +def _r(rows): + return [(r.environment, r.value) for r in rows] + + +def test_rendered_value_and_one_call(world): + get = world({"a": "{{ b }}", "b": "x"}, {None: {"a": "x", "b": "x"}}) + assert _r(get("a")) == [(None, "x")] + assert get.calls == [None] + + +def test_transitive_secret_is_masked_with_source(world): + rows = world( + {"redis_connection_string": "redis://default:{{ redis_master_password }}@h"}, + { + None: { + "redis_connection_string": "redis://default:s3cr3t-value-123@h", + "redis_master_password": "s3cr3t-value-123", + } + }, + secrets_names={"redis_master_password"}, + )("redis_connection_string") + assert rows[0].value == "***" and rows[0].notes == [ + "masked: derived from redis_master_password" + ] + + +def test_show_secrets_disables_masking(world): + rows = world( + {"c": "{{ db_password }}", "db_password": "p"}, + {None: {"c": "verysecret", "db_password": "verysecret"}}, + )("c", show=True) + assert rows[0].value == "verysecret" and not rows[0].masked + + +def test_filtered_dynamic_secret_is_masked(world): + rows = world( + {"d": "{{ vars[n] | b64encode }}", "n": "db_password", "db_password": "x"}, + { + None: { + "d": base64.b64encode(b"long-secret-1").decode(), + "n": "db_password", + "db_password": "long-secret-1", + } + }, + )("d") + assert rows[0].masked and "db_password" in rows[0].notes[0] + + +def test_unresolvable_dynamic_key_is_masked_as_unanalysable(world): + rows = world( + {"d": "{{ vars[x.split('-') | first] }}", "x": "a-b"}, + {None: {"d": "v", "x": "a-b"}}, + )("d") + assert rows[0].masked and rows[0].notes == [ + "masked: could not analyse dependencies" + ] + + +def test_benign_dynamic_reference_is_shown(world): + raw = { + "h": "{{ hostvars[inventory_hostname]['ansible_' + iface]['ipv4']['address'] }}", + "iface": "eth0", + } + rows = world( + raw, + { + None: { + "h": "10.0.0.5", + "'ansible_' + iface": "ansible_eth0", + "iface": "eth0", + } + }, + )("h") + assert rows[0].value == "10.0.0.5" and not rows[0].masked + + +def test_cross_host_taint(world): + raw = { + "ep": "{{ hostvars[other]['endpoint'] }}", + "endpoint": "plain", + "other": "node2", + } + all_raw = {"node1": raw, "node2": {"endpoint": "x{{ redis_master_password }}"}} + rows = world( + raw, + { + None: { + "ep": "xs3cr3t-value", + "other": "node2", + "redis_master_password": "s3cr3t-value", + } + }, + all_raw=all_raw, + secrets_names={"redis_master_password"}, + )("ep") + assert rows[0].masked + + +def test_literal_net_catches_unreached_secret(world): + # Review round 3, point 3: no taint path, yet the secret value appears. + rows = world( + {"u": "{{ lookup('env', 'X') }}"}, + {None: {"u": "pre-long-secret-1-post", "db_password": "long-secret-1"}}, + secrets_names={"db_password"}, + )("u") + assert rows[0].value == "pre-***-post" + + +def test_environment_row_from_dependency_override_only_for_that_env(world): + # Review round 3, point 6: global names do not create rows everywhere. + get = world( + {"X": "{{ Y }}", "Y": "g", "G1": "1"}, + {None: {"X": "g", "Y": "g", "G1": "1"}, "kolla": {"X": "k", "Y": "k"}}, + env_local={"kolla": {"Y": "k"}, "ceph": {}}, + ) + assert _r(get("X")) == [(None, "g"), ("kolla", "k")] + assert _r(get("G1")) == [(None, "1")] + + +def test_environment_row_from_dynamic_dependency(world): + rows = world( + {"X": "{{ vars['Y'] }}", "Y": "g"}, + {None: {"X": "g", "Y": "g"}, "kolla": {"X": "k", "Y": "k"}}, + env_local={"kolla": {"Y": "k"}}, + )("X") + assert ("kolla", "k") in _r(rows) + + +def test_unanalysable_is_measured_per_environment(world): + get = world( + {"X": "{{ vars[y.split('.')|first] }}", "y": "a.b"}, + {None: {"X": "g"}, "kolla": {"X": "k"}, "ceph": {"X": "g"}}, + env_local={"kolla": {}, "ceph": {}}, + ) + assert _r(get("X", show=True)) == [(None, "g"), ("kolla", "k")] + + +def test_environment_only_variable_in_full_dump_and_single(world): + # Review round 3, point 5: defined only in kolla/configuration.yml. + get = world( + {}, {"kolla": {"kolla_only": "v"}}, env_local={"kolla": {"kolla_only": "v"}} + ) + assert ("kolla_only", "kolla") in [(r.variable, r.environment) for r in get(None)] + assert _r(get("kolla_only")) == [("kolla", "v")] + + +def test_calls_are_one_per_rendered_stack(world): + get = world( + {"X": "{{ Y }}", "Y": "g"}, + {None: {"X": "g", "Y": "g"}, "kolla": {"X": "k"}}, + env_local={"kolla": {"Y": "k"}, "ceph": {}, "manager": {}}, + ) + get("X") + assert sorted(get.calls, key=str) == sorted([None, "kolla"], key=str) + + +def test_absent_variable_returns_empty(world): + assert world({"a": "1"}, {None: {"a": "1"}})("nope") == [] + + +def test_unknown_environment_raises_with_list(world): + get = world({"a": "1"}, {None: {"a": "1"}}, env_local={"kolla": {}, "ceph": {}}) + with pytest.raises( + hv.HostvarsError, match="unknown environment nope; available: ceph, kolla" + ): + get("a", environment="nope") + + +def test_missing_environment_file_marks_only_candidates(world): + # Review focus 4 + get = world( + {"X": "{{ Y }}", "Y": "g", "Z": "z"}, + {None: {"X": "g", "Y": "g", "Z": "z"}}, + env_local={"kolla": {"Y": "k"}}, + missing={"kolla": ("kolla/images.yml",)}, + ) + kolla = [r for r in get("X") if r.environment == "kolla"][0] + assert kolla.failed and kolla.notes == [ + "render failed: kolla/images.yml missing; this environment cannot be applied" + ] + assert _r(get("Z")) == [(None, "z")] + assert None in get.calls and "kolla" not in get.calls + + +def test_error_detail_withheld_for_tainted(world): + rows = world( + {"c": "{{ db_password | bad }}", "db_password": "x"}, + { + None: { + "db_password": "long-secret-1", + "c": TypeError("No filter named 'bad'"), + } + }, + )("c") + assert rows[0].failed and rows[0].notes == [ + "render failed (detail withheld; use --show-secrets)" + ] + + +def test_error_detail_sanitised_for_untainted(mocker): + mocker.patch.object(hv, "list_environments", return_value=[]) + mocker.patch.object( + hv, "build_stack", side_effect=lambda e, root=None: Stack(e, ("G",), ()) + ) + mocker.patch.object( + hv, + "load_stack_files", + side_effect=lambda *a, **k: [("G/secrets.yml", {"db_password": "x"})], + ) + mocker.patch.object(hv, "environment_local_names", return_value=set()) + + def renderer(host, request, *a, **k): + return { + "values": { + "u": {"error": "TypeError: cannot use long-secret-1 here"}, + "db_password": {"value": "long-secret-1"}, + }, + "closures": { + "u": { + "names": ["q"], + "unanalysable": False, + "undefined": ["q"], + "secret_hits": [], + "uses_default": False, + } + }, + } + + rows = hv.effective_rows( + "node1", + "u", + None, + False, + inventory_path="/inv", + vault_password="pw", + facts=None, + raw_hostvars={"u": "{{ q }}"}, + all_raw_hostvars={"node1": {"u": "{{ q }}"}}, + renderer=renderer, + ) + assert rows[0].notes == ["render failed: TypeError: cannot use *** here"] + + +def test_cross_host_vault_value_taints(world): + raw = {"t": "{{ hostvars['node2']['token'] | b64encode }}"} + all_raw = { + "node1": raw, + "node2": {"token": {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n61"}}, + } + rows = world(raw, {None: {"t": "ZW5jb2RlZA=="}}, all_raw=all_raw)("t") + assert rows[0].masked and rows[0].notes == ["masked: derived from token"] + + +def test_environment_stack_failure_withholds_ansible_output(world, mocker): + from osism.utils.render import RenderError + + get = world( + {"X": "{{ Y }}", "Y": "g"}, + {None: {"X": "g", "Y": "g"}}, + env_local={"kolla": {"Y": "k"}}, + ) + real = hv.effective_rows + + def failing_renderer(host, request, inv, stack, pw, facts=None, timeout=300): + if stack.environment == "kolla": + raise RenderError("fatal: kolla-only-secret-xyz leaked", safe=False) + return evaluate_request( + lambda e: ( + {"value": {"X": "g", "Y": "g"}[e]} + if e in ("X", "Y") + else {"error": f"AnsibleUndefinedVariable: '{e}' is undefined"} + ), + request, + ) + + rows = real( + "node1", + "X", + None, + False, + inventory_path="/inv", + vault_password="pw", + facts=None, + raw_hostvars={"X": "{{ Y }}", "Y": "g"}, + all_raw_hostvars={"node1": {"X": "{{ Y }}", "Y": "g"}}, + renderer=failing_renderer, + ) + kolla = [r for r in rows if r.environment == "kolla"][0] + assert kolla.notes == [ + "render failed (Ansible failed for this stack; detail withheld; use --show-secrets)" + ] + assert "kolla-only-secret-xyz" not in repr(rows) + + +def test_missing_fact_gives_failed_row(world): + # Review focus 1 + rows = world( + {"h": "{{ ansible_eth0['ipv4']['address'] }}"}, + {None: {"h": NameError("'ansible_eth0' is undefined")}}, + )("h") + assert rows[0].failed and rows[0].notes[0].startswith("render failed: ") + + +def test_fallback_note(world): + rows = world({"e": "{{ nope | default('fb') }}"}, {None: {"e": "fb"}})("e") + assert rows[0].notes == ["fallback: nope undefined here, a role may define it"] + + +def test_nested_secret_masks_whole_value(world): + # Review focus 2 + rows = world( + {"s": {"a": ["{{ db_password }}"]}, "db_password": "x"}, + {None: {"s": {"a": ["long-secret-1"]}, "db_password": "long-secret-1"}}, + )("s") + assert rows[0].value == "***" + + +# Beyond the brief: paths where a value or an error text could reach output. + + +def test_unknown_environment_is_not_joined_into_a_path(world): + get = world({"a": "1"}, {None: {"a": "1"}}, env_local={"kolla": {}}) + with pytest.raises(hv.HostvarsError): + get("a", environment="../../etc") + assert hv.build_stack.call_count == 0 + assert hv.environment_local_names.call_count == 0 + + +def test_literal_net_sets_masked(world): + rows = world( + {"u": "{{ lookup('env', 'X') }}"}, + {None: {"u": "long-secret-1", "db_password": "long-secret-1"}}, + secrets_names={"db_password"}, + )("u") + assert rows[0].value == "***" and rows[0].masked + + +def test_fallback_note_is_sanitised(world): + # A dynamic key resolving to a secret value enters `undefined`. + raw = {"e": "{{ vars[k] | default('fb') }}", "k": "{{ q }}"} + rows = world( + raw, + { + None: { + "e": "fb", + "k": "long-secret-1", + "q": "long-secret-1", + "db_password": "long-secret-1", + } + }, + secrets_names={"db_password"}, + )("e") + assert rows[0].notes == ["fallback: *** undefined here, a role may define it"] + + +def test_show_secrets_shows_error_detail(world): + rows = world( + {"c": "{{ db_password | bad }}", "db_password": "x"}, + {None: {"db_password": "long-secret-1", "c": TypeError("bad long-secret-1")}}, + )("c", show=True) + assert rows[0].notes == ["render failed: TypeError: bad long-secret-1"] + + +def test_primary_unsafe_failure_withheld(mocker): + from osism.utils.render import RenderError + + mocker.patch.object(hv, "list_environments", return_value=[]) + mocker.patch.object( + hv, "build_stack", side_effect=lambda e, root=None: Stack(e, ("G",), ()) + ) + mocker.patch.object(hv, "load_stack_files", return_value=[]) + + def renderer(*a, **k): + raise RenderError("fatal: leaked-secret-xyz", safe=False) + + kwargs = dict( + inventory_path="/inv", + vault_password="pw", + facts=None, + raw_hostvars={"a": "1"}, + all_raw_hostvars={"node1": {"a": "1"}}, + renderer=renderer, + ) + with pytest.raises(hv.HostvarsError) as exc: + hv.effective_rows("node1", "a", None, False, **kwargs) + assert str(exc.value) == hv.STACK_WITHHELD + assert exc.value.__suppress_context__ + with pytest.raises(hv.HostvarsError, match="leaked-secret-xyz"): + hv.effective_rows("node1", "a", None, True, **kwargs) + + +def test_unreadable_environment_fails_its_rows_only(world, mocker): + from osism.utils.render import RenderError + + get = world({"a": "1"}, {None: {"a": "1"}}, env_local={"kolla": {}}) + hv.environment_local_names.side_effect = RenderError( + "cannot decrypt kolla/secrets.yml (AnsibleError)" + ) + rows = get("a") + assert _r(rows) == [(None, "1"), ("kolla", None)] + assert rows[1].failed and rows[1].notes == [ + "render failed: cannot decrypt kolla/secrets.yml (AnsibleError)" + ] From 2fbd4348dff7b7ef1ee68f2042a721d93063ebd5 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:25:57 +0200 Subject: [PATCH 05/16] Widen the hostvars secret set The secret set S of a stack missed two kinds of secrets, and their values were printed unmasked: - the key rule (password, secret, ironic_osism_) was applied only to the queried host's names. A read of another host's variable, such as hostvars['node2']['ipmi_password'] with a plaintext value in node2's host_vars, or a value derived from it, was not tainted; - a vault value nested inside a dict or list was not detected, although Ansible decrypts it when templating the enclosing variable. S now applies the key rule and the vault rule to every host's names, and the vault rule walks dicts and lists to any depth. The integration test pins the exact ansible-core error for an undefined name, which the row builder matches to drop the row of an absent variable. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/hostvars_rows.py | 29 +++++++++++--- tests/integration/test_hostvars_render.py | 4 +- tests/unit/utils/test_hostvars.py | 48 +++++++++++++++++++++++ 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/osism/utils/hostvars_rows.py b/osism/utils/hostvars_rows.py index 81b61209e..62ec99624 100644 --- a/osism/utils/hostvars_rows.py +++ b/osism/utils/hostvars_rows.py @@ -66,17 +66,34 @@ def closure_of(closures: dict, name: str) -> dict[str, Any]: return {**_UNKNOWN_CLOSURE, **(closures.get(name) or {})} +def _contains_vault(value: Any) -> bool: + """True if a vault value occurs anywhere inside value.""" + if is_vault_value(value): + return True + if isinstance(value, dict): + return any(_contains_vault(v) for v in value.values()) + if isinstance(value, list): + return any(_contains_vault(v) for v in value) + return False + + +def _is_secret(name: Any, value: Any) -> bool: + return is_secret_key(name) or _contains_vault(value) + + def secret_set(files: list, raw: dict, all_raw_hostvars: dict) -> set: - """Step 4: the secret set S of a stack.""" + """Step 4: the secret set S of a stack. + + The key and vault rules apply to every host's names too: a + cross-host read (hostvars[h][name]) reaches another host's + definition of name, which the queried host's raw does not show. + """ secrets: set = set() for path, loaded in files: if os.path.basename(path) == "secrets.yml": secrets |= set(loaded) - for name, value in raw.items(): - if is_secret_key(name) or is_vault_value(value): - secrets.add(name) - for host_vars in all_raw_hostvars.values(): - secrets |= {n for n, v in host_vars.items() if is_vault_value(v)} + for variables in [raw, *all_raw_hostvars.values()]: + secrets |= {n for n, v in variables.items() if _is_secret(n, v)} return secrets diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py index 6eb49a80b..e2c442176 100644 --- a/tests/integration/test_hostvars_render.py +++ b/tests/integration/test_hostvars_render.py @@ -92,7 +92,9 @@ def test_one_run_resolves_chains_and_vaults(setup): assert out["closures"]["svc_url"]["secret_hits"] == ["inline_pw"] assert out["values"]["svc_url"] == {"value": "https://u:inline-secret-xyz@h"} assert out["values"]["db_password"] == {"value": "long-secret-1"} - assert "undefined" in out["values"]["zz"]["error"] + # hostvars_rows matches this exact shape to drop the row of an absent + # variable; a change in ansible-core's wording must fail here. + assert out["values"]["zz"]["error"] == "AnsibleUndefinedVariable: 'zz' is undefined" assert raw["inline_pw"].keys() == {"__ansible_vault"} diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index 10e7ad7ba..4e05e5257 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -491,3 +491,51 @@ def test_unreadable_environment_fails_its_rows_only(world, mocker): assert rows[1].failed and rows[1].notes == [ "render failed: cannot decrypt kolla/secrets.yml (AnsibleError)" ] + + +def test_cross_host_plaintext_password_key_is_masked(world): + # The key rule applies to every host's names, not only the queried one's. + raw = { + "bmc": "{{ hostvars['node2']['ipmi_password'] }}", + "ep": "{{ hostvars['node2']['endpoint'] }}", + } + all_raw = { + "node1": raw, + "node2": { + "ipmi_password": "Node2-Plain-Pw", + "endpoint": "https://admin:{{ ipmi_password }}@x", + }, + } + get = world( + raw, + {None: {"bmc": "Node2-Plain-Pw", "ep": "https://admin:Node2-Plain-Pw@x"}}, + all_raw=all_raw, + ) + for name in ("bmc", "ep"): + rows = get(name) + assert rows[0].value == "***" and rows[0].masked + assert rows[0].notes == ["masked: derived from ipmi_password"] + assert "Node2-Plain-Pw" not in repr(rows) + + +_VAULT = {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n61"} + + +def test_nested_vault_value_is_masked(world): + raw = {"ldap": {"bind_password": _VAULT, "token": _VAULT}} + rows = world( + raw, + {None: {"ldap": {"bind_password": "ldap-bind-pw-1", "token": "ldap-token-1"}}}, + )("ldap") + assert rows[0].value == "***" and rows[0].masked + assert rows[0].notes == ["masked: derived from ldap"] + + +def test_cross_host_nested_vault_value_is_masked(world): + raw = {"cfg": "{{ hostvars['node2']['ldap'] }}"} + all_raw = {"node1": raw, "node2": {"ldap": {"servers": [{"bind": _VAULT}]}}} + rows = world( + raw, {None: {"cfg": {"servers": [{"bind": "ldap-bind-pw-1"}]}}}, all_raw=all_raw + )("cfg") + assert rows[0].value == "***" and rows[0].masked + assert rows[0].notes == ["masked: derived from ldap"] From 91e7c0afc07d655a48587808ff4dd1f1ea943ca2 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:29:19 +0200 Subject: [PATCH 06/16] Render effective values in dump inventory "osism dump inventory" (alias "osism get hostvars") used to print the values exactly as defined, so templated values such as "{{ foo }}" were shown unevaluated. It now renders effective values by default, using the engine in osism.utils.hostvars. New options: --environment ENV render with this environment only; the help lists the available environments --raw today's output, unchanged byte for byte --show-secrets show values that are secrets or derived from secrets --format table (default, with a Notes column), value or json Values that are secrets, or derived from secrets, are masked as "***" unless --show-secrets is given. If the vault password is unavailable the command exits 1 and points to --raw; the exception text is never printed. Exit codes: an absent variable is 0 (json prints []); an unknown host, unknown environment, unavailable vault password or primary stack failure is 1, as is a failed row when a single variable is requested. A full dump with failed rows exits 0 and shows the failures in Notes. "--format value" exits 1 when the result is ambiguous across environments, masked or failed. Both ansible-inventory calls now use an argv list instead of a shell string, so host names are no longer interpreted by a shell. Scope limits: only the effective values of the selected host are rendered; templates that need runtime-only data may fall back and say so in Notes. See the osism documentation for details. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Roger Luethi --- osism/commands/get.py | 163 +++++++++++++++++++++++++- tests/unit/commands/test_get.py | 198 +++++++++++++++++++++++++++++++- 2 files changed, 353 insertions(+), 8 deletions(-) diff --git a/osism/commands/get.py b/osism/commands/get.py index 65b041d18..30c32ea63 100644 --- a/osism/commands/get.py +++ b/osism/commands/get.py @@ -4,15 +4,18 @@ import pprint import re import subprocess +import sys import json from cliff.command import Command from loguru import logger from tabulate import tabulate -from osism import utils +from osism import settings, utils from osism.utils import fact_cache +from osism.utils.hostvars import HostvarsError, Row, effective_rows from osism.utils.inventory import get_hosts_from_inventory, get_inventory_path +from osism.utils.render import list_environments class VersionsManager(Command): @@ -124,6 +127,35 @@ def get_parser(self, prog_name): type=str, help="Name of a variable to show", ) + environments = list_environments() + available = ( + ", ".join(environments) + if environments + else f"(none found under {settings.ENVIRONMENTS_DIRECTORY})" + ) + parser.add_argument( + "--environment", + type=str, + help="Render with this environment only. Available: " + available, + ) + parser.add_argument( + "--raw", + default=False, + help="Show values as defined, without rendering templates", + action="store_true", + ) + parser.add_argument( + "--show-secrets", + default=False, + help="Show values that are secrets or derived from secrets", + action="store_true", + ) + parser.add_argument( + "--format", + choices=["table", "value", "json"], + default="table", + help="Output format (default: table)", + ) return parser def take_action(self, parsed_args): @@ -135,15 +167,70 @@ def take_action(self, parsed_args): ) try: result = subprocess.check_output( - f"ansible-inventory -i {inventory_path} --host {host}", - shell=True, + ["ansible-inventory", "-i", inventory_path, "--host", host], stderr=subprocess.DEVNULL, ) except subprocess.CalledProcessError: logger.error(f"Host {host} not found in inventory.") return 1 - data = json.loads(result) + raw_hostvars = json.loads(result) + + if parsed_args.raw: + return self._take_raw(parsed_args, host, variable, raw_hostvars) + + try: + vault_password = utils.get_ansible_vault_password() + except Exception as exc: # pylint: disable=broad-except + logger.error( + f"Cannot render: vault password unavailable ({type(exc).__name__}); " + "use --raw to see values as defined." + ) + return 1 + + try: + all_raw_hostvars = json.loads( + subprocess.check_output( + ["ansible-inventory", "-i", inventory_path, "--list"], + stderr=subprocess.DEVNULL, + ) + )["_meta"]["hostvars"] + except (subprocess.CalledProcessError, ValueError, KeyError): + logger.error("Cannot render: the inventory could not be listed.") + return 1 + + facts = fact_cache.get_host_facts(utils.redis, host) + + try: + rows = effective_rows( + host, + variable, + parsed_args.environment, + parsed_args.show_secrets, + inventory_path=inventory_path, + vault_password=vault_password, + facts=facts, + raw_hostvars=raw_hostvars, + all_raw_hostvars=all_raw_hostvars, + ) + except HostvarsError as exc: + logger.error(str(exc)) + return 1 + + return self._output(parsed_args, host, variable, rows) + + def _take_raw(self, parsed_args, host, variable, data): + if parsed_args.format != "table": + if variable and variable not in data: + rows = [] + else: + names = [variable] if variable else list(data) + rows = [ + Row(host, name, None, data[name], False, [], False) + for name in names + ] + return self._output(parsed_args, host, variable, rows) + table = [] if variable: @@ -164,6 +251,74 @@ def take_action(self, parsed_args): return + def _output(self, parsed_args, host, variable, rows): + fmt = parsed_args.format + + if fmt == "json": + print( + json.dumps( + [ + { + "host": r.host, + "variable": r.variable, + "environment": r.environment, + "value": r.value, + "masked": r.masked, + "notes": r.notes, + } + for r in rows + ], + default=str, + ) + ) + return 1 if variable and any(r.failed for r in rows) else None + + if fmt == "value": + if not variable: + logger.error("--format value requires a variable name.") + return 1 + if not rows: + return None + if len(rows) > 1: + names = ", ".join(r.environment or "default" for r in rows) + logger.error( + f"ambiguous: environments differ ({names}); pass --environment" + ) + return 1 + row = rows[0] + if row.masked: + logger.error( + f"value is masked ({'; '.join(row.notes)}); pass --show-secrets" + ) + return 1 + if row.failed: + for note in row.notes: + print(note, file=sys.stderr) + return 1 + print(row.value if isinstance(row.value, str) else json.dumps(row.value)) + return None + + if not rows: + if variable: + logger.error(f"Variable {variable} not found in inventory for {host}.") + return None + + table = [] + for r in rows: + label = f"{r.variable} [{r.environment}]" if r.environment else r.variable + value = ( + "***" + if r.masked + else pprint.pformat(r.value, indent=2, width=60, compact=True) + ) + table.append([r.host, label, value, "\n".join(r.notes)]) + print( + tabulate( + table, headers=["Host", "Variable", "Value", "Notes"], tablefmt="grid" + ) + ) + return 1 if variable and any(r.failed for r in rows) else None + class Facts(Command): def get_parser(self, prog_name): diff --git a/tests/unit/commands/test_get.py b/tests/unit/commands/test_get.py index e57e5725a..f13059214 100644 --- a/tests/unit/commands/test_get.py +++ b/tests/unit/commands/test_get.py @@ -19,9 +19,11 @@ from unittest.mock import MagicMock, call, patch import docker +from tabulate import tabulate from osism import utils from osism.commands import get +from osism.utils.hostvars import Row def _make(cls): @@ -70,7 +72,7 @@ def test_hosts_returns_success_for_empty_inventory(): def test_hostvars_returns_nonzero_when_inventory_query_fails(): cmd = _make(get.Hostvars) - parsed_args = cmd.get_parser("test").parse_args(["somehost"]) + parsed_args = cmd.get_parser("test").parse_args(["somehost", "--raw"]) with patch( "osism.commands.get.get_inventory_path", @@ -86,7 +88,7 @@ def test_hostvars_returns_nonzero_when_inventory_query_fails(): def test_hostvars_returns_success_when_variable_absent_from_result(): cmd = _make(get.Hostvars) - parsed_args = cmd.get_parser("test").parse_args(["somehost", "missingvar"]) + parsed_args = cmd.get_parser("test").parse_args(["somehost", "missingvar", "--raw"]) with patch( "osism.commands.get.get_inventory_path", @@ -102,7 +104,7 @@ def test_hostvars_returns_success_when_variable_absent_from_result(): def test_hostvars_prints_requested_variable(capsys): cmd = _make(get.Hostvars) - parsed_args = cmd.get_parser("test").parse_args(["somehost", "myvar"]) + parsed_args = cmd.get_parser("test").parse_args(["somehost", "myvar", "--raw"]) with patch( "osism.commands.get.get_inventory_path", @@ -123,7 +125,7 @@ def test_hostvars_prints_requested_variable(capsys): def test_hostvars_lists_all_variables_without_variable_argument(capsys): cmd = _make(get.Hostvars) - parsed_args = cmd.get_parser("test").parse_args(["somehost"]) + parsed_args = cmd.get_parser("test").parse_args(["somehost", "--raw"]) with patch( "osism.commands.get.get_inventory_path", @@ -525,3 +527,191 @@ def test_mariadb_backup_host_fails_on_timeout(loguru_logs): assert result == 1 assert any("Timeout" in r["message"] for r in loguru_logs) mock_run.delay.return_value.forget.assert_called_once_with() + + +# --- Hostvars rendered path --- + + +def _hv(mocker, rows=None, inv_ok=True, vault_ok=True): + mocker.patch.object(get, "list_environments", return_value=["ceph", "kolla"]) + mocker.patch.object(get, "get_inventory_path", return_value="/inv/hosts.yml") + + def fake_check_output(cmd, **kw): + if not inv_ok: + raise subprocess.CalledProcessError(5, cmd) + return b'{"_meta": {"hostvars": {}}}' if "--list" in cmd else b"{}" + + mocker.patch.object(get.subprocess, "check_output", side_effect=fake_check_output) + if vault_ok: + mocker.patch.object(get.utils, "get_ansible_vault_password", return_value="pw") + else: + mocker.patch.object( + get.utils, "get_ansible_vault_password", side_effect=ValueError("k") + ) + mocker.patch.dict( + vars(utils), {"redis": mocker.Mock(get=mocker.Mock(return_value=None))} + ) + return mocker.patch.object(get, "effective_rows", return_value=rows or []) + + +def _run(cls_args): + cmd = _make(get.Hostvars) + parser = cmd.get_parser("dump inventory") + return cmd.take_action(parser.parse_args(cls_args)) + + +def test_hostvars_rendered_table_has_notes_column(mocker, capsys): + note = "fallback: n undefined here, a role may define it" + _hv(mocker, [Row("h", "a", None, "x", False, [note], False)]) + assert not _run(["h", "a"]) + out = capsys.readouterr().out + assert "Notes" in out and "fallback: n undefined" in out and "'x'" in out + + +def test_hostvars_render_reads_facts_in_the_new_cache_schema(mocker): + effective_rows = _hv(mocker, [Row("h", "a", None, "x", False, [], False)]) + entry = json.dumps({"__payload__": json.dumps({"ansible_hostname": "h"})}) + store = {"ansible_factss1_h": entry} + mocker.patch.dict( + vars(utils), {"redis": mocker.Mock(get=mocker.Mock(side_effect=store.get))} + ) + assert not _run(["h", "a"]) + assert effective_rows.call_args.kwargs["facts"] == {"ansible_hostname": "h"} + + +def test_hostvars_environment_row_label(mocker, capsys): + _hv( + mocker, + [ + Row("h", "a", None, "g", False, [], False), + Row("h", "a", "kolla", "k", False, [], False), + ], + ) + _run(["h", "a"]) + assert "a [kolla]" in capsys.readouterr().out + + +def test_hostvars_value_format_ambiguous_exits_1(mocker, capsys): + _hv( + mocker, + [ + Row("h", "a", None, "g", False, [], False), + Row("h", "a", "kolla", "k", False, [], False), + ], + ) + assert _run(["h", "a", "--format", "value"]) == 1 + + +def test_hostvars_value_format_masked_exits_1(mocker): + _hv(mocker, [Row("h", "a", None, "***", True, ["masked: derived from p"], False)]) + assert _run(["h", "a", "--format", "value"]) == 1 + + +def test_hostvars_value_format_prints_bare(mocker, capsys): + _hv(mocker, [Row("h", "a", None, "x", False, [], False)]) + assert not _run(["h", "a", "--format", "value"]) + assert capsys.readouterr().out == "x\n" + + +def test_hostvars_json_format(mocker, capsys): + _hv(mocker, [Row("h", "a", "kolla", "k", False, [], False)]) + _run(["h", "a", "--format", "json"]) + assert json.loads(capsys.readouterr().out) == [ + { + "host": "h", + "variable": "a", + "environment": "kolla", + "value": "k", + "masked": False, + "notes": [], + } + ] + + +def test_hostvars_absent_variable_exits_0(mocker, capsys): + _hv(mocker, []) + assert not _run(["h", "nope"]) + assert not _run(["h", "nope", "--format", "value"]) + capsys.readouterr() + assert not _run(["h", "nope", "--format", "json"]) + assert json.loads(capsys.readouterr().out) == [] + + +def test_hostvars_failed_single_variable_exits_1(mocker): + _hv(mocker, [Row("h", "a", None, None, False, ["render failed: x"], True)]) + assert _run(["h", "a"]) == 1 + + +def test_hostvars_failed_row_in_full_dump_exits_0(mocker, capsys): + _hv(mocker, [Row("h", "a", None, None, False, ["render failed: x"], True)]) + assert not _run(["h"]) + assert "render failed: x" in capsys.readouterr().out + + +def test_hostvars_vault_unavailable_exits_1_without_detail(mocker, capsys): + _hv(mocker, vault_ok=False) + assert _run(["h", "a"]) == 1 + out = capsys.readouterr() + assert "k)" not in out.out + out.err + + +def test_hostvars_unknown_host_exits_1(mocker): + _hv(mocker, inv_ok=False) + assert _run(["h", "a"]) == 1 + + +def test_hostvars_unknown_environment_exits_1(mocker): + m = _hv(mocker) + m.side_effect = get.HostvarsError( + "unknown environment nope; available: ceph, kolla" + ) + assert _run(["h", "a", "--environment", "nope"]) == 1 + + +def test_hostvars_help_lists_environments(mocker): + mocker.patch.object(get, "list_environments", return_value=["ceph", "kolla"]) + parser = _make(get.Hostvars).get_parser("dump inventory") + assert "Available: ceph, kolla" in " ".join(parser.format_help().split()) + + +def test_hostvars_raw_table_is_unchanged(mocker, capsys): + data = {"a": "{{ b }}", "b": "x"} + mocker.patch.object(get, "get_inventory_path", return_value="/inv/hosts.yml") + mocker.patch.object( + get.subprocess, "check_output", return_value=json.dumps(data).encode() + ) + assert not _run(["h", "--raw"]) + expected = tabulate( + [ + ["h", "a", pprint.pformat("{{ b }}", indent=2, width=60, compact=True)], + ["h", "b", pprint.pformat("x", indent=2, width=60, compact=True)], + ], + headers=["Host", "Variable", "Value"], + tablefmt="grid", + ) + assert capsys.readouterr().out == expected + "\n" + + +def test_hostvars_raw_uses_argv_list(mocker): + mocker.patch.object(get, "get_inventory_path", return_value="/inv/hosts.yml") + spy = mocker.patch.object(get.subprocess, "check_output", return_value=b"{}") + _run(["node;x", "--raw"]) + cmd = spy.call_args[0][0] + assert isinstance(cmd, list) and "node;x" in cmd + assert spy.call_args.kwargs.get("shell") is not True + + +def test_hostvars_raw_json_format(mocker, capsys): + mocker.patch.object(get, "get_inventory_path", return_value="/inv/hosts.yml") + mocker.patch.object(get.subprocess, "check_output", return_value=b'{"a": 1}') + _run(["h", "a", "--raw", "--format", "json"]) + assert json.loads(capsys.readouterr().out) == [ + { + "host": "h", + "variable": "a", + "environment": None, + "value": 1, + "masked": False, + "notes": [], + } + ] From f0a15c2b6b9a40463d37f848a425122461dde59b Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:52:48 +0200 Subject: [PATCH 07/16] Treat unmodelled vars/hostvars as unanalysable The dependency walker ignored the names vars and hostvars unless they were the base of a constant subscript or attribute. Other uses reached secrets without the value being masked: lookup('ansible.builtin.vars', ...), hostvars[h].get(...), map('extract', vars|hostvars, ...) and an alias such as {% set v = vars %} all rendered a secret, or its base64, in the clear. vars and hostvars are now modelled only as the base of a subscript or attribute, of .get(key), of lookup/query('vars', ...) under the names vars, ansible.builtin.vars and ansible.legacy.vars, and of map('extract', ...). With hostvars, the first component of the extract key is a cross-host reference; with vars, the constant items of the mapped list are the referenced names. Any other use (the bare name, an alias, a mapping method such as vars.items(), hostvars[h] on its own, *args) can reach every variable, so the value is masked as unanalysable. An integration test renders the leaking shapes with real Ansible on a two-host inventory and asserts that no plaintext or base64 secret reaches the rows. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/template_deps.py | 163 +++++++++++++++++++--- tests/integration/test_hostvars_render.py | 78 +++++++++++ tests/unit/utils/test_hostvars.py | 57 ++++++++ tests/unit/utils/test_template_deps.py | 81 +++++++++++ 4 files changed, 363 insertions(+), 16 deletions(-) diff --git a/osism/utils/template_deps.py b/osism/utils/template_deps.py index d77a586cc..29030f0bc 100644 --- a/osism/utils/template_deps.py +++ b/osism/utils/template_deps.py @@ -11,8 +11,15 @@ Names bound inside the template (loop targets, ``{% set %}``) are tracked per scope and in statement order. A later binding never hides an earlier reference. + +``vars`` and ``hostvars`` are modelled only as the base of these accesses: +a subscript or attribute (``vars['x']``, ``hostvars[h].x``), ``.get(x)``, +``lookup('vars', x)`` and ``map('extract', hostvars, x)``. Any other use +(the bare name, an alias, ``vars.items()``, ``hostvars[h]`` on its own) +can reach every variable, so it makes the value unanalysable. """ +import collections from dataclasses import dataclass, field from typing import Any @@ -22,8 +29,6 @@ _ENV = Environment() _GLOBALS = frozenset( { - "vars", - "hostvars", "groups", "group_names", "inventory_hostname", @@ -46,6 +51,15 @@ } ) _LOOKUPS = frozenset({"lookup", "query", "q"}) +_VARS_LOOKUPS = frozenset({"vars", "ansible.builtin.vars", "ansible.legacy.vars"}) +_VARIABLE_MAPS = frozenset({"vars", "hostvars"}) +# Jinja's getattr prefers a Python attribute over a key, so vars.items is +# the method, not a variable named "items". HostVars adds raw_get. +_MAPPING_ATTRS = frozenset( + a + for a in dir(dict) + dir(collections.ChainMap) + ["raw_get"] + if not a.startswith("_") +) # Statements whose scoping this walker does not model; their presence makes # the value unanalysable (masked), which is the safe direction. _UNMODELLED = (nodes.Macro, nodes.CallBlock, nodes.With, nodes.FilterBlock) @@ -125,11 +139,47 @@ def _hostvars_host(base: nodes.Node): """For hostvars[H] / hostvars.H return (True, cross_host); else (False, None).""" if isinstance(base, nodes.Getitem) and _is_name(base.node, "hostvars"): return True, not _is_name(base.arg, "inventory_hostname") - if isinstance(base, nodes.Getattr) and _is_name(base.node, "hostvars"): + if ( + isinstance(base, nodes.Getattr) + and _is_name(base.node, "hostvars") + and not _is_mapping_attr(base.attr) + ): return True, True return False, None +def _is_mapping_attr(attr: str) -> bool: + return attr.startswith("_") or attr in _MAPPING_ATTRS + + +def _variable_map(base: nodes.Node, acc: _Acc, bound: frozenset): + """If base is vars or hostvars[H]/hostvars.H, walk H and return cross_host. + + Returns None when base is not one of them. + """ + if _is_name(base, "vars") and "vars" not in bound: + return False + is_hostvars, cross = _hostvars_host(base) + if not is_hostvars or "hostvars" in bound: + return None + if isinstance(base, nodes.Getitem): + _walk(base.arg, acc, bound) + return bool(cross) + + +def _walk_call_rest(node: nodes.Call, args: list, acc: _Acc, bound) -> None: + if node.dyn_args is not None or node.dyn_kwargs is not None: + # *args/**kwargs may carry further variable names. + acc.unanalysable = True + for arg in args: + _walk(arg, acc, bound) + for kwarg in node.kwargs: + _walk(kwarg, acc, bound) + for dyn in (node.dyn_args, node.dyn_kwargs): + if dyn is not None: + _walk(dyn, acc, bound) + + def _is_name(node: nodes.Node, name: str) -> bool: return isinstance(node, nodes.Name) and node.name == name @@ -154,29 +204,110 @@ def _walk(node: nodes.Node, acc: _Acc, bound: frozenset) -> None: _walk_body(node.else_, acc, bound) return if isinstance(node, (nodes.Getitem, nodes.Getattr)): - base = node.node - is_hostvars, cross = _hostvars_host(base) - if _is_name(base, "vars") or is_hostvars: - if is_hostvars and isinstance(base, nodes.Getitem): - _walk(base.arg, acc, bound) + cross = _variable_map(node.node, acc, bound) + if cross is not None: if isinstance(node, nodes.Getattr): - (acc.cross if cross else acc.names).add(node.attr) + if _is_mapping_attr(node.attr): + acc.unanalysable = True + else: + (acc.cross if cross else acc.names).add(node.attr) else: - _target(node.arg, acc, bool(cross), bound) - return - if isinstance(node, nodes.Call) and isinstance(node.node, nodes.Name): - if node.node.name in _LOOKUPS and node.args and _const(node.args[0]) == "vars": - for arg in node.args[1:]: - _target(arg, acc, False, bound) + _target(node.arg, acc, cross, bound) return + if isinstance(node, nodes.Call) and _walk_call(node, acc, bound): + return + if isinstance(node, nodes.Filter) and _walk_map_extract(node, acc, bound): + return if isinstance(node, nodes.Name) and node.ctx == "load": - if node.name not in _GLOBALS and node.name not in bound: + if node.name in bound: + return + if node.name in _VARIABLE_MAPS: + # Not the base of a modelled access: it can reach anything. + acc.unanalysable = True + elif node.name not in _GLOBALS: acc.names.add(node.name) return for child in node.iter_child_nodes(): _walk(child, acc, bound) +def _walk_call(node: nodes.Call, acc: _Acc, bound: frozenset) -> bool: + """lookup('vars', ...) and .get(key, ...).""" + callee = node.node + if ( + isinstance(callee, nodes.Name) + and callee.name in _LOOKUPS + and callee.name not in bound + and node.args + and _const(node.args[0]) in _VARS_LOOKUPS + ): + for arg in node.args[1:]: + _target(arg, acc, False, bound) + _walk_call_rest(node, [], acc, bound) + return True + if isinstance(callee, nodes.Getattr) and callee.attr == "get" and node.args: + cross = _variable_map(callee.node, acc, bound) + if cross is None: + return False + _target(node.args[0], acc, cross, bound) + _walk_call_rest(node, node.args[1:], acc, bound) + return True + return False + + +def _walk_map_extract(node: nodes.Filter, acc: _Acc, bound: frozenset) -> bool: + """seq | map('extract', hostvars, key) and seq | map('extract', vars). + + extract(item, container, morekeys) is container[item][morekeys...]: + with hostvars the items are hosts and the first key component is the + variable; with vars the items are the variables. + """ + args = node.args + if not ( + node.name == "map" + and len(args) >= 2 + and _const(args[0]) == "extract" + and isinstance(args[1], nodes.Name) + and args[1].name in _VARIABLE_MAPS + and args[1].name not in bound + ): + return False + if args[1].name == "hostvars": + if node.node is not None: + _walk(node.node, acc, bound) + key = _first_key(args[2]) if len(args) >= 3 else None + if key is None: + acc.unanalysable = True + else: + acc.cross.add(key) + else: + items = node.node + if isinstance(items, (nodes.List, nodes.Tuple)) and all( + isinstance(_const(i), str) for i in items.items + ): + acc.names.update(_const(i) for i in items.items) + else: + acc.unanalysable = True + if items is not None: + _walk(items, acc, bound) + for arg in args[2:]: + _walk(arg, acc, bound) + for kwarg in node.kwargs: + _walk(kwarg, acc, bound) + if node.dyn_args is not None or node.dyn_kwargs is not None: + acc.unanalysable = True + return True + + +def _first_key(key: nodes.Node) -> str | None: + if isinstance(key, (nodes.List, nodes.Tuple)): + if not key.items: + return None + key = key.items[0] + value = _const(key) + return value if isinstance(value, str) else None + + def _const(node: nodes.Node) -> Any: return node.value if isinstance(node, nodes.Const) else None diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py index e2c442176..2432cf8e4 100644 --- a/tests/integration/test_hostvars_render.py +++ b/tests/integration/test_hostvars_render.py @@ -3,12 +3,16 @@ """render_batch end to end against real Ansible; the plugin imports osism.""" +import base64 +import json import os import shutil import subprocess import pytest +import yaml +from osism.utils.hostvars import effective_rows from osism.utils.render import ( build_stack, environment_local_names, @@ -104,3 +108,77 @@ def test_environment_local_names_reads_inline_vault(setup): "inline_pw", "svc_url", } + + +def _inventory_hostvars(inv, host): + def run(*args): + return json.loads( + subprocess.run( + ["ansible-inventory", "-i", inv, *args], + check=True, + capture_output=True, + text=True, + stdin=subprocess.DEVNULL, + ).stdout + ) + + return run("--host", host), run("--list")["_meta"]["hostvars"] + + +@pytest.fixture +def two_hosts(tmp_path): + """node1 reads a secret through shapes the walker once missed.""" + inv = tmp_path / "hosts.yml" + inv.write_text( + yaml.safe_dump( + { + "all": { + "hosts": { + "node1": { + "ansible_host": "192.0.2.10", + "enc_lookup": "{{ lookup('ansible.builtin.vars', " + "'redis_master_password') | b64encode }}", + "enc_get": "{{ hostvars[inventory_hostname]" + ".get('redis_master_password') | b64encode }}", + "bmc_list": "{{ groups['all'] | map('extract', " + "hostvars, 'ipmi_password') | select('defined') | list }}", + "fb": "{{ nope_undefined | default('fallback-value') }}", + }, + "node2": { + "ansible_host": "192.0.2.11", + "ipmi_password": "Node2PlainIpmiPw", + }, + } + } + } + ) + ) + root = tmp_path / "environments" + root.mkdir() + (root / "configuration.yml").write_text("plain: 1\n") + (root / "secrets.yml").write_text("redis_master_password: Redis-Secret-42\n") + raw, all_raw = _inventory_hostvars(str(inv), "node1") + return dict( + inventory_path=str(inv), + vault_password="probe-vault-pw", + facts=None, + raw_hostvars=raw, + all_raw_hostvars=all_raw, + root=str(root), + ) + + +@pytest.mark.parametrize("name", ["enc_lookup", "enc_get", "bmc_list"]) +def test_real_render_masks_unmodelled_secret_shapes(two_hosts, name): + rows = effective_rows("node1", name, None, False, **two_hosts) + assert len(rows) == 1 and rows[0].masked and rows[0].value == "***" + leaked = ( + "Redis-Secret-42", + base64.b64encode(b"Redis-Secret-42").decode(), + "Node2PlainIpmiPw", + ) + assert not any(s in repr(rows) for s in leaked) + # The same run shows the value with --show-secrets: the mask is not a + # render failure in disguise. + shown = effective_rows("node1", name, None, True, **two_hosts) + assert any(s in repr(shown) for s in leaked) diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index 4e05e5257..9444d15f3 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -539,3 +539,60 @@ def test_cross_host_nested_vault_value_is_masked(world): )("cfg") assert rows[0].value == "***" and rows[0].masked assert rows[0].notes == ["masked: derived from ldap"] + + +# Final review C1: template shapes that reached a secret unmasked. + +_B64 = base64.b64encode(b"s3cr3t-value-123").decode() + + +@pytest.mark.parametrize( + "template", + [ + "{{ lookup('ansible.builtin.vars', 'redis_master_password') | b64encode }}", + "{{ hostvars[inventory_hostname].get('redis_master_password') | b64encode }}", + "{{ ['redis_master_password'] | map('extract', vars) | first | b64encode }}", + "{% set v = vars %}{{ v.redis_master_password | b64encode }}", + ], +) +def test_unmodelled_secret_shapes_are_masked(world, template): + rows = world( + {"enc": template}, + {None: {"enc": _B64, "redis_master_password": "s3cr3t-value-123"}}, + secrets_names={"redis_master_password"}, + )("enc") + assert rows[0].value == "***" and rows[0].masked + assert _B64 not in repr(rows) + + +def test_cross_host_map_extract_plaintext_is_masked(world): + raw = { + "bmc_list": "{{ groups['all'] | map('extract', hostvars, 'ipmi_password') " + "| select('defined') | list }}" + } + all_raw = {"node1": raw, "node2": {"ipmi_password": "Node2PlainIpmiPw"}} + rows = world(raw, {None: {"bmc_list": ["Node2PlainIpmiPw"]}}, all_raw=all_raw)( + "bmc_list" + ) + assert rows[0].value == "***" and rows[0].notes == [ + "masked: derived from ipmi_password" + ] + assert "Node2PlainIpmiPw" not in repr(rows) + + +def test_benign_map_extract_hostvars_is_shown(world): + raw = { + "names": "{{ groups['all'] | map('extract', hostvars, " + "['ansible_facts', 'hostname']) | list }}" + } + all_raw = {"node1": raw, "node2": {}} + rows = world(raw, {None: {"names": ["node1", "node2"]}}, all_raw=all_raw)("names") + assert rows[0].value == ["node1", "node2"] and not rows[0].masked + + +@pytest.mark.parametrize("template", ["{{ vars }}", "{{ hostvars }}"]) +def test_bare_variable_maps_are_masked(world, template): + rows = world({"all": template}, {None: {"all": {"a": "1"}}})("all") + assert rows[0].masked and rows[0].notes == [ + "masked: could not analyse dependencies" + ] diff --git a/tests/unit/utils/test_template_deps.py b/tests/unit/utils/test_template_deps.py index 2e9665c3e..7b57800f4 100644 --- a/tests/unit/utils/test_template_deps.py +++ b/tests/unit/utils/test_template_deps.py @@ -116,3 +116,84 @@ def test_syntax_error_is_unanalysable(): def test_non_template_string_has_no_refs(): r = references("plain") assert r.names == frozenset() and not r.dynamic_keys + + +# Final review C1: shapes that reached a secret without being modelled. + + +def test_fqcn_vars_lookup_is_a_reference(): + for plugin in ("vars", "ansible.builtin.vars", "ansible.legacy.vars"): + r = references(f"{{{{ lookup('{plugin}', 'redis_master_password') }}}}") + assert r.names == {"redis_master_password"} and not r.unanalysable + r = references(f"{{{{ query('{plugin}', n) | first }}}}") + assert [k.expression for k in r.dynamic_keys] == ["n"] + + +def test_get_on_vars_and_hostvars_is_a_subscript(): + r = references( + "{{ hostvars[inventory_hostname].get('redis_master_password') | b64encode }}" + ) + assert r.names == {"redis_master_password"} and not r.unanalysable + assert references("{{ vars.get('a', 'x') }}").names == {"a"} + r = references("{{ hostvars[h].get('endpoint') }}") + assert r.cross_host_names == {"endpoint"} and r.names == {"h"} + assert references("{{ hostvars.node2.get('endpoint') }}").cross_host_names == { + "endpoint" + } + r = references("{{ vars.get(n) }}") + assert [k.expression for k in r.dynamic_keys] == ["n"] and "get" not in r.names + + +def test_mapping_methods_are_unanalysable(): + for expr in ( + "{{ vars.get }}", + "{{ vars.values() | list }}", + "{{ vars.items() | list }}", + "{{ hostvars[h].values() | list }}", + "{{ hostvars.node2.keys() | list }}", + "{{ hostvars.raw_get('node2') }}", + "{{ hostvars[h]._vars }}", + ): + assert references(expr).unanalysable, expr + + +def test_map_extract_vars_is_modelled_by_its_constant_items(): + r = references( + "{{ ['redis_master_password'] | map('extract', vars) | first | b64encode }}" + ) + assert r.names == {"redis_master_password"} and not r.unanalysable + assert references("{{ names | map('extract', vars) | list }}").unanalysable + + +def test_map_extract_hostvars_first_key_is_cross_host(): + r = references( + "{{ groups['all'] | map('extract', hostvars, 'ipmi_password') " + "| select('defined') | list }}" + ) + assert r.cross_host_names == {"ipmi_password"} and not r.unanalysable + r = references( + "{{ groups['x'] | map('extract', hostvars, ['ansible_facts', 'hostname']) " + "| list }}" + ) + assert r.cross_host_names == {"ansible_facts"} and not r.unanalysable + assert references("{{ groups['x'] | map('extract', hostvars, k) }}").unanalysable + assert references("{{ groups['x'] | map('extract', hostvars) }}").unanalysable + + +def test_alias_of_vars_is_unanalysable(): + assert references( + "{% set v = vars %}{{ v.redis_master_password | b64encode }}" + ).unanalysable + + +def test_bare_vars_and_hostvars_are_unanalysable(): + assert references("{{ vars }}").unanalysable + assert references("{{ hostvars }}").unanalysable + assert references("{{ hostvars[inventory_hostname] }}").unanalysable + assert references("{{ hostvars | dict2items }}").unanalysable + assert references("{{ 'x' | extract(vars) }}").unanalysable + + +def test_star_args_to_a_vars_lookup_are_unanalysable(): + assert references("{{ lookup('vars', *names) }}").unanalysable + assert references("{{ vars.get(*names) }}").unanalysable From 55f16ad88bc1a09ddb9ce94c3cee6827bf8f34e7 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:53:25 +0200 Subject: [PATCH 08/16] Keep the API's inline-vault masking shape is_vault_value treats an inline vault value, {"__ansible_vault": ...}, as a vault value. mask_structure used it, so the API's inventory masking changed its output from {'x': {'__ansible_vault': '***'}} to {'x': '***'}. The API must keep its output. mask_structure gets a structural_vault parameter. Its default, False, is the API's old rule: a vault value is a string with the vault header, so an inline vault dict keeps its shape and only its ciphertext is masked. structural_vault=True applies is_vault_value and masks the whole inline vault dict. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/secrets.py | 32 +++++++++++++++++++++++--------- tests/unit/utils/test_secrets.py | 12 ++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/osism/utils/secrets.py b/osism/utils/secrets.py index 6728cd4d7..c8b28822f 100644 --- a/osism/utils/secrets.py +++ b/osism/utils/secrets.py @@ -28,31 +28,45 @@ def is_vault_value(value: Any) -> bool: ``!vault`` value comes out of ``ansible-inventory`` as ``{"__ansible_vault": ""}``. """ - if isinstance(value, str): - return value.strip().startswith(VAULT_PREFIX) + if _is_vault_string(value): + return True if isinstance(value, dict) and set(value) == {"__ansible_vault"}: return True return False -def mask_structure(data: dict, mask: str = "***") -> dict: - """Mask by key name and by vault value, recursively. The API's rule.""" +def mask_structure( + data: dict, mask: str = "***", structural_vault: bool = False +) -> dict: + """Mask by key name and by vault value, recursively. + + The default is the API's rule: a vault value is a string with the + vault header, so an inline vault dict keeps its shape and only its + ciphertext is masked. With structural_vault, the vault rule is + is_vault_value and the whole inline vault dict becomes the mask. + """ masked: dict = {} for key, value in data.items(): - masked[key] = mask if is_secret_key(key) else _mask_value(value, mask) + masked[key] = ( + mask if is_secret_key(key) else _mask_value(value, mask, structural_vault) + ) return masked -def _mask_value(value: Any, mask: str) -> Any: - if is_vault_value(value): +def _mask_value(value: Any, mask: str, structural_vault: bool) -> Any: + if is_vault_value(value) if structural_vault else _is_vault_string(value): return mask if isinstance(value, dict): - return mask_structure(value, mask) + return mask_structure(value, mask, structural_vault) if isinstance(value, list): - return [_mask_value(item, mask) for item in value] + return [_mask_value(item, mask, structural_vault) for item in value] return value +def _is_vault_string(value: Any) -> bool: + return isinstance(value, str) and value.strip().startswith(VAULT_PREFIX) + + def replace_literals( text: str, secret_values: Iterable[str], mask: str = "***", min_length: int = 0 ) -> str: diff --git a/tests/unit/utils/test_secrets.py b/tests/unit/utils/test_secrets.py index 87f2e8ca0..2cac1a850 100644 --- a/tests/unit/utils/test_secrets.py +++ b/tests/unit/utils/test_secrets.py @@ -73,3 +73,15 @@ def test_replace_literals_deep_copies(): out = replace_literals_deep(obj, ["secret1"]) assert out == {"a": ["xx-***-yy", 3]} assert obj == {"a": ["xx-secret1-yy", 3]} + + +def test_mask_structure_keeps_api_inline_vault_shape(): + # The API masks by string prefix only (spec D6): an inline vault dict + # keeps its shape, its ciphertext string is masked. + data = {"x": {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n63"}} + assert mask_structure(data) == {"x": {"__ansible_vault": "***"}} + + +def test_mask_structure_structural_vault_masks_whole_value(): + data = {"x": {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n63"}} + assert mask_structure(data, structural_vault=True) == {"x": "***"} From 83f2cf92c386055f57c6948bebce0e316de83c2b Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:55:21 +0200 Subject: [PATCH 09/16] Emit fallback notes only under default filters A rendered value got a "fallback: undefined here" note for every undefined name in its dependency closure as soon as the string "default(" occurred anywhere in a raw value. Cached facts are passed to Ansible but were not counted as defined. So osism/defaults' internal_address, "{{ ansible_default_ipv4.address|default( ansible_all_ipv4_addresses[0]) }}", rendered from facts and still got two false fallback notes; the d alias was not recognised at all. The request now carries the queried host's fact names, which count as defined in the closure walk. The dependency walker records the names (and dynamic keys) referenced inside a default or d filter's base or argument, in nested dict and list values too. A closure reports "fallback", the undefined names among them, instead of the uses_default flag, and only those get a fallback note. An integration test covers an undefined name with a default on real Ansible. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/evaluate.py | 19 +++++--- osism/utils/hostvars.py | 1 + osism/utils/hostvars_rows.py | 21 ++++---- osism/utils/template_deps.py | 42 +++++++++++++--- tests/integration/test_hostvars_render.py | 10 ++++ tests/unit/utils/test_evaluate.py | 58 +++++++++++++++++++++-- tests/unit/utils/test_hostvars.py | 37 +++++++++++++-- tests/unit/utils/test_template_deps.py | 12 +++++ 8 files changed, 171 insertions(+), 29 deletions(-) diff --git a/osism/utils/evaluate.py b/osism/utils/evaluate.py index b8bbc01e8..0af474aaf 100644 --- a/osism/utils/evaluate.py +++ b/osism/utils/evaluate.py @@ -17,12 +17,17 @@ applied over the inventory raw_all -- name -> list of raw values across all hosts (and the stack value), for cross-host references + facts -- optional; names of the queried host's cached facts, which + count as defined Result: values -- name -> {"value": v} | {"error": str}, for names and secrets closures -- name -> {"names": [...], "unanalysable": bool, "undefined": [...], "secret_hits": [...], - "uses_default": bool} + "fallback": [...]} + + fallback lists the undefined names that occur inside a default/d + filter's base or argument, where the value falls back. """ from typing import Callable @@ -34,11 +39,12 @@ def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dict: raw, raw_all = request["raw"], request["raw_all"] + facts = set(request.get("facts") or ()) seen: set = set() names: set = set() undefined: set = set() + defaulted: set = set() unanalysable = False - uses_default = False work = [(name, "host")] while work: current, scope = work.pop() @@ -53,15 +59,14 @@ def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dic if current in raw: sources.append(raw[current]) if not sources: - if current != name: + if current != name and current not in facts: undefined.add(current) continue for value in sources: refs = references(value) if refs.unanalysable: unanalysable = True - if isinstance(value, str) and "default(" in value.replace(" ", ""): - uses_default = True + defaulted |= refs.defaulted for n in refs.names: work.append((n, scope)) for n in refs.cross_host_names: @@ -76,6 +81,8 @@ def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dic if "error" in result or not isinstance(result.get("value"), str): unanalysable = True continue + if key.defaulted: + defaulted.add(result["value"]) work.append((result["value"], "all" if key.cross_host else scope)) secrets = set(request["secrets"]) return { @@ -83,7 +90,7 @@ def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dic "unanalysable": unanalysable, "undefined": sorted(undefined), "secret_hits": sorted(names & secrets), - "uses_default": uses_default, + "fallback": sorted(undefined & defaulted), } diff --git a/osism/utils/hostvars.py b/osism/utils/hostvars.py index f61fc3875..34eb380e7 100644 --- a/osism/utils/hostvars.py +++ b/osism/utils/hostvars.py @@ -121,6 +121,7 @@ def _render(stack: Stack, names: list, ctx: _Ctx, merged=None) -> Rendered: "secrets": sorted(secrets), "raw": raw, "raw_all": _raw_all(ctx.all_raw_hostvars), + "facts": sorted(ctx.facts) if isinstance(ctx.facts, dict) else [], } result = ctx.renderer( ctx.host, request, ctx.inventory_path, stack, ctx.vault_password, ctx.facts diff --git a/osism/utils/hostvars_rows.py b/osism/utils/hostvars_rows.py index 62ec99624..2c28b278b 100644 --- a/osism/utils/hostvars_rows.py +++ b/osism/utils/hostvars_rows.py @@ -37,7 +37,7 @@ "unanalysable": True, "undefined": [], "secret_hits": [], - "uses_default": False, + "fallback": [], } @@ -159,16 +159,15 @@ def _row( value, rendered.secret_values, MASK, MIN_SECRET_LENGTH ) value, masked = cleaned, cleaned != value - if closure["uses_default"]: - # A dynamic key resolved to a value can land in `undefined`. - notes += [ - _clean( - f"fallback: {n} undefined here, a role may define it", - rendered, - show_secrets, - ) - for n in sorted(closure["undefined"]) - ] + # A dynamic key resolved to a value can land in `fallback`. + notes += [ + _clean( + f"fallback: {n} undefined here, a role may define it", + rendered, + show_secrets, + ) + for n in sorted(closure["fallback"]) + ] return Row(host, name, environment, value, masked, notes, False) diff --git a/osism/utils/template_deps.py b/osism/utils/template_deps.py index 29030f0bc..677478dbc 100644 --- a/osism/utils/template_deps.py +++ b/osism/utils/template_deps.py @@ -69,6 +69,8 @@ class DynamicKey: expression: str | None cross_host: bool + # Inside a default/d filter's base or argument. + defaulted: bool = False @dataclass(frozen=True) @@ -77,6 +79,12 @@ class Refs: cross_host_names: frozenset = field(default_factory=frozenset) dynamic_keys: tuple = () unanalysable: bool = False + # Referenced names (either scope) inside a default/d filter's base or + # argument: if undefined, the value falls back. + defaulted: frozenset = field(default_factory=frozenset) + + +_DEFAULT_FILTERS = frozenset({"default", "d"}) class _Acc: @@ -84,8 +92,20 @@ def __init__(self) -> None: self.names: set = set() self.cross: set = set() self.dynamic: list = [] + self.defaulted: set = set() + self.defaulting = 0 self.unanalysable = False + def add(self, name: str, cross: bool = False) -> None: + (self.cross if cross else self.names).add(name) + if self.defaulting: + self.defaulted.add(name) + + def add_dynamic(self, expression: str | None, cross: bool) -> None: + self.dynamic.append( + DynamicKey(expression, cross, defaulted=bool(self.defaulting)) + ) + def references(raw: Any) -> Refs: acc = _Acc() @@ -94,6 +114,7 @@ def references(raw: Any) -> Refs: names=frozenset(acc.names), cross_host_names=frozenset(acc.cross), dynamic_keys=tuple(acc.dynamic), + defaulted=frozenset(acc.defaulted), unanalysable=acc.unanalysable, ) @@ -210,7 +231,7 @@ def _walk(node: nodes.Node, acc: _Acc, bound: frozenset) -> None: if _is_mapping_attr(node.attr): acc.unanalysable = True else: - (acc.cross if cross else acc.names).add(node.attr) + acc.add(node.attr, cross) else: _target(node.arg, acc, cross, bound) return @@ -218,6 +239,14 @@ def _walk(node: nodes.Node, acc: _Acc, bound: frozenset) -> None: return if isinstance(node, nodes.Filter) and _walk_map_extract(node, acc, bound): return + if isinstance(node, nodes.Filter) and node.name in _DEFAULT_FILTERS: + acc.defaulting += 1 + try: + for child in node.iter_child_nodes(): + _walk(child, acc, bound) + finally: + acc.defaulting -= 1 + return if isinstance(node, nodes.Name) and node.ctx == "load": if node.name in bound: return @@ -225,7 +254,7 @@ def _walk(node: nodes.Node, acc: _Acc, bound: frozenset) -> None: # Not the base of a modelled access: it can reach anything. acc.unanalysable = True elif node.name not in _GLOBALS: - acc.names.add(node.name) + acc.add(node.name) return for child in node.iter_child_nodes(): _walk(child, acc, bound) @@ -279,13 +308,14 @@ def _walk_map_extract(node: nodes.Filter, acc: _Acc, bound: frozenset) -> bool: if key is None: acc.unanalysable = True else: - acc.cross.add(key) + acc.add(key, cross=True) else: items = node.node if isinstance(items, (nodes.List, nodes.Tuple)) and all( isinstance(_const(i), str) for i in items.items ): - acc.names.update(_const(i) for i in items.items) + for item in items.items: + acc.add(_const(item)) else: acc.unanalysable = True if items is not None: @@ -315,14 +345,14 @@ def _const(node: nodes.Node) -> Any: def _target(key: nodes.Node, acc: _Acc, cross: bool, bound: frozenset) -> None: value = _const(key) if isinstance(value, str): - (acc.cross if cross else acc.names).add(value) + acc.add(value, cross) return # A key that uses a template-bound name ({% set %}, a loop target) cannot # be resolved as a standalone expression: it would read the host's # variable of that name instead of the local binding. Unresolvable. uses_bound = bool(_target_names(key) & bound) expression = None if uses_bound else _unparse(key) - acc.dynamic.append(DynamicKey(expression=expression, cross_host=cross)) + acc.add_dynamic(expression, cross) _walk(key, acc, bound) diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py index 2432cf8e4..326741e18 100644 --- a/tests/integration/test_hostvars_render.py +++ b/tests/integration/test_hostvars_render.py @@ -182,3 +182,13 @@ def test_real_render_masks_unmodelled_secret_shapes(two_hosts, name): # render failure in disguise. shown = effective_rows("node1", name, None, True, **two_hosts) assert any(s in repr(shown) for s in leaked) + + +def test_real_render_reports_fallback(two_hosts): + rows = effective_rows("node1", "fb", None, False, **two_hosts) + assert [(r.value, r.notes) for r in rows] == [ + ( + "fallback-value", + ["fallback: nope_undefined undefined here, a role may define it"], + ) + ] diff --git a/tests/unit/utils/test_evaluate.py b/tests/unit/utils/test_evaluate.py index 33f23c7f5..bec813f12 100644 --- a/tests/unit/utils/test_evaluate.py +++ b/tests/unit/utils/test_evaluate.py @@ -15,13 +15,16 @@ def resolve(expr): return resolve -def _req(names, raw, secrets=(), raw_all=None): - return { +def _req(names, raw, secrets=(), raw_all=None, facts=None): + request = { "names": names, "secrets": list(secrets), "raw": raw, "raw_all": raw_all or {}, } + if facts is not None: + request["facts"] = facts + return request def test_static_closure_and_secret_hits(): @@ -104,4 +107,53 @@ def test_undefined_and_default_are_reported(): _resolver({"e": "fb"}), _req(["e"], {"e": "{{ nope | default('fb') }}"}) ) assert r["closures"]["e"]["undefined"] == ["nope"] - assert r["closures"]["e"]["uses_default"] is True + assert r["closures"]["e"]["fallback"] == ["nope"] + + +# Final review I2: a fallback note needs an undefined name under default/d. + + +def test_fact_names_count_as_defined(): + raw = { + "internal_address": "{{ ansible_default_ipv4.address" + "|default(ansible_all_ipv4_addresses[0]) }}" + } + r = evaluate_request( + _resolver({"internal_address": "192.0.2.10"}), + _req( + ["internal_address"], + raw, + facts=["ansible_all_ipv4_addresses", "ansible_default_ipv4"], + ), + ) + assert r["closures"]["internal_address"]["undefined"] == [] + assert r["closures"]["internal_address"]["fallback"] == [] + + +def test_d_alias_is_a_fallback(): + r = evaluate_request(_resolver({}), _req(["e"], {"e": "{{ nope | d('fb') }}"})) + assert r["closures"]["e"]["fallback"] == ["nope"] + + +def test_undefined_outside_default_is_not_a_fallback(): + r = evaluate_request( + _resolver({}), + _req(["e"], {"e": "{{ nope }}-{{ other | default('x') }}"}), + ) + assert r["closures"]["e"]["undefined"] == ["nope", "other"] + assert r["closures"]["e"]["fallback"] == ["other"] + + +def test_default_argument_and_nested_values_are_fallbacks(): + r = evaluate_request( + _resolver({}), + _req( + ["e", "a"], + { + "e": {"k": ["{{ x | default(y) }}"]}, + "a": "{{ e }}", + }, + ), + ) + assert r["closures"]["e"]["fallback"] == ["x", "y"] + assert r["closures"]["a"]["fallback"] == ["x", "y"] diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index 9444d15f3..6cd456c28 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -68,7 +68,7 @@ def resolve(expr): return evaluate_request(resolve, request) - def rows(variable=None, environment=None, show=False): + def rows(variable=None, environment=None, show=False, facts=None): return hv.effective_rows( "node1", variable, @@ -76,7 +76,7 @@ def rows(variable=None, environment=None, show=False): show, inventory_path="/inv", vault_password="pw", - facts=None, + facts=facts, raw_hostvars=raw, all_raw_hostvars=all_raw or {"node1": raw}, renderer=renderer, @@ -311,7 +311,7 @@ def renderer(host, request, *a, **k): "unanalysable": False, "undefined": ["q"], "secret_hits": [], - "uses_default": False, + "fallback": [], } }, } @@ -596,3 +596,34 @@ def test_bare_variable_maps_are_masked(world, template): assert rows[0].masked and rows[0].notes == [ "masked: could not analyse dependencies" ] + + +# Final review I2: no false fallback notes. + + +def test_fact_backed_default_has_no_fallback_note(world): + raw = { + "internal_address": "{{ ansible_default_ipv4.address" + "|default(ansible_all_ipv4_addresses[0]) }}" + } + facts = { + "ansible_default_ipv4": {"address": "192.0.2.10"}, + "ansible_all_ipv4_addresses": ["192.0.2.10"], + } + rows = world(raw, {None: {"internal_address": "192.0.2.10"}})( + "internal_address", facts=facts + ) + assert rows[0].value == "192.0.2.10" and rows[0].notes == [] + + +def test_d_alias_fallback_note(world): + rows = world({"e": "{{ nope | d('fb') }}"}, {None: {"e": "fb"}})("e") + assert rows[0].notes == ["fallback: nope undefined here, a role may define it"] + + +def test_undefined_outside_default_gets_no_fallback_note(world): + rows = world( + {"e": "{{ nope if false else 'x' }}{{ other | default('y') }}"}, + {None: {"e": "xy"}}, + )("e") + assert rows[0].notes == ["fallback: other undefined here, a role may define it"] diff --git a/tests/unit/utils/test_template_deps.py b/tests/unit/utils/test_template_deps.py index 7b57800f4..fdc54dfbe 100644 --- a/tests/unit/utils/test_template_deps.py +++ b/tests/unit/utils/test_template_deps.py @@ -197,3 +197,15 @@ def test_bare_vars_and_hostvars_are_unanalysable(): def test_star_args_to_a_vars_lookup_are_unanalysable(): assert references("{{ lookup('vars', *names) }}").unanalysable assert references("{{ vars.get(*names) }}").unanalysable + + +def test_defaulted_names_are_those_under_default_or_d(): + r = references("{{ a | default(b) }}{{ c | d('x') }}{{ e }}") + assert r.defaulted == {"a", "b", "c"} + r = references("{{ vars[k] | default('fb') }}") + assert r.dynamic_keys[0].defaulted is True + assert references("{{ vars[k] }}").dynamic_keys[0].defaulted is False + assert references({"x": ["{{ hostvars[h]['p'] | default(1) }}"]}).defaulted == { + "h", + "p", + } From 2fcf6fbddcd16b98c41857f6eea281bf567c7bc1 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:56:53 +0200 Subject: [PATCH 10/16] Load !unsafe values from stack files A value tagged !unsafe in an environments file made the command exit 1: the vault-aware SafeLoader had no constructor for the tag and raised a ConstructorError. The loader now constructs such a value as UnsafeText, a str subclass. The dependency walker never parses it as a template, since Ansible never templates it either. The closure walk runs inside the action plugin, and JSON turns a str subclass into a plain str, so the request carries the tag as {"__ansible_unsafe": text}, which the walker skips too. Ansible reads the stack files itself, so the rendered value is unaffected. ansible-inventory drops the tag from inventory values; those are still analysed as templates. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/hostvars.py | 3 ++- osism/utils/render.py | 11 +++++++++- osism/utils/template_deps.py | 26 +++++++++++++++++++++++ tests/integration/test_hostvars_render.py | 9 +++++++- tests/unit/utils/test_hostvars.py | 13 ++++++++++++ tests/unit/utils/test_render.py | 12 +++++++++++ tests/unit/utils/test_template_deps.py | 11 ++++++++++ 7 files changed, 82 insertions(+), 3 deletions(-) diff --git a/osism/utils/hostvars.py b/osism/utils/hostvars.py index 34eb380e7..2a09c2213 100644 --- a/osism/utils/hostvars.py +++ b/osism/utils/hostvars.py @@ -30,6 +30,7 @@ load_stack_files, render_batch, ) +from osism.utils.template_deps import encode_unsafe __all__ = ["HostvarsError", "Row", "effective_rows"] @@ -119,7 +120,7 @@ def _render(stack: Stack, names: list, ctx: _Ctx, merged=None) -> Rendered: request = { "names": list(names), "secrets": sorted(secrets), - "raw": raw, + "raw": encode_unsafe(raw), "raw_all": _raw_all(ctx.all_raw_hostvars), "facts": sorted(ctx.facts) if isinstance(ctx.facts, dict) else [], } diff --git a/osism/utils/render.py b/osism/utils/render.py index 385842856..172a46cce 100644 --- a/osism/utils/render.py +++ b/osism/utils/render.py @@ -22,6 +22,7 @@ import yaml from osism import settings +from osism.utils.template_deps import UnsafeText _PLUGIN = """\ import json @@ -76,7 +77,8 @@ class Stack: class _VaultSafeLoader(yaml.SafeLoader): - """SafeLoader that keeps an inline !vault value as the encrypted marker.""" + """SafeLoader that keeps an inline !vault value as the encrypted marker + and loads an !unsafe value as UnsafeText, which is never analysed.""" def _construct_vault(loader: yaml.SafeLoader, node: yaml.Node) -> dict: @@ -86,6 +88,13 @@ def _construct_vault(loader: yaml.SafeLoader, node: yaml.Node) -> dict: _VaultSafeLoader.add_constructor("!vault", _construct_vault) +def _construct_unsafe(loader: yaml.SafeLoader, node: yaml.Node) -> UnsafeText: + return UnsafeText(loader.construct_scalar(cast(yaml.ScalarNode, node))) + + +_VaultSafeLoader.add_constructor("!unsafe", _construct_unsafe) + + def list_environments(root: str | None = None) -> list: root = root or settings.ENVIRONMENTS_DIRECTORY try: diff --git a/osism/utils/template_deps.py b/osism/utils/template_deps.py index 677478dbc..a01afae9b 100644 --- a/osism/utils/template_deps.py +++ b/osism/utils/template_deps.py @@ -65,6 +65,30 @@ _UNMODELLED = (nodes.Macro, nodes.CallBlock, nodes.With, nodes.FilterBlock) +_UNSAFE_MARKER = "__ansible_unsafe" + + +class UnsafeText(str): + """A value tagged !unsafe: Ansible never templates it, so neither do we.""" + + +def encode_unsafe(obj: Any) -> Any: + """Keep the !unsafe tag through JSON, which turns UnsafeText into str.""" + if isinstance(obj, UnsafeText): + return {_UNSAFE_MARKER: str(obj)} + if isinstance(obj, dict): + return {k: encode_unsafe(v) for k, v in obj.items()} + if isinstance(obj, list): + return [encode_unsafe(v) for v in obj] + return obj + + +def _is_unsafe(raw: Any) -> bool: + return isinstance(raw, UnsafeText) or ( + isinstance(raw, dict) and set(raw) == {_UNSAFE_MARKER} + ) + + @dataclass(frozen=True) class DynamicKey: expression: str | None @@ -120,6 +144,8 @@ def references(raw: Any) -> Refs: def _collect(raw: Any, acc: _Acc) -> None: + if _is_unsafe(raw): + return if isinstance(raw, dict): for value in raw.values(): _collect(value, acc) diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py index 326741e18..c5a502664 100644 --- a/tests/integration/test_hostvars_render.py +++ b/tests/integration/test_hostvars_render.py @@ -155,7 +155,9 @@ def two_hosts(tmp_path): ) root = tmp_path / "environments" root.mkdir() - (root / "configuration.yml").write_text("plain: 1\n") + (root / "configuration.yml").write_text( + "plain: 1\nliteral: !unsafe '{{ plain }}'\n" + ) (root / "secrets.yml").write_text("redis_master_password: Redis-Secret-42\n") raw, all_raw = _inventory_hostvars(str(inv), "node1") return dict( @@ -192,3 +194,8 @@ def test_real_render_reports_fallback(two_hosts): ["fallback: nope_undefined undefined here, a role may define it"], ) ] + + +def test_real_render_keeps_unsafe_literal(two_hosts): + rows = effective_rows("node1", "literal", None, False, **two_hosts) + assert [(r.value, r.masked, r.notes) for r in rows] == [("{{ plain }}", False, [])] diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index 6cd456c28..ac3766708 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -627,3 +627,16 @@ def test_undefined_outside_default_gets_no_fallback_note(world): {None: {"e": "xy"}}, )("e") assert rows[0].notes == ["fallback: other undefined here, a role may define it"] + + +def test_unsafe_stack_value_is_not_analysed(world, mocker): + from osism.utils.template_deps import UnsafeText + + get = world( + {"a": "1"}, + {None: {"lit": "{{ db_password }}", "db_password": "long-secret-1"}}, + global_files={"lit": UnsafeText("{{ db_password }}")}, + secrets_names={"db_password"}, + ) + rows = get("lit") + assert rows[0].value == "{{ db_password }}" and not rows[0].masked diff --git a/tests/unit/utils/test_render.py b/tests/unit/utils/test_render.py index f1fc4cf3f..b14b83438 100644 --- a/tests/unit/utils/test_render.py +++ b/tests/unit/utils/test_render.py @@ -147,3 +147,15 @@ def test_own_render_errors_are_safe(tmp_path): with pytest.raises(RenderError) as exc: render_batch("h", {"names": []}, "/inv", build_stack("kolla", root), "pw") assert exc.value.safe is True + + +def test_load_yaml_unsafe_is_a_literal_string(tmp_path): + # Final review I3: !unsafe made the command exit 1 (ConstructorError). + from osism.utils.template_deps import references + + f = tmp_path / "c.yml" + f.write_text("literal: !unsafe '{{ x }}'\n") + loaded = load_yaml(str(f), "pw") + assert loaded == {"literal": "{{ x }}"} + assert references(loaded["literal"]) == references("plain") + assert json.loads(json.dumps(loaded)) == {"literal": "{{ x }}"} diff --git a/tests/unit/utils/test_template_deps.py b/tests/unit/utils/test_template_deps.py index fdc54dfbe..52b1079e8 100644 --- a/tests/unit/utils/test_template_deps.py +++ b/tests/unit/utils/test_template_deps.py @@ -1,5 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 +import json + from osism.utils.template_deps import references @@ -209,3 +211,12 @@ def test_defaulted_names_are_those_under_default_or_d(): "h", "p", } + + +def test_unsafe_text_survives_the_request_as_a_literal(): + from osism.utils.template_deps import UnsafeText, encode_unsafe + + raw = {"a": UnsafeText("{{ secret_password }}"), "b": ["{{ c }}"]} + assert references(raw).names == {"c"} + encoded = json.loads(json.dumps(encode_unsafe(raw))) + assert references(encoded).names == {"c"} From d33f595b9725a7d5706eb9de7086aa716e9aa90f Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:57:23 +0200 Subject: [PATCH 11/16] Pass cached facts before the stack files render_batch passed the cached facts file as the last -e argument. A later -e wins, so a fact outranked the environments files, while in a play extra-vars outrank facts: a name defined both as a fact and in the configuration repository rendered as the fact. The facts file now goes first, giving inventory < facts < stack files. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/render.py | 6 ++++-- tests/unit/utils/test_render.py | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/osism/utils/render.py b/osism/utils/render.py index 172a46cce..d93d49c4a 100644 --- a/osism/utils/render.py +++ b/osism/utils/render.py @@ -216,13 +216,15 @@ def render_batch( "--vault-password-file", vault_file, ] - for path in stack.files: - command += ["-e", f"@{path}"] + # A later -e wins. In a play, facts rank below extra-vars, so the + # cached facts go before the stack files. if facts: facts_path = os.path.join(workdir, "facts.json") with open(facts_path, "w") as fp: json.dump(facts, fp) command += ["-e", f"@{facts_path}"] + for path in stack.files: + command += ["-e", f"@{path}"] env = os.environ.copy() env.update( ANSIBLE_GATHERING="explicit", diff --git a/tests/unit/utils/test_render.py b/tests/unit/utils/test_render.py index b14b83438..f14eef14a 100644 --- a/tests/unit/utils/test_render.py +++ b/tests/unit/utils/test_render.py @@ -115,13 +115,18 @@ def fake_run(cmd, **kwargs): "/inv", build_stack("kolla", root), "pw", + facts={"ansible_hostname": "n"}, ) assert len(runs) == 1 cmd, kwargs = runs[0] assert isinstance(cmd, list) and cmd[1] == "node;rm -rf /" and "shell" not in kwargs assert kwargs["cwd"] not in ("/ansible", None) + assert kwargs["env"]["ANSIBLE_NOCOLOR"] == "1" extra = [cmd[i + 1] for i, a in enumerate(cmd) if a == "-e"] - assert [e.replace("@" + root + "/", "") for e in extra] == [ + # Final review I4: in a play, extra-vars outrank facts. Later -e wins, + # so the facts file goes first. + assert extra[0].endswith("/facts.json") + assert [e.replace("@" + root + "/", "") for e in extra[1:]] == [ "configuration.yml", "secrets.yml", "kolla/secrets.yml", From 355038196cf163486665a08aae81644f8a3eda47 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 14:57:40 +0200 Subject: [PATCH 12/16] Turn off forced colour in the render run An ANSIBLE_FORCE_COLOR setting inherited from the caller's environment makes Ansible colour its output even with ANSIBLE_NOCOLOR=1. The ANSI escapes then end up in the error detail a render failure shows. The render subprocess now runs with ANSIBLE_FORCE_COLOR=0. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/render.py | 1 + tests/unit/utils/test_render.py | 2 ++ 2 files changed, 3 insertions(+) diff --git a/osism/utils/render.py b/osism/utils/render.py index d93d49c4a..09379eaf5 100644 --- a/osism/utils/render.py +++ b/osism/utils/render.py @@ -229,6 +229,7 @@ def render_batch( env.update( ANSIBLE_GATHERING="explicit", ANSIBLE_NOCOLOR="1", + ANSIBLE_FORCE_COLOR="0", ANSIBLE_RETRY_FILES_ENABLED="False", ) env["ANSIBLE_ACTION_PLUGINS"] = os.pathsep.join( diff --git a/tests/unit/utils/test_render.py b/tests/unit/utils/test_render.py index f14eef14a..b0f3a2ed8 100644 --- a/tests/unit/utils/test_render.py +++ b/tests/unit/utils/test_render.py @@ -122,6 +122,8 @@ def fake_run(cmd, **kwargs): assert isinstance(cmd, list) and cmd[1] == "node;rm -rf /" and "shell" not in kwargs assert kwargs["cwd"] not in ("/ansible", None) assert kwargs["env"]["ANSIBLE_NOCOLOR"] == "1" + # ANSIBLE_FORCE_COLOR in the caller's environment beats NOCOLOR. + assert kwargs["env"]["ANSIBLE_FORCE_COLOR"] == "0" extra = [cmd[i + 1] for i, a in enumerate(cmd) if a == "-e"] # Final review I4: in a play, extra-vars outrank facts. Later -e wins, # so the facts file goes first. From 43bf809bd0e60f06faacea785be76ebaee64ea62 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 15:00:13 +0200 Subject: [PATCH 13/16] Look variable names up instead of templating A variable's value was rendered by templating "{{ }}". A name that is not an identifier was therefore evaluated as an expression: an environments key 'plain ~ 2' rendered as 12, and the CLI's variable argument could combine other variables, secrets included, into one expression. Values are now looked up as vars['']. An absent name makes that lookup fail with Jinja's "has no attribute" message, so "'' in vars" is checked first and an absent name is reported as "AnsibleUndefinedVariable: '' is undefined", the shape the rows code relies on to drop the row of an absent variable. Dynamic keys found in templates are still templated as expressions. The command also refuses a variable argument that is not an identifier ([A-Za-z_][A-Za-z0-9_]*) and exits 1. --raw is unaffected; it never templates. The unit-test fakes answer the new expressions through a small by_name adapter. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/commands/get.py | 15 +++++++++ osism/utils/evaluate.py | 19 ++++++++++-- tests/integration/test_hostvars_render.py | 11 +++++-- tests/unit/commands/test_get.py | 12 +++++++ tests/unit/utils/_fakes.py | 24 ++++++++++++++ tests/unit/utils/test_evaluate.py | 38 ++++++++++++++++++++++- tests/unit/utils/test_hostvars.py | 14 ++++++--- 7 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 tests/unit/utils/_fakes.py diff --git a/osism/commands/get.py b/osism/commands/get.py index 30c32ea63..ea3b2d5cc 100644 --- a/osism/commands/get.py +++ b/osism/commands/get.py @@ -112,6 +112,10 @@ def take_action(self, parsed_args): ) +# The rendered path looks the name up; it is never templated. +VARIABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + class Hostvars(Command): def get_parser(self, prog_name): parser = super(Hostvars, self).get_parser(prog_name) @@ -162,6 +166,17 @@ def take_action(self, parsed_args): host = parsed_args.host[0] variable = parsed_args.variable + if ( + not parsed_args.raw + and variable is not None + and not VARIABLE_NAME.fullmatch(variable) + ): + logger.error( + f"not a valid variable name: {variable} " + "(letters, digits and underscores, not starting with a digit)" + ) + return 1 + inventory_path = get_inventory_path( "/ansible/inventory/hosts.yml", prefer_minified=False ) diff --git a/osism/utils/evaluate.py b/osism/utils/evaluate.py index 0af474aaf..1970e93d4 100644 --- a/osism/utils/evaluate.py +++ b/osism/utils/evaluate.py @@ -7,7 +7,8 @@ discovered while walking a closure are resolved by Ansible's own templar in the same invocation (one Ansible run per stack). ``resolve`` templates one expression and returns ``{"value": ...}`` or ``{"error": str}``; unit -tests pass a fake. +tests pass a fake. Dynamic keys are templated as expressions; variable +values are looked up as ``vars['']``. Request: names -- variables to report @@ -94,6 +95,20 @@ def _closure(name: str, request: dict, resolve: Resolve, key_cache: dict) -> dic } +def _value(resolve: Resolve, name: str) -> dict: + """Look a variable up by name; a name is never templated as an expression. + + vars[''] fails with Jinja's "has no attribute" message, so an + absent name is checked first and reported in the shape of templating + an undefined name, which callers rely on to drop the row. + """ + key = repr(str(name)) + present = resolve(f"{key} in vars") + if present.get("value") is False: + return {"error": f"AnsibleUndefinedVariable: '{name}' is undefined"} + return resolve(f"vars[{key}]") + + def evaluate_request(resolve: Resolve, request: dict) -> dict: key_cache: dict = {} closures = {n: _closure(n, request, resolve, key_cache) for n in request["names"]} @@ -101,5 +116,5 @@ def evaluate_request(resolve: Resolve, request: dict) -> dict: for n in list(request["names"]) + sorted( set(request["secrets"]) - set(request["names"]) ): - values[n] = resolve(n) + values[n] = _value(resolve, n) return {"values": values, "closures": closures} diff --git a/tests/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py index c5a502664..25937b876 100644 --- a/tests/integration/test_hostvars_render.py +++ b/tests/integration/test_hostvars_render.py @@ -97,7 +97,7 @@ def test_one_run_resolves_chains_and_vaults(setup): assert out["values"]["svc_url"] == {"value": "https://u:inline-secret-xyz@h"} assert out["values"]["db_password"] == {"value": "long-secret-1"} # hostvars_rows matches this exact shape to drop the row of an absent - # variable; a change in ansible-core's wording must fail here. + # variable; evaluate composes it after "'zz' in vars" came back false. assert out["values"]["zz"]["error"] == "AnsibleUndefinedVariable: 'zz' is undefined" assert raw["inline_pw"].keys() == {"__ansible_vault"} @@ -156,7 +156,7 @@ def two_hosts(tmp_path): root = tmp_path / "environments" root.mkdir() (root / "configuration.yml").write_text( - "plain: 1\nliteral: !unsafe '{{ plain }}'\n" + "plain: 1\nliteral: !unsafe '{{ plain }}'\n'plain ~ 2': lit\n" ) (root / "secrets.yml").write_text("redis_master_password: Redis-Secret-42\n") raw, all_raw = _inventory_hostvars(str(inv), "node1") @@ -199,3 +199,10 @@ def test_real_render_reports_fallback(two_hosts): def test_real_render_keeps_unsafe_literal(two_hosts): rows = effective_rows("node1", "literal", None, False, **two_hosts) assert [(r.value, r.masked, r.notes) for r in rows] == [("{{ plain }}", False, [])] + + +def test_real_render_looks_names_up_without_templating(two_hosts): + rows = effective_rows("node1", "plain ~ 2", None, False, **two_hosts) + assert [(r.value, r.notes) for r in rows] == [("lit", [])] + rows = effective_rows("node1", "absent_name", None, False, **two_hosts) + assert rows == [] diff --git a/tests/unit/commands/test_get.py b/tests/unit/commands/test_get.py index f13059214..6d656bf19 100644 --- a/tests/unit/commands/test_get.py +++ b/tests/unit/commands/test_get.py @@ -715,3 +715,15 @@ def test_hostvars_raw_json_format(mocker, capsys): "notes": [], } ] + + +def test_hostvars_variable_must_be_an_identifier(mocker, loguru_logs): + # Final review minor 3: the name must never reach Ansible as an + # expression. + m = _hv(mocker) + assert _run(["h", "a ~ db_password"]) == 1 + assert not m.called + assert any( + "not a valid variable name: a ~ db_password" in r["message"] + for r in loguru_logs + ) diff --git a/tests/unit/utils/_fakes.py b/tests/unit/utils/_fakes.py new file mode 100644 index 000000000..0d6d92dbf --- /dev/null +++ b/tests/unit/utils/_fakes.py @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Adapt a name -> result fake to the expressions evaluate_request sends.""" + +import ast +import re + + +def by_name(resolve): + """Answer "'x' in vars" and "vars['x']" from resolve(x); pass the rest.""" + + def inner(expr): + match = re.fullmatch(r"vars\[(.*)\]", expr) + if match: + return resolve(ast.literal_eval(match.group(1))) + match = re.fullmatch(r"('.*'|\".*\") in vars", expr) + if match: + name = ast.literal_eval(match.group(1)) + result = resolve(name) + absent = f"AnsibleUndefinedVariable: '{name}' is undefined" + return {"value": result.get("error") != absent} + return resolve(expr) + + return inner diff --git a/tests/unit/utils/test_evaluate.py b/tests/unit/utils/test_evaluate.py index bec813f12..7988eb16f 100644 --- a/tests/unit/utils/test_evaluate.py +++ b/tests/unit/utils/test_evaluate.py @@ -3,6 +3,8 @@ from osism.utils.evaluate import evaluate_request +from ._fakes import by_name + def _resolver(table, calls=None): def resolve(expr): @@ -12,7 +14,7 @@ def resolve(expr): return {"value": table[expr]} return {"error": f"AnsibleUndefinedVariable: '{expr}' is undefined"} - return resolve + return by_name(resolve) def _req(names, raw, secrets=(), raw_all=None, facts=None): @@ -157,3 +159,37 @@ def test_default_argument_and_nested_values_are_fallbacks(): ) assert r["closures"]["e"]["fallback"] == ["x", "y"] assert r["closures"]["a"]["fallback"] == ["x", "y"] + + +# Final review minor 3: names are looked up, never templated as expressions. + + +def _vars_resolver(table, calls): + def resolve(expr): + calls.append(expr) + for name, value in table.items(): + if expr == f"{name!r} in vars": + return {"value": True} + if expr == f"vars[{name!r}]": + return {"value": value} + if expr.endswith(" in vars"): + return {"value": False} + return {"error": f"TypeError: unexpected expression {expr}"} + + return resolve + + +def test_names_are_resolved_as_vars_lookups(): + calls = [] + r = evaluate_request( + _vars_resolver({"a ~ db_password": "lit", "b": 1}, calls), + _req(["a ~ db_password", "b"], {"a ~ db_password": "lit", "b": 1}), + ) + assert r["values"]["a ~ db_password"] == {"value": "lit"} + assert r["values"]["b"] == {"value": 1} + assert "a ~ db_password" not in calls and "b" not in calls + + +def test_absent_name_reports_undefined(): + r = evaluate_request(_vars_resolver({}, []), _req(["zz"], {})) + assert r["values"]["zz"] == {"error": "AnsibleUndefinedVariable: 'zz' is undefined"} diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index ac3766708..812d90d2d 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -9,6 +9,8 @@ from osism.utils.evaluate import evaluate_request from osism.utils.render import Stack +from ._fakes import by_name + @pytest.fixture def world(mocker): @@ -66,7 +68,7 @@ def resolve(expr): return {"error": f"{type(value).__name__}: {value}"} return {"value": value} - return evaluate_request(resolve, request) + return evaluate_request(by_name(resolve), request) def rows(variable=None, environment=None, show=False, facts=None): return hv.effective_rows( @@ -355,10 +357,12 @@ def failing_renderer(host, request, inv, stack, pw, facts=None, timeout=300): if stack.environment == "kolla": raise RenderError("fatal: kolla-only-secret-xyz leaked", safe=False) return evaluate_request( - lambda e: ( - {"value": {"X": "g", "Y": "g"}[e]} - if e in ("X", "Y") - else {"error": f"AnsibleUndefinedVariable: '{e}' is undefined"} + by_name( + lambda e: ( + {"value": {"X": "g", "Y": "g"}[e]} + if e in ("X", "Y") + else {"error": f"AnsibleUndefinedVariable: '{e}' is undefined"} + ) ), request, ) From 3c270eefed1a096b128a42c923ccbf5ac3470f5e Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 15:01:13 +0200 Subject: [PATCH 14/16] Note values masked by the literal net When only the literal net changed a value, the row was marked masked but carried no note saying why. It now gets the note "masked: contains a secret value". The refusal of --format value for a masked row repeated the prefix, "value is masked (masked: derived from p)". It now lists the masked notes without their "masked: " prefix: "value is masked (derived from p); pass --show-secrets". Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/commands/get.py | 7 +++++-- osism/utils/hostvars_rows.py | 4 +++- tests/unit/commands/test_get.py | 8 ++++++++ tests/unit/utils/test_hostvars.py | 2 ++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/osism/commands/get.py b/osism/commands/get.py index ea3b2d5cc..b8c6a59b4 100644 --- a/osism/commands/get.py +++ b/osism/commands/get.py @@ -302,9 +302,12 @@ def _output(self, parsed_args, host, variable, rows): return 1 row = rows[0] if row.masked: - logger.error( - f"value is masked ({'; '.join(row.notes)}); pass --show-secrets" + reasons = "; ".join( + n.removeprefix("masked: ") + for n in row.notes + if n.startswith("masked: ") ) + logger.error(f"value is masked ({reasons}); pass --show-secrets") return 1 if row.failed: for note in row.notes: diff --git a/osism/utils/hostvars_rows.py b/osism/utils/hostvars_rows.py index 2c28b278b..f20547b09 100644 --- a/osism/utils/hostvars_rows.py +++ b/osism/utils/hostvars_rows.py @@ -158,7 +158,9 @@ def _row( cleaned = replace_literals_deep( value, rendered.secret_values, MASK, MIN_SECRET_LENGTH ) - value, masked = cleaned, cleaned != value + if cleaned != value: + value, masked = cleaned, True + notes.append("masked: contains a secret value") # A dynamic key resolved to a value can land in `fallback`. notes += [ _clean( diff --git a/tests/unit/commands/test_get.py b/tests/unit/commands/test_get.py index 6d656bf19..9154d560d 100644 --- a/tests/unit/commands/test_get.py +++ b/tests/unit/commands/test_get.py @@ -727,3 +727,11 @@ def test_hostvars_variable_must_be_an_identifier(mocker, loguru_logs): "not a valid variable name: a ~ db_password" in r["message"] for r in loguru_logs ) + + +def test_hostvars_value_format_masked_message(mocker, loguru_logs): + _hv(mocker, [Row("h", "a", None, "***", True, ["masked: derived from p"], False)]) + assert _run(["h", "a", "--format", "value"]) == 1 + assert [r["message"] for r in loguru_logs if r["level"] == "ERROR"] == [ + "value is masked (derived from p); pass --show-secrets" + ] diff --git a/tests/unit/utils/test_hostvars.py b/tests/unit/utils/test_hostvars.py index 812d90d2d..39ad822ed 100644 --- a/tests/unit/utils/test_hostvars.py +++ b/tests/unit/utils/test_hostvars.py @@ -196,6 +196,7 @@ def test_literal_net_catches_unreached_secret(world): secrets_names={"db_password"}, )("u") assert rows[0].value == "pre-***-post" + assert rows[0].masked and rows[0].notes == ["masked: contains a secret value"] def test_environment_row_from_dependency_override_only_for_that_env(world): @@ -427,6 +428,7 @@ def test_literal_net_sets_masked(world): secrets_names={"db_password"}, )("u") assert rows[0].value == "***" and rows[0].masked + assert rows[0].notes == ["masked: contains a secret value"] def test_fallback_note_is_sanitised(world): From 880f745081bbca81b9fd053fc92c5c4fb4211920 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Wed, 7 Oct 2026 15:01:23 +0200 Subject: [PATCH 15/16] Leave a failed row's value cell empty The table output printed None in the Value column of a row whose render failed. The cell is now empty; the row's note carries the failure. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/commands/get.py | 11 ++++++----- tests/unit/commands/test_get.py | 7 +++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/osism/commands/get.py b/osism/commands/get.py index b8c6a59b4..3d9fb91f1 100644 --- a/osism/commands/get.py +++ b/osism/commands/get.py @@ -324,11 +324,12 @@ def _output(self, parsed_args, host, variable, rows): table = [] for r in rows: label = f"{r.variable} [{r.environment}]" if r.environment else r.variable - value = ( - "***" - if r.masked - else pprint.pformat(r.value, indent=2, width=60, compact=True) - ) + if r.masked: + value = "***" + elif r.failed: + value = "" + else: + value = pprint.pformat(r.value, indent=2, width=60, compact=True) table.append([r.host, label, value, "\n".join(r.notes)]) print( tabulate( diff --git a/tests/unit/commands/test_get.py b/tests/unit/commands/test_get.py index 9154d560d..87a30c77d 100644 --- a/tests/unit/commands/test_get.py +++ b/tests/unit/commands/test_get.py @@ -735,3 +735,10 @@ def test_hostvars_value_format_masked_message(mocker, loguru_logs): assert [r["message"] for r in loguru_logs if r["level"] == "ERROR"] == [ "value is masked (derived from p); pass --show-secrets" ] + + +def test_hostvars_failed_row_has_empty_value_cell(mocker, capsys): + _hv(mocker, [Row("h", "a", None, None, False, ["render failed: x"], True)]) + _run(["h"]) + out = capsys.readouterr().out + assert "None" not in out and "render failed: x" in out From 65e4eb501baf00c84332b47d97329456fb7f5b3f Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Fri, 27 Nov 2026 13:29:47 +0100 Subject: [PATCH 16/16] Share one engine for host-context templating resolve_in_host_context() and the batch renderer of osism dump inventory (osism/utils/render.py) both run a controller-side action plugin through "ansible -c local" and read its result back from a file. Each carried its own copy of everything around the plugin: the temporary directory, the plugin installation, the environment, the extra-vars files, the subprocess call, the error handling and the readback. The copies had already drifted: only the renderer ran from a neutral working directory, closed stdin and overrode ANSIBLE_FORCE_COLOR. run_in_host_context() in osism/utils/inventory.py is now the one engine. Both callers keep their own plugin, because what they template differs: the resolver's plugin writes one templated module argument and must keep working on ansible-core 2.18, while the renderer's plugin uses the 2.19 templar API (trust_as_template). The engine: - installs the plugin into a temporary directory that is also the working directory, so no group_vars/ next to the caller's current directory is loaded - never gathers facts, closes stdin and forces colour off - passes facts as an extra-vars file before any other extra-vars files, since a later -e wins and extra vars outrank facts in a play - passes optional request data as a file, so Ansible does not template it, and an optional vault password as a 0600 password file - returns the text the plugin wrote HostContextResolutionError gains from_ansible, set when the message is Ansible's own output. The renderer maps it to RenderError.safe, which decides whether the detail may be shown without --show-secrets. resolve_in_host_context() now also runs from the neutral working directory with stdin closed. Its signature, its return value and its unit and integration tests are unchanged; the renderer's tests now patch the engine's subprocess call. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- osism/utils/inventory.py | 122 ++++++++++++++++++++++++++------ osism/utils/render.py | 76 ++++---------------- tests/unit/utils/test_render.py | 6 +- 3 files changed, 115 insertions(+), 89 deletions(-) diff --git a/osism/utils/inventory.py b/osism/utils/inventory.py index 316ba059f..18226922f 100644 --- a/osism/utils/inventory.py +++ b/osism/utils/inventory.py @@ -28,7 +28,15 @@ def run(self, tmp=None, task_vars=None): class HostContextResolutionError(Exception): - """Raised when an expression cannot be templated in a host's context.""" + """Raised when an expression cannot be templated in a host's context. + + ``from_ansible`` is True when the message is Ansible's own output, which + may quote variable values; it is False for messages composed here. + """ + + def __init__(self, message: str, from_ansible: bool = False): + super().__init__(message) + self.from_ansible = from_ansible def get_inventory_path(base_path: str, prefer_minified: bool = True) -> str: @@ -133,28 +141,87 @@ def resolve_in_host_context( expression. The message carries Ansible's own explanation, which names the undefined variable or attribute. """ + return run_in_host_context( + host, + inventory_path, + "osism_resolve", + _RESOLVE_ACTION_PLUGIN, + # JSON module args rather than key=value, so a value containing spaces + # survives. + {"content": "{{ %s }}" % expression}, + facts=facts, + timeout=timeout, + ) + + +def run_in_host_context( + host: str, + inventory_path: str, + plugin_name: str, + plugin_source: str, + args: dict, + request: object = None, + facts: dict | None = None, + extra_vars_files: tuple = (), + vault_password: str | None = None, + timeout: int = 60, +) -> str: + """Run a controller-side action plugin in a host's variable context. + + The one engine behind ``resolve_in_host_context`` and the batch renderer + of ``osism dump inventory`` (``osism.utils.render``). Each brings its own + plugin, because what it templates differs; everything around the plugin + lives here once: + + - The plugin is installed into a temporary directory, which is also the + working directory, so no ``group_vars/`` next to the caller's current + directory leaks into the run. + - ``-c local`` with an action plugin: no connection, no module launched + with the target's interpreter, so a host that is down still resolves. + Facts are never gathered and stdin is closed. + - Facts travel as an extra-vars file, ahead of ``extra_vars_files``: a + later ``-e`` wins, and in a play extra vars outrank facts. + - The plugin writes its result to the file named by the ``dest`` + argument, which is read back byte-exact instead of parsed out of + Ansible's output, whose format differs between ansible-core versions. + + Args: + args: Module arguments; ``dest`` is added, and ``request`` when a + request is given. Ansible templates them in the host's context. + request: Optional JSON data for the plugin, passed as a file so that + Ansible does not template it. + vault_password: Optional; given to Ansible as a password file. + + Returns: + The text the plugin wrote. + + Raises: + HostContextResolutionError: Ansible failed (``from_ansible`` set; the + message is its output), timed out, or wrote nothing. + """ env = os.environ.copy() - # The module runs locally, but be explicit: never gather facts, so a host - # that is down cannot turn a lookup into an SSH timeout. - env["ANSIBLE_GATHERING"] = "explicit" - env["ANSIBLE_RETRY_FILES_ENABLED"] = "False" - env["ANSIBLE_NOCOLOR"] = "1" - - with tempfile.TemporaryDirectory(prefix="osism-resolve-") as workdir: - action_path = os.path.join(workdir, "osism_resolve.py") - with open(action_path, "w") as fp: - fp.write(_RESOLVE_ACTION_PLUGIN) - configured_action_plugins = env.get("ANSIBLE_ACTION_PLUGINS") + env.update( + ANSIBLE_GATHERING="explicit", + ANSIBLE_NOCOLOR="1", + # ANSIBLE_FORCE_COLOR in the caller's environment beats NOCOLOR. + ANSIBLE_FORCE_COLOR="0", + ANSIBLE_RETRY_FILES_ENABLED="False", + ) + + with tempfile.TemporaryDirectory(prefix="osism-host-context-") as workdir: + with open(os.path.join(workdir, f"{plugin_name}.py"), "w") as fp: + fp.write(plugin_source) env["ANSIBLE_ACTION_PLUGINS"] = os.pathsep.join( - part for part in (workdir, configured_action_plugins) if part + part for part in (workdir, env.get("ANSIBLE_ACTION_PLUGINS")) if part ) - value_path = os.path.join(workdir, "value") - # JSON module args rather than key=value, so a value containing spaces - # survives. - module_args = json.dumps( - {"content": "{{ %s }}" % expression, "dest": value_path} - ) + dest = os.path.join(workdir, "value") + args = dict(args, dest=dest) + if request is not None: + args["request"] = os.path.join(workdir, "request.json") + with open(args["request"], "w") as fp: + json.dump(request, fp) + command = [ "ansible", host, @@ -163,15 +230,22 @@ def resolve_in_host_context( "-c", "local", "-m", - "osism_resolve", + plugin_name, "-a", - module_args, + json.dumps(args), ] + if vault_password is not None: + vault_file = os.path.join(workdir, "vault") + with open(os.open(vault_file, os.O_WRONLY | os.O_CREAT, 0o600), "w") as fp: + fp.write(vault_password) + command += ["--vault-password-file", vault_file] if facts: facts_path = os.path.join(workdir, "facts.json") with open(facts_path, "w") as fp: json.dump(facts, fp) command += ["-e", f"@{facts_path}"] + for path in extra_vars_files: + command += ["-e", f"@{path}"] try: result = subprocess.run( @@ -180,6 +254,8 @@ def resolve_in_host_context( text=True, timeout=timeout, env=env, + cwd=workdir, + stdin=subprocess.DEVNULL, ) except subprocess.TimeoutExpired as exc: raise HostContextResolutionError( @@ -192,11 +268,11 @@ def resolve_in_host_context( # so take whichever of the two is non-empty and do not parse it. detail = (result.stdout or "").strip() or (result.stderr or "").strip() raise HostContextResolutionError( - detail or f"ansible exited {result.returncode}" + detail or f"ansible exited {result.returncode}", from_ansible=True ) try: - with open(value_path) as fp: + with open(dest) as fp: return fp.read() except OSError as exc: raise HostContextResolutionError("ansible wrote no value") from exc diff --git a/osism/utils/render.py b/osism/utils/render.py index 09379eaf5..44465b6c1 100644 --- a/osism/utils/render.py +++ b/osism/utils/render.py @@ -14,14 +14,13 @@ import json import os -import subprocess -import tempfile from dataclasses import dataclass from typing import cast import yaml from osism import settings +from osism.utils.inventory import HostContextResolutionError, run_in_host_context from osism.utils.template_deps import UnsafeText _PLUGIN = """\ @@ -192,68 +191,19 @@ def render_batch( host, request, inventory_path, stack, vault_password, facts=None, timeout=300 ): _check(stack) - with tempfile.TemporaryDirectory(prefix="osism-render-") as workdir: - with open(os.path.join(workdir, "osism_render.py"), "w") as fp: - fp.write(_PLUGIN) - vault_file = os.path.join(workdir, "vault") - with open(os.open(vault_file, os.O_WRONLY | os.O_CREAT, 0o600), "w") as fp: - fp.write(vault_password) - request_file = os.path.join(workdir, "request.json") - with open(request_file, "w") as fp: - json.dump(request, fp) - dest = os.path.join(workdir, "out.json") - command = [ - "ansible", + try: + text = run_in_host_context( host, - "-i", inventory_path, - "-c", - "local", - "-m", "osism_render", - "-a", - json.dumps({"request": request_file, "dest": dest}), - "--vault-password-file", - vault_file, - ] - # A later -e wins. In a play, facts rank below extra-vars, so the - # cached facts go before the stack files. - if facts: - facts_path = os.path.join(workdir, "facts.json") - with open(facts_path, "w") as fp: - json.dump(facts, fp) - command += ["-e", f"@{facts_path}"] - for path in stack.files: - command += ["-e", f"@{path}"] - env = os.environ.copy() - env.update( - ANSIBLE_GATHERING="explicit", - ANSIBLE_NOCOLOR="1", - ANSIBLE_FORCE_COLOR="0", - ANSIBLE_RETRY_FILES_ENABLED="False", - ) - env["ANSIBLE_ACTION_PLUGINS"] = os.pathsep.join( - p for p in (workdir, env.get("ANSIBLE_ACTION_PLUGINS")) if p + _PLUGIN, + {}, + request=request, + facts=facts, + extra_vars_files=stack.files, + vault_password=vault_password, + timeout=timeout, ) - try: - result = subprocess.run( - command, - capture_output=True, - text=True, - timeout=timeout, - env=env, - cwd=workdir, - stdin=subprocess.DEVNULL, - ) - except subprocess.TimeoutExpired as exc: - raise RenderError(f"ansible timed out after {timeout}s") from exc - if result.returncode != 0: - detail = (result.stdout or "").strip() or (result.stderr or "").strip() - raise RenderError( - detail or f"ansible exited {result.returncode}", safe=False - ) - try: - with open(dest) as fp: - return json.load(fp) - except OSError as exc: - raise RenderError("ansible wrote no result") from exc + except HostContextResolutionError as exc: + raise RenderError(str(exc), safe=not exc.from_ansible) from exc + return json.loads(text) diff --git a/tests/unit/utils/test_render.py b/tests/unit/utils/test_render.py index b0f3a2ed8..aaf20ef86 100644 --- a/tests/unit/utils/test_render.py +++ b/tests/unit/utils/test_render.py @@ -5,7 +5,7 @@ import pytest -from osism.utils import render +from osism.utils import inventory from osism.utils.render import ( RenderError, build_stack, @@ -108,7 +108,7 @@ def fake_run(cmd, **kwargs): json.dump({"values": {}, "closures": {}}, fp) return mocker.Mock(returncode=0, stdout="", stderr="") - mocker.patch.object(render.subprocess, "run", side_effect=fake_run) + mocker.patch.object(inventory.subprocess, "run", side_effect=fake_run) render_batch( "node;rm -rf /", {"names": ["a"], "secrets": [], "raw": {}, "raw_all": {}}, @@ -140,7 +140,7 @@ def fake_run(cmd, **kwargs): def test_render_batch_ansible_failure_raises_unsafe(tmp_path, mocker): root = _envs(tmp_path) mocker.patch.object( - render.subprocess, + inventory.subprocess, "run", return_value=mocker.Mock(returncode=4, stdout="", stderr="boom"), )