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/commands/get.py b/osism/commands/get.py index 65b041d18..3d9fb91f1 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): @@ -109,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) @@ -124,26 +131,121 @@ 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): 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 ) 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 +266,78 @@ 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: + 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: + 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 + 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( + 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/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/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/evaluate.py b/osism/utils/evaluate.py new file mode 100644 index 000000000..1970e93d4 --- /dev/null +++ b/osism/utils/evaluate.py @@ -0,0 +1,120 @@ +# 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. Dynamic keys are templated as expressions; variable +values are looked up as ``vars['']``. + +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 + 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": [...], + "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 + +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"] + facts = set(request.get("facts") or ()) + seen: set = set() + names: set = set() + undefined: set = set() + defaulted: set = set() + unanalysable = 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 and current not in facts: + undefined.add(current) + continue + for value in sources: + refs = references(value) + if refs.unanalysable: + unanalysable = True + defaulted |= refs.defaulted + 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 + if key.defaulted: + defaulted.add(result["value"]) + 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), + "fallback": sorted(undefined & defaulted), + } + + +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"]} + values: dict = {} + for n in list(request["names"]) + sorted( + set(request["secrets"]) - set(request["names"]) + ): + values[n] = _value(resolve, n) + return {"values": values, "closures": closures} diff --git a/osism/utils/hostvars.py b/osism/utils/hostvars.py new file mode 100644 index 000000000..2a09c2213 --- /dev/null +++ b/osism/utils/hostvars.py @@ -0,0 +1,226 @@ +# 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, +) +from osism.utils.template_deps import encode_unsafe + +__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": encode_unsafe(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 + ) + 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..f20547b09 --- /dev/null +++ b/osism/utils/hostvars_rows.py @@ -0,0 +1,185 @@ +# 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": [], + "fallback": [], +} + + +@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 _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. + + 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 variables in [raw, *all_raw_hostvars.values()]: + secrets |= {n for n, v in variables.items() if _is_secret(n, 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 + ) + 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( + 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) + + +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/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 new file mode 100644 index 000000000..44465b6c1 --- /dev/null +++ b/osism/utils/render.py @@ -0,0 +1,209 @@ +# 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 +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 = """\ +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 + and loads an !unsafe value as UnsafeText, which is never analysed.""" + + +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 _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: + 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) + try: + text = run_in_host_context( + host, + inventory_path, + "osism_render", + _PLUGIN, + {}, + request=request, + facts=facts, + extra_vars_files=stack.files, + vault_password=vault_password, + timeout=timeout, + ) + except HostContextResolutionError as exc: + raise RenderError(str(exc), safe=not exc.from_ansible) from exc + return json.loads(text) diff --git a/osism/utils/secrets.py b/osism/utils/secrets.py new file mode 100644 index 000000000..c8b28822f --- /dev/null +++ b/osism/utils/secrets.py @@ -0,0 +1,99 @@ +# 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 _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 = "***", 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, structural_vault) + ) + return masked + + +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, structural_vault) + if isinstance(value, list): + 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: + """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/osism/utils/template_deps.py b/osism/utils/template_deps.py new file mode 100644 index 000000000..a01afae9b --- /dev/null +++ b/osism/utils/template_deps.py @@ -0,0 +1,414 @@ +# 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. + +``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 + +from jinja2 import Environment, nodes +from jinja2.exceptions import TemplateSyntaxError + +_ENV = Environment() +_GLOBALS = frozenset( + { + "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"}) +_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) + + +_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 + cross_host: bool + # Inside a default/d filter's base or argument. + defaulted: bool = False + + +@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 + # 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: + 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() + _collect(raw, acc) + return Refs( + names=frozenset(acc.names), + cross_host_names=frozenset(acc.cross), + dynamic_keys=tuple(acc.dynamic), + defaulted=frozenset(acc.defaulted), + unanalysable=acc.unanalysable, + ) + + +def _collect(raw: Any, acc: _Acc) -> None: + if _is_unsafe(raw): + return + 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") + 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 + + +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)): + cross = _variable_map(node.node, acc, bound) + if cross is not None: + if isinstance(node, nodes.Getattr): + if _is_mapping_attr(node.attr): + acc.unanalysable = True + else: + acc.add(node.attr, cross) + else: + _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.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 + 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.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.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 + ): + for item in items.items: + acc.add(_const(item)) + 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 + + +def _target(key: nodes.Node, acc: _Acc, cross: bool, bound: frozenset) -> None: + value = _const(key) + if isinstance(value, str): + 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.add_dynamic(expression, 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/integration/test_hostvars_render.py b/tests/integration/test_hostvars_render.py new file mode 100644 index 000000000..25937b876 --- /dev/null +++ b/tests/integration/test_hostvars_render.py @@ -0,0 +1,208 @@ +# 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 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, + 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"} + # hostvars_rows matches this exact shape to drop the row of an absent + # 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"} + + +def test_environment_local_names_reads_inline_vault(setup): + _, root = setup + assert environment_local_names("kolla", "probe-vault-pw", root) == { + "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\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") + 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) + + +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"], + ) + ] + + +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 e57e5725a..87a30c77d 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,218 @@ 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": [], + } + ] + + +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 + ) + + +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" + ] + + +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 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 new file mode 100644 index 000000000..7988eb16f --- /dev/null +++ b/tests/unit/utils/test_evaluate.py @@ -0,0 +1,195 @@ +# tests/unit/utils/test_evaluate.py +# SPDX-License-Identifier: Apache-2.0 + +from osism.utils.evaluate import evaluate_request + +from ._fakes import by_name + + +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 by_name(resolve) + + +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(): + 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"]["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"] + + +# 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 new file mode 100644 index 000000000..39ad822ed --- /dev/null +++ b/tests/unit/utils/test_hostvars.py @@ -0,0 +1,648 @@ +# 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 + +from ._fakes import by_name + + +@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(by_name(resolve), request) + + def rows(variable=None, environment=None, show=False, facts=None): + return hv.effective_rows( + "node1", + variable, + environment, + show, + inventory_path="/inv", + vault_password="pw", + facts=facts, + 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" + 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): + # 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": [], + "fallback": [], + } + }, + } + + 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( + by_name( + 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 + assert rows[0].notes == ["masked: contains a secret value"] + + +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)" + ] + + +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"] + + +# 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" + ] + + +# 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"] + + +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 new file mode 100644 index 000000000..aaf20ef86 --- /dev/null +++ b/tests/unit/utils/test_render.py @@ -0,0 +1,168 @@ +# tests/unit/utils/test_render.py +# SPDX-License-Identifier: Apache-2.0 + +import json + +import pytest + +from osism.utils import inventory +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(inventory.subprocess, "run", side_effect=fake_run) + render_batch( + "node;rm -rf /", + {"names": ["a"], "secrets": [], "raw": {}, "raw_all": {}}, + "/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" + # 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. + assert extra[0].endswith("/facts.json") + assert [e.replace("@" + root + "/", "") for e in extra[1:]] == [ + "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( + inventory.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 + + +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_secrets.py b/tests/unit/utils/test_secrets.py new file mode 100644 index 000000000..2cac1a850 --- /dev/null +++ b/tests/unit/utils/test_secrets.py @@ -0,0 +1,87 @@ +# 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]} + + +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": "***"} diff --git a/tests/unit/utils/test_template_deps.py b/tests/unit/utils/test_template_deps.py new file mode 100644 index 000000000..52b1079e8 --- /dev/null +++ b/tests/unit/utils/test_template_deps.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: Apache-2.0 + +import json + +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 + + +# 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 + + +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", + } + + +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"}