| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 3 |
# (c) 2016, Toshio Kuratomi <[email protected]> |
| 4 |
# |
| 5 |
# This file is part of Ansible |
| 6 |
# |
| 7 |
# Ansible is free software: you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# Ansible is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
|
| 20 |
from __future__ import annotations |
| 21 |
|
| 22 |
import io |
| 23 |
import os |
| 24 |
import pathlib |
| 25 |
import tempfile |
| 26 |
import typing as t |
| 27 |
|
| 28 |
from binascii import hexlify |
| 29 |
|
| 30 |
import pytest |
| 31 |
|
| 32 |
import unittest |
| 33 |
from unittest.mock import patch, MagicMock |
| 34 |
|
| 35 |
from ansible import errors |
| 36 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 37 |
from ansible.module_utils._internal import _messages |
| 38 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 39 |
from ansible.parsing import vault |
| 40 |
from ansible.parsing.vault import EncryptedString, VaultSecretsContext, AnsibleVaultError, VaultHelper |
| 41 |
from ansible._internal._templating._jinja_common import VaultExceptionMarker, TruncationMarker, Marker |
| 42 |
from ansible._internal._templating._engine import TemplateEngine, TemplateOptions |
| 43 |
from ansible._internal._templating._utils import TemplateContext |
| 44 |
from ansible._internal._datatag._tags import VaultedValue, Origin, TrustedAsTemplate |
| 45 |
from ansible.utils.collection_loader import _EncryptedStringProtocol |
| 46 |
|
| 47 |
from units.mock.loader import DictDataLoader |
| 48 |
from units.mock.vault_helper import TextVaultSecret, VaultTestHelper |
| 49 |
|
| 50 |
|
| 51 |
class TestUnhexlify(unittest.TestCase): |
| 52 |
def test(self): |
| 53 |
b_plain_data = b'some text to hexlify' |
| 54 |
b_data = hexlify(b_plain_data) |
| 55 |
res = vault._unhexlify(b_data) |
| 56 |
self.assertEqual(res, b_plain_data) |
| 57 |
|
| 58 |
def test_odd_length(self): |
| 59 |
b_data = b'123456789abcdefghijklmnopqrstuvwxyz' |
| 60 |
|
| 61 |
self.assertRaisesRegex(vault.AnsibleVaultFormatError, |
| 62 |
'.*Vault format unhexlify error.*', |
| 63 |
vault._unhexlify, |
| 64 |
b_data) |
| 65 |
|
| 66 |
def test_nonhex(self): |
| 67 |
b_data = b'6z36316566653264333665333637623064303639353237620a636366633565663263336335656532' |
| 68 |
|
| 69 |
self.assertRaisesRegex(vault.AnsibleVaultFormatError, |
| 70 |
'.*Vault format unhexlify error.*Non-hexadecimal digit found', |
| 71 |
vault._unhexlify, |
| 72 |
b_data) |
| 73 |
|
| 74 |
|
| 75 |
class TestParseVaulttext(unittest.TestCase): |
| 76 |
def test(self): |
| 77 |
vaulttext_envelope = u"""$ANSIBLE_VAULT;1.1;AES256 |
| 78 |
33363965326261303234626463623963633531343539616138316433353830356566396130353436 |
| 79 |
3562643163366231316662386565383735653432386435610a306664636137376132643732393835 |
| 80 |
63383038383730306639353234326630666539346233376330303938323639306661313032396437 |
| 81 |
6233623062366136310a633866373936313238333730653739323461656662303864663666653563 |
| 82 |
3138""" |
| 83 |
|
| 84 |
b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8') |
| 85 |
b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope) |
| 86 |
res = vault.parse_vaulttext(b_vaulttext) |
| 87 |
self.assertIsInstance(res[0], bytes) |
| 88 |
self.assertIsInstance(res[1], bytes) |
| 89 |
self.assertIsInstance(res[2], bytes) |
| 90 |
|
| 91 |
def test_non_hex(self): |
| 92 |
vaulttext_envelope = u"""$ANSIBLE_VAULT;1.1;AES256 |
| 93 |
3336396J326261303234626463623963633531343539616138316433353830356566396130353436 |
| 94 |
3562643163366231316662386565383735653432386435610a306664636137376132643732393835 |
| 95 |
63383038383730306639353234326630666539346233376330303938323639306661313032396437 |
| 96 |
6233623062366136310a633866373936313238333730653739323461656662303864663666653563 |
| 97 |
3138""" |
| 98 |
|
| 99 |
b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8') |
| 100 |
b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope) |
| 101 |
self.assertRaisesRegex(vault.AnsibleVaultFormatError, |
| 102 |
'.*Vault format unhexlify error.*Non-hexadecimal digit found', |
| 103 |
vault.parse_vaulttext, |
| 104 |
b_vaulttext_envelope) |
| 105 |
|
| 106 |
|
| 107 |
class TestVaultSecret(unittest.TestCase): |
| 108 |
def test(self): |
| 109 |
secret = vault.VaultSecret() |
| 110 |
secret.load() |
| 111 |
self.assertIsNone(secret._bytes) |
| 112 |
|
| 113 |
def test_bytes(self): |
| 114 |
some_text = u'私はガラスを食べられます。それは私を傷つけません。' |
| 115 |
_bytes = to_bytes(some_text) |
| 116 |
secret = vault.VaultSecret(_bytes) |
| 117 |
secret.load() |
| 118 |
self.assertEqual(secret.bytes, _bytes) |
| 119 |
|
| 120 |
|
| 121 |
class TestPromptVaultSecret(unittest.TestCase): |
| 122 |
def test_empty_prompt_formats(self): |
| 123 |
secret = vault.PromptVaultSecret(vault_id='test_id', prompt_formats=[]) |
| 124 |
secret.load() |
| 125 |
self.assertIsNone(secret._bytes) |
| 126 |
|
| 127 |
@patch('ansible.parsing.vault.display.prompt', return_value='the_password') |
| 128 |
def test_prompt_formats_none(self, mock_display_prompt): |
| 129 |
secret = vault.PromptVaultSecret(vault_id='test_id') |
| 130 |
secret.load() |
| 131 |
self.assertEqual(secret._bytes, b'the_password') |
| 132 |
|
| 133 |
@patch('ansible.parsing.vault.display.prompt', return_value='the_password') |
| 134 |
def test_custom_prompt(self, mock_display_prompt): |
| 135 |
secret = vault.PromptVaultSecret(vault_id='test_id', |
| 136 |
prompt_formats=['The cow flies at midnight: ']) |
| 137 |
secret.load() |
| 138 |
self.assertEqual(secret._bytes, b'the_password') |
| 139 |
|
| 140 |
@patch('ansible.parsing.vault.display.prompt', side_effect=EOFError) |
| 141 |
def test_prompt_eoferror(self, mock_display_prompt): |
| 142 |
secret = vault.PromptVaultSecret(vault_id='test_id') |
| 143 |
self.assertRaisesRegex(vault.AnsibleVaultError, |
| 144 |
'EOFError.*test_id', |
| 145 |
secret.load) |
| 146 |
|
| 147 |
@patch('ansible.parsing.vault.display.prompt', side_effect=['first_password', 'second_password']) |
| 148 |
def test_prompt_passwords_dont_match(self, mock_display_prompt): |
| 149 |
secret = vault.PromptVaultSecret(vault_id='test_id', |
| 150 |
prompt_formats=['Vault password: ', |
| 151 |
'Confirm Vault password: ']) |
| 152 |
self.assertRaisesRegex(errors.AnsibleError, |
| 153 |
'Passwords do not match', |
| 154 |
secret.load) |
| 155 |
|
| 156 |
|
| 157 |
class TestFileVaultSecret(unittest.TestCase): |
| 158 |
def setUp(self): |
| 159 |
self.vault_password = "test-vault-password" |
| 160 |
text_secret = TextVaultSecret(self.vault_password) |
| 161 |
self.vault_secrets = [('foo', text_secret)] |
| 162 |
|
| 163 |
def test(self): |
| 164 |
secret = vault.FileVaultSecret() |
| 165 |
self.assertIsNone(secret._bytes) |
| 166 |
self.assertIsNone(secret._text) |
| 167 |
|
| 168 |
def test_repr_empty(self): |
| 169 |
secret = vault.FileVaultSecret() |
| 170 |
self.assertEqual(repr(secret), "FileVaultSecret()") |
| 171 |
|
| 172 |
def test_repr(self): |
| 173 |
tmp_file = tempfile.NamedTemporaryFile(delete=False) |
| 174 |
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'}) |
| 175 |
|
| 176 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name) |
| 177 |
filename = tmp_file.name |
| 178 |
tmp_file.close() |
| 179 |
self.assertEqual(repr(secret), "FileVaultSecret(filename='%s')" % filename) |
| 180 |
|
| 181 |
def test_empty_bytes(self): |
| 182 |
secret = vault.FileVaultSecret() |
| 183 |
self.assertIsNone(secret.bytes) |
| 184 |
|
| 185 |
def test_file(self): |
| 186 |
password = 'some password' |
| 187 |
|
| 188 |
tmp_file = tempfile.NamedTemporaryFile(delete=False) |
| 189 |
tmp_file.write(to_bytes(password)) |
| 190 |
tmp_file.close() |
| 191 |
|
| 192 |
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'}) |
| 193 |
|
| 194 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name) |
| 195 |
secret.load() |
| 196 |
|
| 197 |
os.unlink(tmp_file.name) |
| 198 |
|
| 199 |
self.assertEqual(secret.bytes, to_bytes(password)) |
| 200 |
|
| 201 |
def test_file_empty(self): |
| 202 |
|
| 203 |
tmp_file = tempfile.NamedTemporaryFile(delete=False) |
| 204 |
tmp_file.write(to_bytes('')) |
| 205 |
tmp_file.close() |
| 206 |
|
| 207 |
fake_loader = DictDataLoader({tmp_file.name: ''}) |
| 208 |
|
| 209 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name) |
| 210 |
self.assertRaisesRegex(vault.AnsibleVaultPasswordError, |
| 211 |
'Invalid vault password was provided from file.*%s' % tmp_file.name, |
| 212 |
secret.load) |
| 213 |
|
| 214 |
os.unlink(tmp_file.name) |
| 215 |
|
| 216 |
def test_file_encrypted(self): |
| 217 |
vault_password = "test-vault-password" |
| 218 |
text_secret = TextVaultSecret(vault_password) |
| 219 |
vault_secrets = [('foo', text_secret)] |
| 220 |
|
| 221 |
password = 'some password' |
| 222 |
# 'some password' encrypted with 'test-ansible-password' |
| 223 |
|
| 224 |
password_file_content = """$ANSIBLE_VAULT;1.1;AES256 |
| 225 |
61393863643638653437313566313632306462383837303132346434616433313438353634613762 |
| 226 |
3334363431623364386164616163326537366333353663650a663634306232363432626162353665 |
| 227 |
39623061353266373631636331643761306665343731376633623439313138396330346237653930 |
| 228 |
6432643864346136640a653364386634666461306231353765636662316335613235383565306437 |
| 229 |
3737 |
| 230 |
""" |
| 231 |
|
| 232 |
tmp_file = tempfile.NamedTemporaryFile(delete=False) |
| 233 |
tmp_file.write(to_bytes(password_file_content)) |
| 234 |
tmp_file.close() |
| 235 |
|
| 236 |
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'}) |
| 237 |
fake_loader._vault.secrets = vault_secrets |
| 238 |
|
| 239 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name) |
| 240 |
secret.load() |
| 241 |
|
| 242 |
os.unlink(tmp_file.name) |
| 243 |
|
| 244 |
self.assertEqual(secret.bytes, to_bytes(password)) |
| 245 |
|
| 246 |
def test_file_not_a_directory(self): |
| 247 |
filename = '/dev/null/foobar' |
| 248 |
fake_loader = DictDataLoader({filename: 'sdfadf'}) |
| 249 |
|
| 250 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename) |
| 251 |
self.assertRaisesRegex(errors.AnsibleError, |
| 252 |
'.*Could not read vault password file.*/dev/null/foobar.*Not a directory', |
| 253 |
secret.load) |
| 254 |
|
| 255 |
def test_file_not_found(self): |
| 256 |
tmp_file = tempfile.NamedTemporaryFile() |
| 257 |
filename = os.path.realpath(tmp_file.name) |
| 258 |
tmp_file.close() |
| 259 |
|
| 260 |
fake_loader = DictDataLoader({filename: 'sdfadf'}) |
| 261 |
|
| 262 |
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename) |
| 263 |
self.assertRaisesRegex(errors.AnsibleError, |
| 264 |
'.*Could not read vault password file.*%s.*' % filename, |
| 265 |
secret.load) |
| 266 |
|
| 267 |
|
| 268 |
class TestScriptVaultSecret(unittest.TestCase): |
| 269 |
def test(self): |
| 270 |
secret = vault.ScriptVaultSecret() |
| 271 |
self.assertIsNone(secret._bytes) |
| 272 |
self.assertIsNone(secret._text) |
| 273 |
|
| 274 |
def _mock_popen(self, mock_popen, return_code=0, stdout=b'', stderr=b''): |
| 275 |
def communicate(): |
| 276 |
return stdout, stderr |
| 277 |
mock_popen.return_value = MagicMock(returncode=return_code) |
| 278 |
mock_popen_instance = mock_popen.return_value |
| 279 |
mock_popen_instance.communicate = communicate |
| 280 |
|
| 281 |
@patch('ansible.parsing.vault.subprocess.Popen') |
| 282 |
def test_read_file(self, mock_popen): |
| 283 |
self._mock_popen(mock_popen, stdout=b'some_password') |
| 284 |
secret = vault.ScriptVaultSecret() |
| 285 |
with patch.object(secret, 'loader') as mock_loader: |
| 286 |
mock_loader.is_executable = MagicMock(return_value=True) |
| 287 |
secret.load() |
| 288 |
|
| 289 |
@patch('ansible.parsing.vault.subprocess.Popen') |
| 290 |
def test_read_file_empty(self, mock_popen): |
| 291 |
self._mock_popen(mock_popen, stdout=b'') |
| 292 |
secret = vault.ScriptVaultSecret() |
| 293 |
with patch.object(secret, 'loader') as mock_loader: |
| 294 |
mock_loader.is_executable = MagicMock(return_value=True) |
| 295 |
self.assertRaisesRegex(vault.AnsibleVaultPasswordError, |
| 296 |
'Invalid vault password was provided from script', |
| 297 |
secret.load) |
| 298 |
|
| 299 |
@patch('ansible.parsing.vault.subprocess.Popen') |
| 300 |
def test_read_file_os_error(self, mock_popen): |
| 301 |
self._mock_popen(mock_popen) |
| 302 |
mock_popen.side_effect = OSError('That is not an executable') |
| 303 |
secret = vault.ScriptVaultSecret() |
| 304 |
with patch.object(secret, 'loader') as mock_loader: |
| 305 |
mock_loader.is_executable = MagicMock(return_value=True) |
| 306 |
self.assertRaisesRegex(errors.AnsibleError, |
| 307 |
'Problem running vault password script.*', |
| 308 |
secret.load) |
| 309 |
|
| 310 |
@patch('ansible.parsing.vault.subprocess.Popen') |
| 311 |
def test_read_file_not_executable(self, mock_popen): |
| 312 |
self._mock_popen(mock_popen) |
| 313 |
secret = vault.ScriptVaultSecret() |
| 314 |
with patch.object(secret, 'loader') as mock_loader: |
| 315 |
mock_loader.is_executable = MagicMock(return_value=False) |
| 316 |
self.assertRaisesRegex(vault.AnsibleVaultError, |
| 317 |
'The vault password script .* was not executable', |
| 318 |
secret.load) |
| 319 |
|
| 320 |
@patch('ansible.parsing.vault.subprocess.Popen') |
| 321 |
def test_read_file_non_zero_return_code(self, mock_popen): |
| 322 |
stderr = b'That did not work for a random reason' |
| 323 |
rc = 37 |
| 324 |
|
| 325 |
self._mock_popen(mock_popen, return_code=rc, stderr=stderr) |
| 326 |
secret = vault.ScriptVaultSecret(filename='/dev/null/some_vault_secret') |
| 327 |
with patch.object(secret, 'loader') as mock_loader: |
| 328 |
mock_loader.is_executable = MagicMock(return_value=True) |
| 329 |
self.assertRaisesRegex(errors.AnsibleError, |
| 330 |
r'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr), |
| 331 |
secret.load) |
| 332 |
|
| 333 |
|
| 334 |
class TestScriptIsClient(unittest.TestCase): |
| 335 |
def test_randomname(self): |
| 336 |
filename = 'randomname' |
| 337 |
res = vault.script_is_client(filename) |
| 338 |
self.assertFalse(res) |
| 339 |
|
| 340 |
def test_something_dash_client(self): |
| 341 |
filename = 'something-client' |
| 342 |
res = vault.script_is_client(filename) |
| 343 |
self.assertTrue(res) |
| 344 |
|
| 345 |
def test_something_dash_client_somethingelse(self): |
| 346 |
filename = 'something-client-somethingelse' |
| 347 |
res = vault.script_is_client(filename) |
| 348 |
self.assertFalse(res) |
| 349 |
|
| 350 |
def test_something_dash_client_py(self): |
| 351 |
filename = 'something-client.py' |
| 352 |
res = vault.script_is_client(filename) |
| 353 |
self.assertTrue(res) |
| 354 |
|
| 355 |
def test_full_path_something_dash_client_py(self): |
| 356 |
filename = '/foo/bar/something-client.py' |
| 357 |
res = vault.script_is_client(filename) |
| 358 |
self.assertTrue(res) |
| 359 |
|
| 360 |
def test_full_path_something_dash_client(self): |
| 361 |
filename = '/foo/bar/something-client' |
| 362 |
res = vault.script_is_client(filename) |
| 363 |
self.assertTrue(res) |
| 364 |
|
| 365 |
def test_full_path_something_dash_client_in_dir(self): |
| 366 |
filename = '/foo/bar/something-client/but/not/filename' |
| 367 |
res = vault.script_is_client(filename) |
| 368 |
self.assertFalse(res) |
| 369 |
|
| 370 |
|
| 371 |
class TestGetFileVaultSecret(unittest.TestCase): |
| 372 |
def test_file(self): |
| 373 |
password = 'some password' |
| 374 |
|
| 375 |
tmp_file = tempfile.NamedTemporaryFile(delete=False) |
| 376 |
tmp_file.write(to_bytes(password)) |
| 377 |
tmp_file.close() |
| 378 |
|
| 379 |
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'}) |
| 380 |
|
| 381 |
secret = vault.get_file_vault_secret(filename=tmp_file.name, loader=fake_loader) |
| 382 |
secret.load() |
| 383 |
|
| 384 |
os.unlink(tmp_file.name) |
| 385 |
|
| 386 |
self.assertEqual(secret.bytes, to_bytes(password)) |
| 387 |
|
| 388 |
def test_file_not_a_directory(self): |
| 389 |
filename = '/dev/null/foobar' |
| 390 |
fake_loader = DictDataLoader({filename: 'sdfadf'}) |
| 391 |
|
| 392 |
self.assertRaisesRegex(errors.AnsibleError, |
| 393 |
'.*The vault password file %s was not found.*' % filename, |
| 394 |
vault.get_file_vault_secret, |
| 395 |
filename=filename, |
| 396 |
loader=fake_loader) |
| 397 |
|
| 398 |
def test_file_not_found(self): |
| 399 |
tmp_file = tempfile.NamedTemporaryFile() |
| 400 |
filename = os.path.realpath(tmp_file.name) |
| 401 |
tmp_file.close() |
| 402 |
|
| 403 |
fake_loader = DictDataLoader({filename: 'sdfadf'}) |
| 404 |
|
| 405 |
self.assertRaisesRegex(errors.AnsibleError, |
| 406 |
'.*The vault password file %s was not found.*' % filename, |
| 407 |
vault.get_file_vault_secret, |
| 408 |
filename=filename, |
| 409 |
loader=fake_loader) |
| 410 |
|
| 411 |
|
| 412 |
class TestVaultIsEncrypted(unittest.TestCase): |
| 413 |
def test_bytes_not_encrypted(self): |
| 414 |
b_data = b"foobar" |
| 415 |
self.assertFalse(vault.is_encrypted(b_data)) |
| 416 |
|
| 417 |
def test_bytes_encrypted(self): |
| 418 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") |
| 419 |
self.assertTrue(vault.is_encrypted(b_data)) |
| 420 |
|
| 421 |
def test_text_not_encrypted(self): |
| 422 |
b_data = to_text(b"foobar") |
| 423 |
self.assertFalse(vault.is_encrypted(b_data)) |
| 424 |
|
| 425 |
def test_text_encrypted(self): |
| 426 |
b_data = to_text(b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible")) |
| 427 |
self.assertTrue(vault.is_encrypted(b_data)) |
| 428 |
|
| 429 |
def test_invalid_text_not_ascii(self): |
| 430 |
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " |
| 431 |
self.assertFalse(vault.is_encrypted(data)) |
| 432 |
|
| 433 |
def test_invalid_bytes_not_ascii(self): |
| 434 |
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " |
| 435 |
b_data = to_bytes(data, encoding='utf-8') |
| 436 |
self.assertFalse(vault.is_encrypted(b_data)) |
| 437 |
|
| 438 |
|
| 439 |
class TestVaultIsEncryptedFile(unittest.TestCase): |
| 440 |
def test_binary_file_handle_not_encrypted(self): |
| 441 |
b_data = b"foobar" |
| 442 |
b_data_fo = io.BytesIO(b_data) |
| 443 |
self.assertFalse(vault.is_encrypted_file(b_data_fo)) |
| 444 |
|
| 445 |
def test_text_file_handle_not_encrypted(self): |
| 446 |
data = u"foobar" |
| 447 |
data_fo = io.StringIO(data) |
| 448 |
self.assertFalse(vault.is_encrypted_file(data_fo)) |
| 449 |
|
| 450 |
def test_binary_file_handle_encrypted(self): |
| 451 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") |
| 452 |
b_data_fo = io.BytesIO(b_data) |
| 453 |
self.assertTrue(vault.is_encrypted_file(b_data_fo)) |
| 454 |
|
| 455 |
def test_text_file_handle_encrypted(self): |
| 456 |
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % to_text(hexlify(b"ansible")) |
| 457 |
data_fo = io.StringIO(data) |
| 458 |
self.assertTrue(vault.is_encrypted_file(data_fo)) |
| 459 |
|
| 460 |
def test_binary_file_handle_invalid(self): |
| 461 |
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " |
| 462 |
b_data = to_bytes(data) |
| 463 |
b_data_fo = io.BytesIO(b_data) |
| 464 |
self.assertFalse(vault.is_encrypted_file(b_data_fo, count=-1)) |
| 465 |
|
| 466 |
def test_text_file_handle_invalid(self): |
| 467 |
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " |
| 468 |
data_fo = io.StringIO(data) |
| 469 |
self.assertFalse(vault.is_encrypted_file(data_fo, count=-1)) |
| 470 |
|
| 471 |
def test_file_already_read_from_finds_header(self): |
| 472 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") |
| 473 |
b_data_fo = io.BytesIO(b_data) |
| 474 |
b_data_fo.read(42) # Arbitrary number |
| 475 |
self.assertTrue(vault.is_encrypted_file(b_data_fo)) |
| 476 |
|
| 477 |
def test_file_already_read_from_saves_file_pos(self): |
| 478 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") |
| 479 |
b_data_fo = io.BytesIO(b_data) |
| 480 |
b_data_fo.read(69) # Arbitrary number |
| 481 |
vault.is_encrypted_file(b_data_fo) |
| 482 |
self.assertEqual(b_data_fo.tell(), 69) |
| 483 |
|
| 484 |
def test_file_with_offset(self): |
| 485 |
b_data = b"JUNK$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") |
| 486 |
b_data_fo = io.BytesIO(b_data) |
| 487 |
self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4)) |
| 488 |
|
| 489 |
def test_file_with_count(self): |
| 490 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") |
| 491 |
vault_length = len(b_data) |
| 492 |
b_data = b_data + u'ァ ア'.encode('utf-8') |
| 493 |
b_data_fo = io.BytesIO(b_data) |
| 494 |
self.assertTrue(vault.is_encrypted_file(b_data_fo, count=vault_length)) |
| 495 |
|
| 496 |
def test_file_with_offset_and_count(self): |
| 497 |
b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") |
| 498 |
vault_length = len(b_data) |
| 499 |
b_data = b'JUNK' + b_data + u'ァ ア'.encode('utf-8') |
| 500 |
b_data_fo = io.BytesIO(b_data) |
| 501 |
self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4, count=vault_length)) |
| 502 |
|
| 503 |
|
| 504 |
@pytest.mark.skipif(not vault.HAS_CRYPTOGRAPHY, |
| 505 |
reason="Skipping cryptography tests because cryptography is not installed") |
| 506 |
class TestVaultCipherAes256(unittest.TestCase): |
| 507 |
def setUp(self): |
| 508 |
self.vault_cipher = vault.VaultAES256() |
| 509 |
|
| 510 |
def test(self): |
| 511 |
self.assertIsInstance(self.vault_cipher, vault.VaultAES256) |
| 512 |
|
| 513 |
# TODO: tag these as slow tests |
| 514 |
def test_create_key_cryptography(self): |
| 515 |
b_password = b'hunter42' |
| 516 |
b_salt = os.urandom(32) |
| 517 |
b_key_cryptography = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16) |
| 518 |
self.assertIsInstance(b_key_cryptography, bytes) |
| 519 |
|
| 520 |
def test_create_key_known_cryptography(self): |
| 521 |
b_password = b'hunter42' |
| 522 |
|
| 523 |
# A fixed salt |
| 524 |
b_salt = b'q' * 32 # q is the most random letter. |
| 525 |
b_key_1 = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16) |
| 526 |
self.assertIsInstance(b_key_1, bytes) |
| 527 |
|
| 528 |
# verify we get the same answer |
| 529 |
# we could potentially run a few iterations of this and time it to see if it's roughly constant time |
| 530 |
# and or that it exceeds some minimal time, but that would likely cause unreliable fails, esp in CI |
| 531 |
b_key_2 = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16) |
| 532 |
self.assertIsInstance(b_key_2, bytes) |
| 533 |
self.assertEqual(b_key_1, b_key_2) |
| 534 |
|
| 535 |
def test_is_equal_is_equal(self): |
| 536 |
self.assertTrue(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'abcdefghijklmnopqrstuvwxyz')) |
| 537 |
|
| 538 |
def test_is_equal_unequal_length(self): |
| 539 |
self.assertFalse(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'abcdefghijklmnopqrstuvwx and sometimes y')) |
| 540 |
|
| 541 |
def test_is_equal_not_equal(self): |
| 542 |
self.assertFalse(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'AbcdefghijKlmnopQrstuvwxZ')) |
| 543 |
|
| 544 |
def test_is_equal_empty(self): |
| 545 |
self.assertTrue(self.vault_cipher._is_equal(b'', b'')) |
| 546 |
|
| 547 |
def test_is_equal_non_ascii_equal(self): |
| 548 |
utf8_data = to_bytes(u'私はガラスを食べられます。それは私を傷つけません。') |
| 549 |
self.assertTrue(self.vault_cipher._is_equal(utf8_data, utf8_data)) |
| 550 |
|
| 551 |
def test_is_equal_non_ascii_unequal(self): |
| 552 |
utf8_data = to_bytes(u'私はガラスを食べられます。それは私を傷つけません。') |
| 553 |
utf8_data2 = to_bytes(u'Pot să mănânc sticlă și ea nu mă rănește.') |
| 554 |
|
| 555 |
# Test for the len optimization path |
| 556 |
self.assertFalse(self.vault_cipher._is_equal(utf8_data, utf8_data2)) |
| 557 |
# Test for the slower, char by char comparison path |
| 558 |
self.assertFalse(self.vault_cipher._is_equal(utf8_data, utf8_data[:-1] + b'P')) |
| 559 |
|
| 560 |
def test_is_equal_non_bytes(self): |
| 561 |
""" Anything not a byte string should raise a TypeError """ |
| 562 |
self.assertRaises(TypeError, self.vault_cipher._is_equal, u"One fish", b"two fish") |
| 563 |
self.assertRaises(TypeError, self.vault_cipher._is_equal, b"One fish", u"two fish") |
| 564 |
self.assertRaises(TypeError, self.vault_cipher._is_equal, 1, b"red fish") |
| 565 |
self.assertRaises(TypeError, self.vault_cipher._is_equal, b"blue fish", 2) |
| 566 |
|
| 567 |
|
| 568 |
class TestMatchSecrets(unittest.TestCase): |
| 569 |
def test_empty_tuple(self): |
| 570 |
secrets = [tuple()] |
| 571 |
vault_ids = ['vault_id_1'] |
| 572 |
self.assertRaises(ValueError, |
| 573 |
vault.match_secrets, |
| 574 |
secrets, vault_ids) |
| 575 |
|
| 576 |
def test_empty_secrets(self): |
| 577 |
matches = vault.match_secrets([], ['vault_id_1']) |
| 578 |
self.assertEqual(matches, []) |
| 579 |
|
| 580 |
def test_single_match(self): |
| 581 |
secret = TextVaultSecret('password') |
| 582 |
matches = vault.match_secrets([('default', secret)], ['default']) |
| 583 |
self.assertEqual(matches, [('default', secret)]) |
| 584 |
|
| 585 |
def test_no_matches(self): |
| 586 |
secret = TextVaultSecret('password') |
| 587 |
matches = vault.match_secrets([('default', secret)], ['not_default']) |
| 588 |
self.assertEqual(matches, []) |
| 589 |
|
| 590 |
def test_multiple_matches(self): |
| 591 |
secrets = [('vault_id1', TextVaultSecret('password1')), |
| 592 |
('vault_id2', TextVaultSecret('password2')), |
| 593 |
('vault_id1', TextVaultSecret('password3')), |
| 594 |
('vault_id4', TextVaultSecret('password4'))] |
| 595 |
vault_ids = ['vault_id1', 'vault_id4'] |
| 596 |
matches = vault.match_secrets(secrets, vault_ids) |
| 597 |
|
| 598 |
self.assertEqual(len(matches), 3) |
| 599 |
expected = [('vault_id1', TextVaultSecret('password1')), |
| 600 |
('vault_id1', TextVaultSecret('password3')), |
| 601 |
('vault_id4', TextVaultSecret('password4'))] |
| 602 |
self.assertEqual([x for x, y in matches], |
| 603 |
[a for a, b in expected]) |
| 604 |
|
| 605 |
|
| 606 |
@pytest.mark.skipif(not vault.HAS_CRYPTOGRAPHY, |
| 607 |
reason="Skipping cryptography tests because cryptography is not installed") |
| 608 |
class TestVaultLib(unittest.TestCase): |
| 609 |
def setUp(self): |
| 610 |
self.vault_password = "test-vault-password" |
| 611 |
text_secret = TextVaultSecret(self.vault_password) |
| 612 |
self.vault_secrets = [('default', text_secret), |
| 613 |
('test_id', text_secret)] |
| 614 |
self.v = vault.VaultLib(self.vault_secrets) |
| 615 |
|
| 616 |
def _vault_secrets_from_password(self, vault_id, password): |
| 617 |
return [(vault_id, TextVaultSecret(password))] |
| 618 |
|
| 619 |
def test_encrypt(self): |
| 620 |
plaintext = u'Some text to encrypt in a café' |
| 621 |
b_vaulttext = self.v.encrypt(plaintext) |
| 622 |
|
| 623 |
self.assertIsInstance(b_vaulttext, bytes) |
| 624 |
|
| 625 |
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n' |
| 626 |
self.assertEqual(b_vaulttext[:len(b_header)], b_header) |
| 627 |
|
| 628 |
def test_encrypt_vault_id(self): |
| 629 |
plaintext = u'Some text to encrypt in a café' |
| 630 |
b_vaulttext = self.v.encrypt(plaintext, vault_id='test_id') |
| 631 |
|
| 632 |
self.assertIsInstance(b_vaulttext, bytes) |
| 633 |
|
| 634 |
b_header = b'$ANSIBLE_VAULT;1.2;AES256;test_id\n' |
| 635 |
self.assertEqual(b_vaulttext[:len(b_header)], b_header) |
| 636 |
|
| 637 |
def test_encrypt_bytes(self): |
| 638 |
|
| 639 |
plaintext = to_bytes(u'Some text to encrypt in a café') |
| 640 |
b_vaulttext = self.v.encrypt(plaintext) |
| 641 |
|
| 642 |
self.assertIsInstance(b_vaulttext, bytes) |
| 643 |
|
| 644 |
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n' |
| 645 |
self.assertEqual(b_vaulttext[:len(b_header)], b_header) |
| 646 |
|
| 647 |
def test_encrypt_no_secret_empty_secrets(self): |
| 648 |
vault_secrets = [] |
| 649 |
v = vault.VaultLib(vault_secrets) |
| 650 |
|
| 651 |
plaintext = u'Some text to encrypt in a café' |
| 652 |
self.assertRaisesRegex(vault.AnsibleVaultError, |
| 653 |
'.*A vault password must be specified to encrypt data.*', |
| 654 |
v.encrypt, |
| 655 |
plaintext) |
| 656 |
|
| 657 |
def test_format_vaulttext_envelope(self): |
| 658 |
cipher_name = "TEST" |
| 659 |
b_ciphertext = b"ansible" |
| 660 |
b_vaulttext = vault.format_vaulttext_envelope(b_ciphertext, |
| 661 |
cipher_name, |
| 662 |
version=self.v.b_version, |
| 663 |
vault_id='default') |
| 664 |
b_lines = b_vaulttext.split(b'\n') |
| 665 |
self.assertGreater(len(b_lines), 1, msg="failed to properly add header") |
| 666 |
|
| 667 |
b_header = b_lines[0] |
| 668 |
# self.assertTrue(b_header.endswith(b';TEST'), msg="header does not end with cipher name") |
| 669 |
|
| 670 |
b_header_parts = b_header.split(b';') |
| 671 |
self.assertEqual(len(b_header_parts), 4, msg="header has the wrong number of parts") |
| 672 |
self.assertEqual(b_header_parts[0], b'$ANSIBLE_VAULT', msg="header does not start with $ANSIBLE_VAULT") |
| 673 |
self.assertEqual(b_header_parts[1], self.v.b_version, msg="header version is incorrect") |
| 674 |
self.assertEqual(b_header_parts[2], b'TEST', msg="header does not end with cipher name") |
| 675 |
|
| 676 |
# And just to verify, lets parse the results and compare |
| 677 |
b_ciphertext2, b_version2, cipher_name2, vault_id2 = \ |
| 678 |
vault.parse_vaulttext_envelope(b_vaulttext) |
| 679 |
self.assertEqual(b_ciphertext, b_ciphertext2) |
| 680 |
self.assertEqual(self.v.b_version, b_version2) |
| 681 |
self.assertEqual(cipher_name, cipher_name2) |
| 682 |
self.assertEqual('default', vault_id2) |
| 683 |
|
| 684 |
def test_parse_vaulttext_envelope(self): |
| 685 |
b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\nansible" |
| 686 |
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext) |
| 687 |
b_lines = b_ciphertext.split(b'\n') |
| 688 |
self.assertEqual(b_lines[0], b"ansible", msg="Payload was not properly split from the header") |
| 689 |
self.assertEqual(cipher_name, u'TEST', msg="cipher name was not properly set") |
| 690 |
self.assertEqual(b_version, b"9.9", msg="version was not properly set") |
| 691 |
|
| 692 |
def test_parse_vaulttext_envelope_crlf(self): |
| 693 |
b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\r\nansible" |
| 694 |
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext) |
| 695 |
b_lines = b_ciphertext.split(b'\n') |
| 696 |
self.assertEqual(b_lines[0], b"ansible", msg="Payload was not properly split from the header") |
| 697 |
self.assertEqual(cipher_name, u'TEST', msg="cipher name was not properly set") |
| 698 |
self.assertEqual(b_version, b"9.9", msg="version was not properly set") |
| 699 |
|
| 700 |
def test_encrypt_decrypt_aes256(self): |
| 701 |
self.v.cipher_name = u'AES256' |
| 702 |
plaintext = u"foobar" |
| 703 |
b_vaulttext = self.v.encrypt(plaintext) |
| 704 |
b_plaintext = self.v.decrypt(b_vaulttext) |
| 705 |
self.assertNotEqual(b_vaulttext, b"foobar", msg="encryption failed") |
| 706 |
self.assertEqual(b_plaintext, b"foobar", msg="decryption failed") |
| 707 |
|
| 708 |
def test_encrypt_decrypt_aes256_none_secrets(self): |
| 709 |
vault_secrets = self._vault_secrets_from_password('default', 'ansible') |
| 710 |
v = vault.VaultLib(vault_secrets) |
| 711 |
|
| 712 |
plaintext = u"foobar" |
| 713 |
b_vaulttext = v.encrypt(plaintext) |
| 714 |
|
| 715 |
# VaultLib will default to empty {} if secrets is None |
| 716 |
v_none = vault.VaultLib(None) |
| 717 |
# so set secrets None explicitly |
| 718 |
v_none.secrets = None |
| 719 |
self.assertRaisesRegex(vault.AnsibleVaultError, |
| 720 |
'.*A vault password must be specified to decrypt data.*', |
| 721 |
v_none.decrypt, |
| 722 |
b_vaulttext) |
| 723 |
|
| 724 |
def test_encrypt_decrypt_aes256_empty_secrets(self): |
| 725 |
vault_secrets = self._vault_secrets_from_password('default', 'ansible') |
| 726 |
v = vault.VaultLib(vault_secrets) |
| 727 |
|
| 728 |
plaintext = u"foobar" |
| 729 |
b_vaulttext = v.encrypt(plaintext) |
| 730 |
|
| 731 |
vault_secrets_empty = [] |
| 732 |
v_none = vault.VaultLib(vault_secrets_empty) |
| 733 |
|
| 734 |
self.assertRaisesRegex(vault.AnsibleVaultError, |
| 735 |
'.*Attempting to decrypt but no vault secrets found.*', |
| 736 |
v_none.decrypt, |
| 737 |
b_vaulttext) |
| 738 |
|
| 739 |
def test_encrypt_decrypt_aes256_multiple_secrets_all_wrong(self): |
| 740 |
plaintext = u'Some text to encrypt in a café' |
| 741 |
b_vaulttext = self.v.encrypt(plaintext) |
| 742 |
|
| 743 |
vault_secrets = [('default', TextVaultSecret('another-wrong-password')), |
| 744 |
('wrong-password', TextVaultSecret('wrong-password'))] |
| 745 |
|
| 746 |
v_multi = vault.VaultLib(vault_secrets) |
| 747 |
with self.assertRaisesRegex(errors.AnsibleError, '.*Decryption failed.*'): |
| 748 |
v_multi.decrypt(b_vaulttext) |
| 749 |
|
| 750 |
def test_encrypt_decrypt_aes256_multiple_secrets_one_valid(self): |
| 751 |
plaintext = u'Some text to encrypt in a café' |
| 752 |
b_vaulttext = self.v.encrypt(plaintext) |
| 753 |
|
| 754 |
correct_secret = TextVaultSecret(self.vault_password) |
| 755 |
wrong_secret = TextVaultSecret('wrong-password') |
| 756 |
|
| 757 |
vault_secrets = [('default', wrong_secret), |
| 758 |
('corect_secret', correct_secret), |
| 759 |
('wrong_secret', wrong_secret)] |
| 760 |
|
| 761 |
v_multi = vault.VaultLib(vault_secrets) |
| 762 |
b_plaintext = v_multi.decrypt(b_vaulttext) |
| 763 |
self.assertNotEqual(b_vaulttext, to_bytes(plaintext), msg="encryption failed") |
| 764 |
self.assertEqual(b_plaintext, to_bytes(plaintext), msg="decryption failed") |
| 765 |
|
| 766 |
def test_encrypt_decrypt_aes256_existing_vault(self): |
| 767 |
self.v.cipher_name = u'AES256' |
| 768 |
b_orig_plaintext = b"Setec Astronomy" |
| 769 |
vaulttext = u"""$ANSIBLE_VAULT;1.1;AES256 |
| 770 |
33363965326261303234626463623963633531343539616138316433353830356566396130353436 |
| 771 |
3562643163366231316662386565383735653432386435610a306664636137376132643732393835 |
| 772 |
63383038383730306639353234326630666539346233376330303938323639306661313032396437 |
| 773 |
6233623062366136310a633866373936313238333730653739323461656662303864663666653563 |
| 774 |
3138""" |
| 775 |
|
| 776 |
b_plaintext = self.v.decrypt(vaulttext) |
| 777 |
self.assertEqual(b_plaintext, b_plaintext, msg="decryption failed") |
| 778 |
|
| 779 |
b_vaulttext = to_bytes(vaulttext, encoding='ascii', errors='strict') |
| 780 |
b_plaintext = self.v.decrypt(b_vaulttext) |
| 781 |
self.assertEqual(b_plaintext, b_orig_plaintext, msg="decryption failed") |
| 782 |
|
| 783 |
def test_decrypt_and_get_vault_id(self): |
| 784 |
b_expected_plaintext = to_bytes('foo bar\n') |
| 785 |
vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel |
| 786 |
65616435333934613466373335363332373764363365633035303466643439313864663837393234 |
| 787 |
3330656363343637313962633731333237313636633534630a386264363438363362326132363239 |
| 788 |
39363166646664346264383934393935653933316263333838386362633534326664646166663736 |
| 789 |
6462303664383765650a356637643633366663643566353036303162386237336233393065393164 |
| 790 |
6264""" |
| 791 |
|
| 792 |
vault_secrets = self._vault_secrets_from_password('ansible_devel', 'ansible') |
| 793 |
v = vault.VaultLib(vault_secrets) |
| 794 |
|
| 795 |
b_vaulttext = to_bytes(vaulttext) |
| 796 |
|
| 797 |
b_plaintext, vault_id_used, vault_secret_used = v.decrypt_and_get_vault_id(b_vaulttext) |
| 798 |
|
| 799 |
self.assertEqual(b_expected_plaintext, b_plaintext) |
| 800 |
self.assertEqual(vault_id_used, 'ansible_devel') |
| 801 |
self.assertEqual(vault_secret_used.text, 'ansible') |
| 802 |
|
| 803 |
def test_decrypt_non_default_1_2(self): |
| 804 |
b_expected_plaintext = to_bytes('foo bar\n') |
| 805 |
vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel |
| 806 |
65616435333934613466373335363332373764363365633035303466643439313864663837393234 |
| 807 |
3330656363343637313962633731333237313636633534630a386264363438363362326132363239 |
| 808 |
39363166646664346264383934393935653933316263333838386362633534326664646166663736 |
| 809 |
6462303664383765650a356637643633366663643566353036303162386237336233393065393164 |
| 810 |
6264""" |
| 811 |
|
| 812 |
vault_secrets = self._vault_secrets_from_password('default', 'ansible') |
| 813 |
v = vault.VaultLib(vault_secrets) |
| 814 |
|
| 815 |
b_vaulttext = to_bytes(vaulttext) |
| 816 |
|
| 817 |
b_plaintext = v.decrypt(b_vaulttext) |
| 818 |
self.assertEqual(b_expected_plaintext, b_plaintext) |
| 819 |
|
| 820 |
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext) |
| 821 |
self.assertEqual('ansible_devel', vault_id) |
| 822 |
self.assertEqual(b'1.2', b_version) |
| 823 |
|
| 824 |
def test_decrypt_decrypted(self): |
| 825 |
plaintext = u"ansible" |
| 826 |
self.assertRaises(errors.AnsibleError, self.v.decrypt, plaintext) |
| 827 |
|
| 828 |
b_plaintext = b"ansible" |
| 829 |
self.assertRaises(errors.AnsibleError, self.v.decrypt, b_plaintext) |
| 830 |
|
| 831 |
def test_cipher_not_set(self): |
| 832 |
plaintext = u"ansible" |
| 833 |
self.v.encrypt(plaintext) |
| 834 |
self.assertEqual(self.v.cipher_name, "AES256") |
| 835 |
|
| 836 |
|
| 837 |
def test_verify_encrypted_string_methods(): |
| 838 |
"""Verify all relevant methods on `str` are implemented on `EncryptedString`.""" |
| 839 |
str_methods_to_not_implement = { |
| 840 |
'__class__', |
| 841 |
'__dir__', |
| 842 |
'__getattribute__', # generated by Python, identical to the one on `str` in Python 3.13+, but different on earlier versions |
| 843 |
'__getnewargs__', |
| 844 |
'__getstate__', |
| 845 |
'__reduce__', |
| 846 |
'__reduce_ex__', |
| 847 |
} |
| 848 |
|
| 849 |
str_methods = set(dir('')) |
| 850 |
encrypted_string_methods = set(name for name in dir(EncryptedString) if name in str_methods and getattr(EncryptedString, name) is not getattr(str, name)) |
| 851 |
|
| 852 |
missing_methods = str_methods - encrypted_string_methods - str_methods_to_not_implement |
| 853 |
|
| 854 |
assert not missing_methods |
| 855 |
|
| 856 |
|
| 857 |
def test_vault_secrets_context_required(_zap_vault_secrets_context) -> None: |
| 858 |
with pytest.raises(ReferenceError, match=f"A required {VaultSecretsContext.__name__} context is not active."): |
| 859 |
VaultSecretsContext.current() |
| 860 |
|
| 861 |
|
| 862 |
def test_vault_secrets_context_optional(_zap_vault_secrets_context) -> None: |
| 863 |
assert VaultSecretsContext.current(optional=True) is None |
| 864 |
|
| 865 |
|
| 866 |
def test_vault_secrets_context_current(_zap_vault_secrets_context) -> None: |
| 867 |
ctx = VaultSecretsContext([]) |
| 868 |
|
| 869 |
VaultSecretsContext.initialize(ctx) |
| 870 |
|
| 871 |
assert VaultSecretsContext.current() is ctx |
| 872 |
|
| 873 |
|
| 874 |
def test_vault_secrets_context_already_initialized(_zap_vault_secrets_context) -> None: |
| 875 |
VaultSecretsContext.initialize(VaultSecretsContext([])) |
| 876 |
|
| 877 |
with pytest.raises(RuntimeError, match=f"The {VaultSecretsContext.__name__} context is already initialized."): |
| 878 |
VaultSecretsContext.initialize(VaultSecretsContext([])) |
| 879 |
|
| 880 |
|
| 881 |
def test_encrypted_string_unmanaged_access(_vault_secrets_context: VaultTestHelper) -> None: |
| 882 |
""" |
| 883 |
Validates that unmanaged access to an `EncryptedString`: |
| 884 |
* properly decrypts and caches the value when secrets are available |
| 885 |
* propagates Origin and VaultedValue tags |
| 886 |
""" |
| 887 |
plaintext = 'i am plaintext' |
| 888 |
encrypted_string = _vault_secrets_context.make_encrypted_string(plaintext) |
| 889 |
|
| 890 |
origin = Origin.get_required_tag(encrypted_string) |
| 891 |
vaulted_value_tag = VaultedValue(ciphertext=VaultHelper.get_ciphertext(encrypted_string, with_tags=False)) |
| 892 |
|
| 893 |
res1 = str(encrypted_string) |
| 894 |
res2 = str(encrypted_string) |
| 895 |
|
| 896 |
assert res1 == res2 == plaintext |
| 897 |
assert res1 is res2 # ensure the result is cached |
| 898 |
|
| 899 |
assert Origin.get_required_tag(res1) is origin |
| 900 |
assert VaultedValue.get_required_tag(res1).ciphertext == vaulted_value_tag.ciphertext |
| 901 |
|
| 902 |
|
| 903 |
def test_encrypted_string_unmanaged_access_fail(_vault_secrets_context: VaultTestHelper) -> None: |
| 904 |
"""Validates that unmanaged access to an `EncryptedString` fails with AnsibleVaultError when secrets are not available.""" |
| 905 |
encrypted_string = _vault_secrets_context.make_encrypted_string("i am plaintext") |
| 906 |
VaultSecretsContext.current().secrets = [] |
| 907 |
|
| 908 |
with pytest.raises(AnsibleVaultError): |
| 909 |
str(encrypted_string) |
| 910 |
|
| 911 |
|
| 912 |
@pytest.mark.parametrize( |
| 913 |
"value, conversion_func", ( |
| 914 |
("fourty-two", str), |
| 915 |
(42, int), |
| 916 |
(42.42, float), |
| 917 |
)) |
| 918 |
def test_encrypted_string_conversion_methods(value: t.Any, conversion_func: t.Callable, _vault_secrets_context: VaultTestHelper): |
| 919 |
"""Ensure that `EncryptedString` dunder conversion methods decrypt and pass through correctly.""" |
| 920 |
encrypted_string = _vault_secrets_context.make_encrypted_string(str(value)) |
| 921 |
|
| 922 |
converted = conversion_func(encrypted_string) |
| 923 |
|
| 924 |
assert converted == value |
| 925 |
|
| 926 |
|
| 927 |
def test_radd(_vault_secrets_context: VaultTestHelper) -> None: |
| 928 |
"""Ensure that the __radd__ dunder method decrypts and passes through.""" |
| 929 |
assert "plain string " + _vault_secrets_context.make_encrypted_string("secret string") == "plain string secret string" |
| 930 |
|
| 931 |
|
| 932 |
def make_marker(marker_type: type[Marker], *args, **kwargs): |
| 933 |
"""Utility function to create marker values under a TemplateContext.""" |
| 934 |
with TemplateContext(template_value="blah", templar=TemplateEngine(), options=TemplateOptions.DEFAULT): |
| 935 |
return marker_type(*args, **kwargs) |
| 936 |
|
| 937 |
|
| 938 |
origin = Origin(path="/test") |
| 939 |
|
| 940 |
|
| 941 |
@pytest.mark.parametrize("value, expected_ciphertext", ( |
| 942 |
(origin.tag(EncryptedString(ciphertext="ciphertext")), "ciphertext"), |
| 943 |
(origin.tag(VaultedValue(ciphertext="ciphertext").tag("something")), "ciphertext"), |
| 944 |
(make_marker(VaultExceptionMarker, ciphertext=origin.tag("ciphertext"), event=_messages.Event(msg="")), "ciphertext"), |
| 945 |
(make_marker(TruncationMarker), None), |
| 946 |
("not vaulted", None), |
| 947 |
)) |
| 948 |
def test_vaulthelper_get_ciphertext(value: t.Any, expected_ciphertext: str | None) -> None: |
| 949 |
"""Validate `get_ciphertext` helper responses and tag preservation behavior.""" |
| 950 |
expected_tags = {origin} if expected_ciphertext is not None else set() |
| 951 |
|
| 952 |
tagged_ciphertext = VaultHelper.get_ciphertext(value, with_tags=True) |
| 953 |
untagged_ciphertext = VaultHelper.get_ciphertext(value, with_tags=False) |
| 954 |
|
| 955 |
assert untagged_ciphertext == expected_ciphertext |
| 956 |
assert tagged_ciphertext == expected_ciphertext |
| 957 |
assert AnsibleTagHelper.tags(tagged_ciphertext) == expected_tags |
| 958 |
assert not AnsibleTagHelper.tags(untagged_ciphertext) |
| 959 |
|
| 960 |
|
| 961 |
@pytest.mark.parametrize("expression, expected_expression", ( |
| 962 |
("os.path.join(ed, efn)", "str(temp_file)"), |
| 963 |
("os.path.exists(ef)", "True"), |
| 964 |
("os.path.dirname(ef)", "str(temp_dir)"), |
| 965 |
("os.path.isdir(ed)", "True"), |
| 966 |
("os.path.basename(ef)", "temp_file.name"), |
| 967 |
("os.listdir(ed)", "[temp_file.name]"), |
| 968 |
("open(ef).read()", "'Ansible'"), |
| 969 |
)) |
| 970 |
def test_encrypted_string_path_fspath(_vault_secrets_context: VaultTestHelper, expression: str, expected_expression: str) -> None: |
| 971 |
"""Ensure that `EncryptedString` works with `PathLike` duck-typing consumers.""" |
| 972 |
with tempfile.TemporaryDirectory() as temp_dir_path: |
| 973 |
temp_dir = pathlib.Path(temp_dir_path) |
| 974 |
temp_file = (pathlib.Path(temp_dir) / 'temp_file') |
| 975 |
temp_file.write_text('Ansible') |
| 976 |
|
| 977 |
expression_locals = dict( |
| 978 |
temp_file=temp_file, |
| 979 |
temp_dir=temp_dir, |
| 980 |
ed=_vault_secrets_context.make_encrypted_string(str(temp_dir)), |
| 981 |
edn=_vault_secrets_context.make_encrypted_string(temp_dir.name), |
| 982 |
ef=_vault_secrets_context.make_encrypted_string(str(temp_file)), |
| 983 |
efn=_vault_secrets_context.make_encrypted_string(temp_file.name), |
| 984 |
) |
| 985 |
|
| 986 |
expected = eval(expected_expression, globals(), expression_locals) |
| 987 |
result = eval(expression, globals(), expression_locals) |
| 988 |
|
| 989 |
assert result == expected |
| 990 |
|
| 991 |
|
| 992 |
def test_protocol_conformance(_vault_secrets_context: VaultTestHelper) -> None: |
| 993 |
"""Verify that the `_EncryptedStringProtocol` defined by the collection loader is implemented.""" |
| 994 |
assert isinstance(_vault_secrets_context.make_encrypted_string("hey"), _EncryptedStringProtocol) |
| 995 |
|
| 996 |
|
| 997 |
def test_encrypted_string_cannot_be_trusted() -> None: |
| 998 |
"""Verify that `EncryptedString` cannot be trusted for templating.""" |
| 999 |
es = EncryptedString(ciphertext='x') |
| 1000 |
still_not_trusted = TrustedAsTemplate().tag(es) |
| 1001 |
|
| 1002 |
assert not TrustedAsTemplate.is_tagged_on(still_not_trusted) |