| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections.abc as c |
| 4 |
import types |
| 5 |
import typing as t |
| 6 |
|
| 7 |
from unittest import mock |
| 8 |
|
| 9 |
import pytest |
| 10 |
|
| 11 |
from ansible.inventory.group import Group |
| 12 |
from ansible.inventory.host import Host |
| 13 |
from ansible._internal._datatag._tags import TrustedAsTemplate |
| 14 |
from ansible.inventory.data import InventoryData |
| 15 |
from ansible.inventory import helpers |
| 16 |
|
| 17 |
|
| 18 |
def do_test(exec_str: str) -> None: |
| 19 |
hostname = TrustedAsTemplate().tag("hostname") |
| 20 |
groupname = TrustedAsTemplate().tag("groupname") |
| 21 |
|
| 22 |
# avoid unused locals |
| 23 |
assert hostname |
| 24 |
assert groupname |
| 25 |
|
| 26 |
inv = InventoryData() |
| 27 |
exec(exec_str) |
| 28 |
RecursiveChecker().visit(inv) |
| 29 |
|
| 30 |
|
| 31 |
@pytest.mark.parametrize("exec_str, trust_removal_required", ( |
| 32 |
# # cases where trust removal is required |
| 33 |
("inv.add_host(hostname, group='all')", True), |
| 34 |
("inv.add_group(groupname)", True), |
| 35 |
("inv.get_host(TrustedAsTemplate().tag('localhost'))", True), |
| 36 |
("inv.groups['all'].add_host(Host(hostname))", True), |
| 37 |
("inv.get_host('localhost').set_variable(TrustedAsTemplate().tag('key'), 'value')", True), # trusted key |
| 38 |
("inv.get_host('localhost').add_group(Group(groupname))", True), |
| 39 |
("inv.groups['all'].set_variable(TrustedAsTemplate().tag('key'), 'value')", True), # trusted key |
| 40 |
# cases where trust removal is not required |
| 41 |
("inv.add_host('hostname', group=TrustedAsTemplate().tag('all'))", False), # trusted group |
| 42 |
("inv.add_child('all', TrustedAsTemplate().tag(inv.add_host('hostname')))", False), # host trusted |
| 43 |
("inv.add_child(TrustedAsTemplate().tag('all'), inv.add_host('hostname'))", False), # group trusted |
| 44 |
)) |
| 45 |
def test_ensure_trust_stripping(exec_str: str, trust_removal_required: bool): |
| 46 |
do_test(exec_str) |
| 47 |
|
| 48 |
try: |
| 49 |
# re-run the test with the remove_trust helper no-opped to ensure that the test fails as expected |
| 50 |
with mock.patch.object(helpers, 'remove_trust', lambda o: o): |
| 51 |
do_test(exec_str) |
| 52 |
except TrustFoundError: |
| 53 |
if not trust_removal_required: |
| 54 |
pytest.fail("test expected no trust failure; the test is faulty") |
| 55 |
else: |
| 56 |
if trust_removal_required: |
| 57 |
pytest.fail("test expected trust failure; the test is faulty") |
| 58 |
|
| 59 |
|
| 60 |
class TrustFoundError(Exception): |
| 61 |
"""Raised when an object is trusted which should not be.""" |
| 62 |
|
| 63 |
def __init__(self, obj: t.Any) -> None: |
| 64 |
super().__init__(f'TrustedAsTemplate is tagged on {obj}.') |
| 65 |
|
| 66 |
|
| 67 |
class RecursiveChecker: |
| 68 |
"""Recrursive visitor used to assert that an object is not tagged with, and does not contain, a TrustedAsTemplate tag.""" |
| 69 |
|
| 70 |
def __init__(self) -> None: |
| 71 |
self.seen: set[int] = set() |
| 72 |
|
| 73 |
def visit(self, obj: t.Any) -> None: |
| 74 |
obj_id = id(obj) |
| 75 |
|
| 76 |
if obj_id in self.seen: |
| 77 |
return |
| 78 |
|
| 79 |
self.seen.add(obj_id) |
| 80 |
|
| 81 |
if TrustedAsTemplate.is_tagged_on(obj): |
| 82 |
raise TrustFoundError(obj) |
| 83 |
|
| 84 |
if isinstance(obj, (str, int, bool, types.NoneType)): |
| 85 |
pass # expected scalar type |
| 86 |
elif isinstance(obj, (InventoryData, Host, Group)): |
| 87 |
self.visit(obj.__dict__) |
| 88 |
elif isinstance(obj, c.Mapping): |
| 89 |
for key, value in obj.items(): |
| 90 |
self.visit(key) |
| 91 |
self.visit(value) |
| 92 |
elif isinstance(obj, c.Iterable): |
| 93 |
for item in obj: |
| 94 |
self.visit(item) |
| 95 |
else: |
| 96 |
raise TypeError(f'Checking of {type(obj)} is not supported.') # pragma: nocover |