Fix password lookup rewrites file when using encrypt (#79431)

* Remove unused mock from test_password_already_created_encrypt

The _get_paths mock is never used in the
test_password_already_created_encrypt test case.

* Add test to assert the password file is not rewritten

If the password file already contains the salt and the hasing algorithm
does not use the ident parameter, the password lookup should not write
to the password file.

* Fix "changed" if using "encrypt" in password lookup

When using the "encrypt" parameter to the password lookup without the
ident parameter, the password file was always marked as "changed". This
caused the file to be rewritten with the same content. This is fixed by
only marking the file as changed, if an "ident" value needs to be added
to the file.

Fixes #79430.

Add changelog entry
pull/56508/merge
Gaudenz Steinlin 2 years ago committed by GitHub
parent 3936b5c471
commit c33a782a9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,2 @@
bugfixes:
- Fixes the password lookup to not rewrite files if they are not changed when using the "encrypt" parameter (#79430).

@ -366,11 +366,12 @@ class LookupModule(LookupBase):
ident = params['ident']
if encrypt and not ident:
changed = True
try:
ident = BaseHash.algorithms[encrypt].implicit_ident
except KeyError:
ident = None
if ident:
changed = True
if changed and b_path != to_bytes('/dev/null'):
content = _format_content(plaintext_password, salt, encrypt=encrypt, ident=ident)

@ -520,10 +520,8 @@ class TestLookupModuleWithPasslib(BaseTestLookupModule):
self.assertEqual(int(str_parts[2]), crypt_parts['rounds'])
self.assertIsInstance(result, text_type)
@patch.object(PluginLoader, '_get_paths')
@patch('ansible.plugins.lookup.password._write_password_file')
def test_password_already_created_encrypt(self, mock_get_paths, mock_write_file):
mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three']
def test_password_already_created_encrypt(self, mock_write_file):
password.os.path.exists = lambda x: x == to_bytes('/path/to/somewhere')
with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m:
@ -531,6 +529,9 @@ class TestLookupModuleWithPasslib(BaseTestLookupModule):
for result in results:
self.assertEqual(result, u'$pbkdf2-sha256$20000$ODc2NTQzMjE$Uikde0cv0BKaRaAXMrUQB.zvG4GmnjClwjghwIRf2gU')
# Assert the password file is not rewritten
mock_write_file.assert_not_called()
@pytest.mark.skipif(passlib is None, reason='passlib must be installed to run these tests')
class TestLookupModuleWithPasslibWrappedAlgo(BaseTestLookupModule):

Loading…
Cancel
Save