salt/tests/unit/modules/test_ssh.py

145 lines
5.7 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import tempfile
# Import Salt Testing Libs
2017-02-19 16:43:29 +00:00
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
from tests.support.mock import (
MagicMock,
2015-05-15 17:11:29 +00:00
NO_MOCK,
NO_MOCK_REASON,
patch
2015-05-15 17:11:29 +00:00
)
# Import Salt Libs
import salt.utils.files
Use explicit unicode strings + break up salt.utils This PR is part of what will be an ongoing effort to use explicit unicode strings in Salt. Because Python 3 does not suport Python 2's raw unicode string syntax (i.e. `ur'\d+'`), we must use `salt.utils.locales.sdecode()` to ensure that the raw string is unicode. However, because of how `salt/utils/__init__.py` has evolved into the hulking monstrosity it is today, this means importing a large module in places where it is not needed, which could negatively impact performance. For this reason, this PR also breaks out some of the functions from `salt/utils/__init__.py` into new/existing modules under `salt/utils/`. The long term goal will be that the modules within this directory do not depend on importing `salt.utils`. A summary of the changes in this PR is as follows: * Moves the following functions from `salt.utils` to new locations (including a deprecation warning if invoked from `salt.utils`): `to_bytes`, `to_str`, `to_unicode`, `str_to_num`, `is_quoted`, `dequote`, `is_hex`, `is_bin_str`, `rand_string`, `contains_whitespace`, `clean_kwargs`, `invalid_kwargs`, `which`, `which_bin`, `path_join`, `shlex_split`, `rand_str`, `is_windows`, `is_proxy`, `is_linux`, `is_darwin`, `is_sunos`, `is_smartos`, `is_smartos_globalzone`, `is_smartos_zone`, `is_freebsd`, `is_netbsd`, `is_openbsd`, `is_aix` * Moves the functions already deprecated by @rallytime to the bottom of `salt/utils/__init__.py` for better organization, so we can keep the deprecated ones separate from the ones yet to be deprecated as we continue to break up `salt.utils` * Updates `salt/*.py` and all files under `salt/client/` to use explicit unicode string literals. * Gets rid of implicit imports of `salt.utils` (e.g. `from salt.utils import foo` becomes `import salt.utils.foo as foo`). * Renames the `test.rand_str` function to `test.random_hash` to more accurately reflect what it does * Modifies `salt.utils.stringutils.random()` (née `salt.utils.rand_string()`) such that it returns a string matching the passed size. Previously this function would get `size` bytes from `os.urandom()`, base64-encode it, and return the result, which would in most cases not be equal to the passed size.
2017-07-25 01:47:15 +00:00
import salt.utils.platform
2017-02-19 16:43:29 +00:00
import salt.modules.ssh as ssh
2015-05-15 17:11:29 +00:00
from salt.exceptions import CommandExecutionError
2015-05-15 17:11:29 +00:00
@skipIf(NO_MOCK, NO_MOCK_REASON)
2017-02-19 16:43:29 +00:00
class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin):
2016-08-29 01:18:52 +00:00
'''
TestCase for salt.modules.ssh
'''
def setup_loader_modules(self):
2017-02-19 16:43:29 +00:00
return {
ssh: {
'__salt__': {
'user.info': lambda u: getattr(self, 'user_info_mock', None),
}
2017-02-19 16:43:29 +00:00
}
}
2017-02-19 16:43:29 +00:00
def tearDown(self):
try:
delattr(self, 'user_info_mock')
except AttributeError:
pass
def test_expand_user_token(self):
'''
2015-05-15 17:11:29 +00:00
Test if the %u, %h, and %% tokens are correctly expanded
'''
output = ssh._expand_authorized_keys_path('/home/%u', 'user',
'/home/user')
self.assertEqual(output, '/home/user')
output = ssh._expand_authorized_keys_path('/home/%h', 'user',
'/home/user')
self.assertEqual(output, '/home//home/user')
2016-02-11 19:49:15 +00:00
output = ssh._expand_authorized_keys_path('%h/foo', 'user',
'/home/user')
self.assertEqual(output, '/home/user/foo')
2015-05-15 11:00:11 +00:00
output = ssh._expand_authorized_keys_path('/srv/%h/aaa/%u%%', 'user',
'/home/user')
self.assertEqual(output, '/srv//home/user/aaa/user%')
2015-05-15 17:11:29 +00:00
user = 'dude'
home = '/home/dude'
path = '/home/dude%'
self.assertRaises(CommandExecutionError, ssh._expand_authorized_keys_path, path, user, home)
path = '/home/%dude'
self.assertRaises(CommandExecutionError, ssh._expand_authorized_keys_path, path, user, home)
def test_set_auth_key_invalid(self):
self.user_info_mock = {'home': '/dev/null'}
# Inserting invalid public key should be rejected
2016-08-29 01:18:52 +00:00
invalid_key = 'AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY' # missing padding
self.assertEqual(ssh.set_auth_key('user', invalid_key), 'Invalid public key')
def test_replace_auth_key(self):
'''
Test the _replace_auth_key with some different authorized_keys examples
'''
# First test a known working example, gathered from the authorized_keys file
# in the integration test files.
enc = 'ssh-rsa'
key = 'AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+' \
'PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNl' \
'GEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWp' \
'XLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal' \
'72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi' \
'/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ=='
options = 'command="/usr/local/lib/ssh-helper"'
email = 'github.com'
empty_line = '\n'
comment_line = '# this is a comment\n'
# Write out the authorized key to a temporary file
2018-04-26 19:52:08 +00:00
temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w+')
temp_file.close()
with salt.utils.files.fopen(temp_file.name, 'w') as _fh:
# Add comment
_fh.write(comment_line)
# Add empty line for #41335
_fh.write(empty_line)
_fh.write('{0} {1} {2} {3}'.format(options, enc, key, email))
with patch.dict(ssh.__salt__, {'user.info': MagicMock(return_value={})}):
with patch('salt.modules.ssh._get_config_file', MagicMock(return_value=temp_file.name)):
ssh._replace_auth_key('foo', key, config=temp_file.name)
# The previous authorized key should have been replaced by the simpler one
with salt.utils.files.fopen(temp_file.name) as _fh:
file_txt = salt.utils.stringutils.to_unicode(_fh.read())
self.assertIn(enc, file_txt)
self.assertIn(key, file_txt)
self.assertNotIn(options, file_txt)
self.assertNotIn(email, file_txt)
# Now test a very simple key using ecdsa instead of ssh-rsa and with multiple options
enc = 'ecdsa-sha2-nistp256'
key = 'abcxyz'
with salt.utils.files.fopen(temp_file.name, 'a') as _fh:
_fh.write(salt.utils.stringutils.to_str('{0} {1}'.format(enc, key)))
# Replace the simple key from before with the more complicated options + new email
# Option example is taken from Pull Request #39855
options = ['no-port-forwarding', 'no-agent-forwarding', 'no-X11-forwarding',
'command="echo \'Please login as the user \"ubuntu\" rather than the user \"root\".\'']
email = 'foo@example.com'
with patch.dict(ssh.__salt__, {'user.info': MagicMock(return_value={})}):
with patch('salt.modules.ssh._get_config_file', MagicMock(return_value=temp_file.name)):
2017-03-28 23:12:56 +00:00
ssh._replace_auth_key('foo', key, enc=enc, comment=email, options=options, config=temp_file.name)
# Assert that the new line was added as-is to the file
with salt.utils.files.fopen(temp_file.name) as _fh:
file_txt = salt.utils.stringutils.to_unicode(_fh.read())
self.assertIn(enc, file_txt)
self.assertIn(key, file_txt)
self.assertIn('{0} '.format(','.join(options)), file_txt)
self.assertIn(email, file_txt)
self.assertIn(empty_line, file_txt)
self.assertIn(comment_line, file_txt)