| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright: (c) 2017, Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import collections.abc as c |
| 8 |
import os |
| 9 |
import os.path |
| 10 |
import pathlib |
| 11 |
import re |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
from ansible.config.manager import ConfigManager, ensure_type, resolve_path, get_config_type |
| 16 |
from ansible.errors import AnsibleOptionsError, AnsibleError |
| 17 |
from ansible.module_utils import secrets as _secrets_api |
| 18 |
from ansible.module_utils._internal import _secrets |
| 19 |
from ansible._internal._datatag._tags import Origin, VaultedValue |
| 20 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 21 |
from ansible.template import is_trusted_as_template |
| 22 |
from units.mock.vault_helper import VaultTestHelper |
| 23 |
|
| 24 |
curdir = os.path.dirname(__file__) |
| 25 |
cfg_file = os.path.join(curdir, 'test.cfg') |
| 26 |
cfg_file2 = os.path.join(curdir, 'test2.cfg') |
| 27 |
cfg_file3 = os.path.join(curdir, 'test3.cfg') |
| 28 |
|
| 29 |
|
| 30 |
class CustomMapping(c.Mapping): |
| 31 |
def __init__(self, values: c.Mapping) -> None: |
| 32 |
self._values = values |
| 33 |
|
| 34 |
def __getitem__(self, key, /): |
| 35 |
return self._values[key] |
| 36 |
|
| 37 |
def __len__(self): |
| 38 |
return len(self._values) |
| 39 |
|
| 40 |
def __iter__(self): |
| 41 |
return iter(self._values) |
| 42 |
|
| 43 |
|
| 44 |
class Unhashable: |
| 45 |
def __eq__(self, other): ... |
| 46 |
|
| 47 |
|
| 48 |
@pytest.mark.parametrize("value, value_type, expected_value", [ |
| 49 |
(None, 'str', None), # all types share a common short-circuit for None |
| 50 |
(Unhashable(), 'bool', False), |
| 51 |
('y', 'bool', True), |
| 52 |
('yes', 'bool', True), |
| 53 |
('on', 'bool', True), |
| 54 |
('1', 'bool', True), |
| 55 |
('true', 'bool', True), |
| 56 |
('t', 'bool', True), |
| 57 |
(1, 'bool', True), |
| 58 |
(1.0, 'bool', True), |
| 59 |
(True, 'bool', True), |
| 60 |
('n', 'bool', False), |
| 61 |
('no', 'bool', False), |
| 62 |
('off', 'bool', False), |
| 63 |
('0', 'bool', False), |
| 64 |
('false', 'bool', False), |
| 65 |
('f', 'bool', False), |
| 66 |
(0, 'bool', False), |
| 67 |
(0.0, 'bool', False), |
| 68 |
(False, 'bool', False), |
| 69 |
(False, 'boolean', False), # alias |
| 70 |
('10', 'int', 10), |
| 71 |
(20, 'int', 20), |
| 72 |
(True, 'int', 1), |
| 73 |
(False, 'int', 0), |
| 74 |
(42.0, 'int', 42), |
| 75 |
(-42.0, 'int', -42), |
| 76 |
(-42.0, 'integer', -42), # alias |
| 77 |
('2', 'float', 2.0), |
| 78 |
('0.10', 'float', 0.10), |
| 79 |
(0.2, 'float', 0.2), |
| 80 |
('a,b', 'list', ['a', 'b']), |
| 81 |
(['a', 1], 'list', ['a', 1]), |
| 82 |
(('a', 1), 'list', ['a', 1]), |
| 83 |
('None', 'none', None), |
| 84 |
('/p1', 'pathspec', ['/p1']), |
| 85 |
('/p1:/p2', 'pathspec', ['/p1', '/p2']), |
| 86 |
('/p1:/p2', 'pathspec', ['/p1', '/p2']), |
| 87 |
(['/p1', '/p2'], 'pathspec', ['/p1', '/p2']), |
| 88 |
('/tmp/test.yml,/home/test2.yml', 'pathlist', ['/tmp/test.yml', '/home/test2.yml']), |
| 89 |
('a', 'str', 'a'), |
| 90 |
('Café', 'str', 'Café'), |
| 91 |
('', 'str', ''), |
| 92 |
('29', 'str', '29'), |
| 93 |
('13.37', 'str', '13.37'), |
| 94 |
('123j', 'str', '123j'), |
| 95 |
('0x123', 'str', '0x123'), |
| 96 |
('true', 'str', 'true'), |
| 97 |
('True', 'str', 'True'), |
| 98 |
(0, 'str', '0'), |
| 99 |
(29, 'str', '29'), |
| 100 |
(13.37, 'str', '13.37'), |
| 101 |
(123j, 'str', '123j'), |
| 102 |
(0x123, 'str', '291'), |
| 103 |
(True, 'str', 'True'), |
| 104 |
(True, 'string', 'True'), # alias |
| 105 |
(CustomMapping(dict(a=1)), 'dict', dict(a=1)), |
| 106 |
(dict(a=1), 'dict', dict(a=1)), |
| 107 |
(dict(a=1), 'dictionary', dict(a=1)), # alias |
| 108 |
(123, 'bogustype', 123), # unknown non-string types pass through unmodified |
| 109 |
]) |
| 110 |
def test_ensure_type(value: object, value_type: str, expected_value: object) -> None: |
| 111 |
value = ensure_type(value, value_type) |
| 112 |
|
| 113 |
assert isinstance(value, type(expected_value)) |
| 114 |
assert value == expected_value |
| 115 |
|
| 116 |
|
| 117 |
@pytest.mark.parametrize("value, value_type, expected_msg_substring", [ |
| 118 |
('a', 'int', "Invalid value provided for 'int': 'a'"), |
| 119 |
('NaN', 'int', "Invalid value provided for 'int': 'NaN'"), |
| 120 |
(b'10', 'int', "Invalid value provided for 'int': b'10'"), |
| 121 |
(1.1, 'int', "Invalid value provided for 'int': 1.1"), |
| 122 |
('1.1', 'int', "Invalid value provided for 'int': '1.1'"), |
| 123 |
(-1.1, 'int', "Invalid value provided for 'int': -1.1"), |
| 124 |
('a', 'float', "Invalid value provided for 'float': 'a'"), |
| 125 |
(b'a', 'float', "Invalid value provided for 'float': b'a'"), |
| 126 |
(1, 'list', "Invalid value provided for 'list': 1"), |
| 127 |
(b'a', 'list', "Invalid value provided for 'list': b'a'"), |
| 128 |
(1, 'none', "Invalid value provided for 'none': 1"), |
| 129 |
(1, 'path', "Invalid value provided for 'path': 1"), |
| 130 |
(1, 'tmp', "Invalid value provided for 'tmp': 1"), |
| 131 |
(1, 'pathspec', "Invalid value provided for 'pathspec': 1"), |
| 132 |
(b'a', 'pathspec', "Invalid value provided for 'pathspec': b'a'"), |
| 133 |
([b'a'], 'pathspec', "Invalid value provided for 'pathspec': [b'a']"), |
| 134 |
(1, 'pathlist', "Invalid value provided for 'pathlist': 1"), |
| 135 |
(b'a', 'pathlist', "Invalid value provided for 'pathlist': b'a'"), |
| 136 |
([b'a'], 'pathlist', "Invalid value provided for 'pathlist': [b'a']"), |
| 137 |
(1, 'dict', "Invalid value provided for 'dict': 1"), |
| 138 |
([1], 'str', "Invalid value provided for 'str': [1]"), |
| 139 |
]) |
| 140 |
def test_ensure_type_failure(value: object, value_type: str, expected_msg_substring: str) -> None: |
| 141 |
with pytest.raises(ValueError, match=re.escape(expected_msg_substring)): |
| 142 |
ensure_type(value, value_type) |
| 143 |
|
| 144 |
|
| 145 |
@pytest.mark.parametrize("value, expected_value, value_type, origin, origin_ftype", [ |
| 146 |
('"value"', '"value"', 'str', 'env: ENVVAR', None), |
| 147 |
('"value"', '"value"', 'str', os.path.join(curdir, 'test.yml'), 'yaml'), |
| 148 |
('"value"', 'value', 'str', cfg_file, 'ini'), |
| 149 |
('\'value\'', 'value', 'str', cfg_file, 'ini'), |
| 150 |
('\'\'value\'\'', '\'value\'', 'str', cfg_file, 'ini'), |
| 151 |
('""value""', '"value"', 'str', cfg_file, 'ini'), |
| 152 |
('"x"', 'x', 'bogustype', cfg_file, 'ini'), # unknown string types are unquoted |
| 153 |
]) |
| 154 |
def test_ensure_type_unquoting(value: str, expected_value: str, value_type: str, origin: str | None, origin_ftype: str | None) -> None: |
| 155 |
actual_value = ensure_type(value, value_type, origin, origin_ftype) |
| 156 |
|
| 157 |
assert actual_value == expected_value |
| 158 |
|
| 159 |
|
| 160 |
test_origin = Origin(description='abc') |
| 161 |
|
| 162 |
|
| 163 |
@pytest.mark.parametrize("value, type", ( |
| 164 |
(test_origin.tag('a,b,c'), 'list'), |
| 165 |
(test_origin.tag(('a', 'b')), 'list'), |
| 166 |
(test_origin.tag('1'), 'int'), |
| 167 |
(test_origin.tag('plainstr'), 'str'), |
| 168 |
)) |
| 169 |
def test_ensure_type_tag_propagation(value: object, type: str) -> None: |
| 170 |
result = ensure_type(value, type) |
| 171 |
|
| 172 |
if value == result: |
| 173 |
assert value is result # if the value wasn't transformed, it should be the same instance |
| 174 |
|
| 175 |
if isinstance(value, str) and isinstance(result, list): |
| 176 |
# split a str list; each value should be tagged |
| 177 |
assert all(Origin.is_tagged_on(v) for v in result) |
| 178 |
|
| 179 |
# the result should always be tagged |
| 180 |
assert Origin.is_tagged_on(result) |
| 181 |
|
| 182 |
|
| 183 |
@pytest.mark.parametrize("value, type", ( |
| 184 |
(test_origin.tag('plainstr'), 'tmp'), |
| 185 |
)) |
| 186 |
def test_ensure_type_no_tag_propagation(value: object, type: str) -> None: |
| 187 |
result = ensure_type(value, type, origin='/tmp') |
| 188 |
|
| 189 |
assert not AnsibleTagHelper.tags(result) |
| 190 |
|
| 191 |
|
| 192 |
@pytest.mark.parametrize("value, type", ( |
| 193 |
('blah1', 'temppath'), |
| 194 |
('blah2', 'tmp'), |
| 195 |
('blah3', 'tmppath'), |
| 196 |
)) |
| 197 |
def test_ensure_type_temppath(value: object, type: str, tmp_path: pathlib.Path) -> None: |
| 198 |
path = ensure_type(value, type, origin=str(tmp_path)) |
| 199 |
|
| 200 |
assert os.path.isdir(path) |
| 201 |
assert value in path |
| 202 |
assert os.listdir(path) == [] |
| 203 |
|
| 204 |
|
| 205 |
def test_ensure_type_vaulted(_vault_secrets_context: VaultTestHelper) -> None: |
| 206 |
raw = "secretvalue" |
| 207 |
origin = Origin(description='test') |
| 208 |
es = _vault_secrets_context.make_encrypted_string(raw) |
| 209 |
es = origin.tag(es) |
| 210 |
result = ensure_type(es, 'str') |
| 211 |
|
| 212 |
assert isinstance(result, str) |
| 213 |
assert result == raw |
| 214 |
assert VaultedValue.is_tagged_on(result) |
| 215 |
assert Origin.get_tag(result) is origin |
| 216 |
|
| 217 |
|
| 218 |
class TestConfigManager: |
| 219 |
@classmethod |
| 220 |
def setup_class(cls): |
| 221 |
cls.manager = ConfigManager(cfg_file, os.path.join(curdir, 'test.yml')) |
| 222 |
|
| 223 |
@classmethod |
| 224 |
def teardown_class(cls): |
| 225 |
cls.manager = None |
| 226 |
|
| 227 |
def test_resolve_path(self): |
| 228 |
assert os.path.join(curdir, 'test.yml') == resolve_path('./test.yml', cfg_file) |
| 229 |
|
| 230 |
def test_resolve_path_cwd(self): |
| 231 |
assert os.path.join(os.getcwd(), 'test.yml') == resolve_path('{{CWD}}/test.yml') |
| 232 |
assert os.path.join(os.getcwd(), 'test.yml') == resolve_path('./test.yml') |
| 233 |
|
| 234 |
def test_value_and_origin_from_ini(self): |
| 235 |
assert self.manager.get_config_value_and_origin('config_entry') == ('fromini', cfg_file) |
| 236 |
|
| 237 |
def test_value_from_ini(self): |
| 238 |
assert self.manager.get_config_value('config_entry') == 'fromini' |
| 239 |
|
| 240 |
def test_value_and_origin_from_alt_ini(self): |
| 241 |
assert self.manager.get_config_value_and_origin('config_entry', cfile=cfg_file2) == ('fromini2', cfg_file2) |
| 242 |
|
| 243 |
def test_value_from_alt_ini(self): |
| 244 |
assert self.manager.get_config_value('config_entry', cfile=cfg_file2) == 'fromini2' |
| 245 |
|
| 246 |
def test_config_types(self): |
| 247 |
assert get_config_type('/tmp/ansible.ini') == 'ini' |
| 248 |
assert get_config_type('/tmp/ansible.cfg') == 'ini' |
| 249 |
assert get_config_type('/tmp/ansible.yaml') == 'yaml' |
| 250 |
assert get_config_type('/tmp/ansible.yml') == 'yaml' |
| 251 |
|
| 252 |
def test_config_types_negative(self): |
| 253 |
with pytest.raises(AnsibleOptionsError) as exec_info: |
| 254 |
get_config_type('/tmp/ansible.txt') |
| 255 |
assert "Unsupported configuration file extension for" in str(exec_info.value) |
| 256 |
|
| 257 |
def test_read_config_yaml_file(self): |
| 258 |
assert isinstance(self.manager._read_config_yaml_file(os.path.join(curdir, 'test.yml')), dict) |
| 259 |
|
| 260 |
def test_read_config_yaml_file_negative(self): |
| 261 |
with pytest.raises(AnsibleError) as exec_info: |
| 262 |
self.manager._read_config_yaml_file(os.path.join(curdir, 'test_non_existent.yml')) |
| 263 |
|
| 264 |
assert "Missing base YAML definition file (bad install?)" in str(exec_info.value) |
| 265 |
|
| 266 |
|
| 267 |
@pytest.fixture |
| 268 |
def fresh_masker(monkeypatch: pytest.MonkeyPatch) -> _secrets.SecretMasker: |
| 269 |
"""Swap in a fresh SecretMasker so registration/masking is isolated per test.""" |
| 270 |
masker = _secrets.SecretMasker() |
| 271 |
monkeypatch.setattr(_secrets_api, '_secret_masker', masker) |
| 272 |
return masker |
| 273 |
|
| 274 |
|
| 275 |
def test_initialize_plugin_secret_option_invalid_type() -> None: |
| 276 |
cm = ConfigManager() |
| 277 |
with pytest.raises(AnsibleOptionsError): |
| 278 |
cm.initialize_plugin_configuration_definitions('connection', 'demo', {'port': {'type': 'int', 'secret': True}}) |
| 279 |
|
| 280 |
|
| 281 |
def test_secret_config_value_registered_from_env(monkeypatch: pytest.MonkeyPatch, fresh_masker: _secrets.SecretMasker) -> None: |
| 282 |
monkeypatch.setenv('ANSIBLE_TEST_SECRET_OPT', 'super-secret-value') |
| 283 |
cm = ConfigManager() |
| 284 |
cm.initialize_plugin_configuration_definitions('connection', 'demo', { |
| 285 |
'password': {'type': 'str', 'secret': True, 'env': [{'name': 'ANSIBLE_TEST_SECRET_OPT'}], 'default': None}, |
| 286 |
}) |
| 287 |
|
| 288 |
value = cm.get_config_value('password', plugin_type='connection', plugin_name='demo') |
| 289 |
|
| 290 |
assert value == 'super-secret-value' |
| 291 |
assert fresh_masker.mask_string('log: super-secret-value') == 'log: $REDACTED$' |
| 292 |
|
| 293 |
|
| 294 |
def test_secret_config_value_registers_list_elements(fresh_masker: _secrets.SecretMasker) -> None: |
| 295 |
cm = ConfigManager() |
| 296 |
cm.initialize_plugin_configuration_definitions('connection', 'demo', { |
| 297 |
'keys': {'type': 'list', 'secret': True, 'default': []}, |
| 298 |
}) |
| 299 |
|
| 300 |
value = cm.get_config_value('keys', plugin_type='connection', plugin_name='demo', |
| 301 |
direct={'keys': ['first-secret-key', 12345678, 'second-secret-key']}) |
| 302 |
|
| 303 |
assert value == ['first-secret-key', 12345678, 'second-secret-key'] |
| 304 |
masked = fresh_masker.mask_string('first-secret-key, 12345678, and second-secret-key') |
| 305 |
assert masked == '$REDACTED$, 12345678, and $REDACTED$' |
| 306 |
|
| 307 |
|
| 308 |
def test_non_secret_config_value_not_registered(fresh_masker: _secrets.SecretMasker) -> None: |
| 309 |
cm = ConfigManager() |
| 310 |
cm.initialize_plugin_configuration_definitions('connection', 'demo', { |
| 311 |
'token': {'type': 'str', 'default': None}, # not marked secret |
| 312 |
}) |
| 313 |
|
| 314 |
cm.get_config_value('token', plugin_type='connection', plugin_name='demo', direct={'token': 'not-a-registered-secret'}) |
| 315 |
|
| 316 |
assert fresh_masker.mask_string('not-a-registered-secret') == 'not-a-registered-secret' |
| 317 |
|
| 318 |
|
| 319 |
@pytest.mark.parametrize(("key", "expected_value"), ( |
| 320 |
("COLOR_UNREACHABLE", "bright red"), |
| 321 |
("COLOR_VERBOSE", "rgb013"), |
| 322 |
("COLOR_DEBUG", "gray10"))) |
| 323 |
def test_256color_support(key, expected_value): |
| 324 |
# GIVEN: a config file containing 256-color values with default definitions |
| 325 |
manager = ConfigManager(cfg_file3) |
| 326 |
# WHEN: get config values |
| 327 |
actual_value = manager.get_config_value(key) |
| 328 |
# THEN: no error |
| 329 |
assert actual_value == expected_value |
| 330 |
|
| 331 |
|
| 332 |
def test_config_trust_from_env(monkeypatch: pytest.MonkeyPatch) -> None: |
| 333 |
expected = "from test" |
| 334 |
monkeypatch.setenv("ANSIBLE_TEST_ENTRY", expected) |
| 335 |
result = ConfigManager().get_config_value("_Z_TEST_ENTRY") |
| 336 |
origin = Origin.get_tag(result) |
| 337 |
|
| 338 |
assert result == expected |
| 339 |
assert is_trusted_as_template(result) |
| 340 |
assert origin and origin.description == '<Config env: ANSIBLE_TEST_ENTRY>' |
| 341 |
|
| 342 |
|
| 343 |
def test_config_trust_from_file(tmp_path: pathlib.Path) -> None: |
| 344 |
expected = "from test" |
| 345 |
cfg_path = tmp_path / 'test.cfg' |
| 346 |
|
| 347 |
cfg_path.write_text(f"[testing]\nvalid={expected}") |
| 348 |
|
| 349 |
result = ConfigManager(str(cfg_path)).get_config_value("_Z_TEST_ENTRY") |
| 350 |
origin = Origin.get_tag(result) |
| 351 |
|
| 352 |
assert result == expected |
| 353 |
assert is_trusted_as_template(result) |
| 354 |
assert origin |
| 355 |
assert origin.path == str(cfg_path) |
| 356 |
assert origin.description == "section 'testing' option 'valid'" |