Example #1
0
def test_os_environment_remains_intact():
    """
    Make sure the OS environment is not tainted after running a command
    that specifies runas.
    """
    with patch("pwd.getpwnam") as getpwnam_mock:
        with patch("subprocess.Popen") as popen_mock:
            environment = os.environ.copy()

            popen_mock.return_value = Mock(
                communicate=lambda *args, **kwags: [b"", None],
                pid=lambda: 1,
                retcode=0,
            )

            with patch.dict(cmdmod.__grains__, {
                    "os": "Darwin",
                    "os_family": "Solaris"
            }):
                if sys.platform.startswith(("freebsd", "openbsd")):
                    shell = "/bin/sh"
                else:
                    shell = "/bin/bash"

                cmdmod._run("ls",
                            cwd=tempfile.gettempdir(),
                            runas="foobar",
                            shell=shell)

                environment2 = os.environ.copy()

                assert environment == environment2

                if not salt.utils.platform.is_darwin():
                    getpwnam_mock.assert_called_with("foobar")
Example #2
0
    def test_os_environment_remains_intact(self):
        '''
        Make sure the OS environment is not tainted after running a command
        that specifies runas.
        '''
        with patch('pwd.getpwnam') as getpwnam_mock:
            with patch('subprocess.Popen') as popen_mock:
                environment = os.environ.copy()

                popen_mock.return_value = Mock(
                    communicate=lambda *args, **kwags: [b'', None],
                    pid=lambda: 1,
                    retcode=0
                )

                with patch.dict(cmdmod.__grains__, {'os': 'Darwin', 'os_family': 'Solaris'}):
                    if sys.platform.startswith(('freebsd', 'openbsd')):
                        shell = '/bin/sh'
                    else:
                        shell = '/bin/bash'

                    cmdmod._run('ls',
                                cwd=tempfile.gettempdir(),
                                runas='foobar',
                                shell=shell)

                    environment2 = os.environ.copy()

                    self.assertEqual(environment, environment2)

                    getpwnam_mock.assert_called_with('foobar')
Example #3
0
    def test_os_environment_remains_intact(self, popen_mock, getpwnam_mock):
        '''
        Make sure the OS environment is not tainted after running a command
        that specifies runas.
        '''
        environment = os.environ.copy()

        popen_mock.return_value = Mock(
            communicate=lambda *args, **kwags: ['{}', None],
            pid=lambda: 1,
            retcode=0)

        from salt.modules import cmdmod

        cmdmod.__grains__ = {'os': 'darwin'}
        if sys.platform.startswith(('freebsd', 'openbsd')):
            shell = '/bin/sh'
        else:
            shell = '/bin/bash'

        try:
            cmdmod._run('ls',
                        cwd=tempfile.gettempdir(),
                        runas='foobar',
                        shell=shell)

            environment2 = os.environ.copy()

            self.assertEqual(environment, environment2)

            getpwnam_mock.assert_called_with('foobar')
        finally:
            delattr(cmdmod, '__grains__')
Example #4
0
    def test_os_environment_remains_intact(self, popen_mock, getpwnam_mock):
        """
        Make sure the OS environment is not tainted after running a command
        that specifies runas.
        """
        environment = os.environ.copy()

        popen_mock.return_value = Mock(communicate=lambda *args, **kwags: ["{}", None], pid=lambda: 1, retcode=0)

        from salt.modules import cmdmod

        cmdmod.__grains__ = {"os": "Darwin", "os_family": "Solaris"}
        if sys.platform.startswith(("freebsd", "openbsd")):
            shell = "/bin/sh"
        else:
            shell = "/bin/bash"

        try:
            cmdmod._run("ls", cwd=tempfile.gettempdir(), runas="foobar", shell=shell)

            environment2 = os.environ.copy()

            self.assertEqual(environment, environment2)

            getpwnam_mock.assert_called_with("foobar")
        finally:
            delattr(cmdmod, "__grains__")
Example #5
0
def test_run_user_not_available():
    """
    Tests return when runas user is not available
    """
    mock_true = MagicMock(return_value=True)
    with patch("salt.modules.cmdmod._is_valid_shell", mock_true):
        with patch("os.path.isfile", mock_true):
            with patch("os.access", mock_true):
                with pytest.raises(CommandExecutionError):
                    cmdmod._run("foo", "bar", runas="baz")
Example #6
0
def test_run_with_tuple():
    """
    Tests return when cmd is a tuple
    """
    mock_true = MagicMock(return_value=True)
    with patch("salt.modules.cmdmod._is_valid_shell", mock_true):
        with patch("salt.utils.platform.is_windows",
                   MagicMock(return_value=False)):
            with patch("os.path.isfile", mock_true):
                with patch("os.access", mock_true):
                    cmdmod._run(("echo", "foo"), python_shell=True, cwd="/")
Example #7
0
def test_run_shell_is_not_file():
    """
    Tests error raised when shell is not available after _is_valid_shell error msg
    and os.path.isfile returns False
    """
    with patch("salt.modules.cmdmod._is_valid_shell",
               MagicMock(return_value=True)):
        with patch("salt.utils.platform.is_windows",
                   MagicMock(return_value=False)):
            with patch("os.path.isfile", MagicMock(return_value=False)):
                with pytest.raises(CommandExecutionError):
                    cmdmod._run("foo", "bar")
Example #8
0
def test_run_zero_umask():
    """
    Tests error raised when umask is set to zero
    """
    with patch("salt.modules.cmdmod._is_valid_shell",
               MagicMock(return_value=True)):
        with patch("salt.utils.platform.is_windows",
                   MagicMock(return_value=False)):
            with patch("os.path.isfile", MagicMock(return_value=True)):
                with patch("os.access", MagicMock(return_value=True)):
                    with pytest.raises(CommandExecutionError):
                        cmdmod._run("foo", "bar", umask=0)
Example #9
0
def test_run_invalid_cwd_not_abs_path():
    """
    Tests error raised when cwd is not an absolute path
    """
    with patch("salt.modules.cmdmod._is_valid_shell",
               MagicMock(return_value=True)):
        with patch("salt.utils.platform.is_windows",
                   MagicMock(return_value=False)):
            with patch("os.path.isfile", MagicMock(return_value=True)):
                with patch("os.access", MagicMock(return_value=True)):
                    with pytest.raises(CommandExecutionError):
                        cmdmod._run("foo", "bar")
Example #10
0
def test_run_runas_with_windows():
    """
    Tests error raised when runas is passed on windows
    """
    with patch("salt.modules.cmdmod._is_valid_shell",
               MagicMock(return_value=True)):
        with patch("salt.utils.platform.is_windows",
                   MagicMock(return_value=True)):
            with patch("salt.utils.win_chcp.get_codepage_id",
                       MagicMock(return_value=65001)):
                with patch.dict(cmdmod.__grains__, {"os": "fake_os"}):
                    with pytest.raises(CommandExecutionError):
                        cmdmod._run("foo", "bar", runas="baz")
Example #11
0
 def test_run(self):
     '''
     Tests end result when a command is not found
     '''
     with patch('salt.modules.cmdmod._is_valid_shell', MagicMock(return_value=True)):
         with patch('salt.utils.platform.is_windows', MagicMock(return_value=False)):
             with patch('os.path.isfile', MagicMock(return_value=True)):
                 with patch('os.access', MagicMock(return_value=True)):
                     ret = cmdmod._run('foo', cwd=os.getcwd(), use_vt=True).get('stderr')
                     self.assertIn('foo', ret)
Example #12
0
    def test_run_cwd_in_combination_with_runas(self):
        """
        cmd.run executes command in the cwd directory
        when the runas parameter is specified
        """
        cmd = "pwd"
        cwd = "/tmp"
        runas = os.getlogin()

        with patch.dict(cmdmod.__grains__, {"os": "Darwin", "os_family": "Solaris"}):
            stdout = cmdmod._run(cmd, cwd=cwd, runas=runas).get("stdout")
        self.assertEqual(stdout, cwd)
Example #13
0
 def test_run(self):
     """
     Tests end result when a command is not found
     """
     with patch("salt.modules.cmdmod._is_valid_shell", MagicMock(return_value=True)):
         with patch("salt.utils.platform.is_windows", MagicMock(return_value=False)):
             with patch("os.path.isfile", MagicMock(return_value=True)):
                 with patch("os.access", MagicMock(return_value=True)):
                     ret = cmdmod._run("foo", cwd=os.getcwd(), use_vt=True).get(
                         "stderr"
                     )
                     self.assertIn("foo", ret)
Example #14
0
    def test_os_environment_remains_intact(self,
                                           loads_mock,
                                           popen_mock,
                                           getpwnam_mock):
        '''
        Make sure the OS environment is not tainted after running a command
        that specifies runas.
        '''
        environment = os.environ.copy()

        popen_mock.return_value = Mock(
            communicate=lambda *args, **kwags: ['{}', None],
            pid=lambda: 1,
            retcode=0
        )

        loads_mock.return_value = {'data': {'USER': '******'}}

        from salt.modules import cmdmod

        cmdmod.__grains__ = {'os': 'darwin'}
        if sys.platform.startswith('freebsd'):
            shell = '/bin/sh'
        else:
            shell = '/bin/bash'

        try:
            cmdmod._run('ls',
                        cwd=tempfile.gettempdir(),
                        runas='foobar',
                        shell=shell)

            environment2 = os.environ.copy()

            self.assertEqual(environment, environment2)

            getpwnam_mock.assert_called_with('foobar')
            loads_mock.assert_called_with('{}')
        finally:
            delattr(cmdmod, '__grains__')
Example #15
0
def test_os_environment_do_not_pass_notify_socket():
    """
    Make sure NOTIFY_SOCKET environment variable is not passed
    to the command if not explicitly set with env parameter.
    """
    with patch("pwd.getpwnam") as getpwnam_mock:
        new_env = os.environ.copy()
        new_env.update({"NOTIFY_SOCKET": "/run/systemd/notify"})
        with patch("subprocess.Popen") as popen_mock, patch(
                "os.environ.copy", return_value=new_env):
            popen_mock.return_value = Mock(
                communicate=lambda *args, **kwags: [b"", None],
                pid=lambda: 1,
                retcode=0,
            )

            with patch.dict(cmdmod.__grains__, {
                    "os": "SUSE",
                    "os_family": "Suse"
            }):
                if sys.platform.startswith(("freebsd", "openbsd")):
                    shell = "/bin/sh"
                else:
                    shell = "/bin/bash"

                cmdmod._run("ls", cwd=tempfile.gettempdir(), shell=shell)

                assert "NOTIFY_SOCKET" not in popen_mock.call_args_list[0][1][
                    "env"]

                cmdmod._run(
                    "ls",
                    cwd=tempfile.gettempdir(),
                    shell=shell,
                    env={"NOTIFY_SOCKET": "/run/systemd/notify.new"},
                )

                assert (popen_mock.call_args_list[1][1]["env"]["NOTIFY_SOCKET"]
                        == "/run/systemd/notify.new")
Example #16
0
    def test_run_cwd_in_combination_with_runas(self):
        '''
        cmd.run executes command in the cwd directory
        when the runas parameter is specified
        '''
        cmd = 'pwd'
        cwd = '/tmp'
        runas = 'foobar'

        with patch('pwd.getpwnam') as getpwnam_mock, \
                patch.dict(cmdmod.__grains__, {'os': 'Darwin', 'os_family': 'Solaris'}):
            stdout = cmdmod._run(cmd, cwd=cwd, runas=runas).get('stdout')
        self.assertEqual(stdout, cwd)
Example #17
0
 def test_run(self):
     '''
     Tests end result when a command is not found
     '''
     ret = cmdmod._run('foo', use_vt=True).get('stderr')
     self.assertIn('foo', ret)
Example #18
0
 def test_run(self):
     '''
     Tests end result when a command is not found
     '''
     ret = cmdmod._run('foo', use_vt=True).get('stderr')
     self.assertIn('foo', ret)
Example #19
0
    def test_shell_properly_handled_on_macOS(self):
        '''
        cmd.run should invoke a new bash login only
        when bash is the default shell for the selected user
        '''
        class _CommandHandler(object):
            '''
            Class for capturing cmd
            '''
            def __init__(self):
                self.cmd = None

            def clear(self):
                self.cmd = None

        cmd_handler = _CommandHandler()

        def mock_proc(__cmd__, **kwargs):
            cmd_handler.cmd = ' '.join(__cmd__)
            return MagicMock(
                return_value=MockTimedProc(stdout=None, stderr=None))

        with patch('pwd.getpwnam') as getpwnam_mock:
            with patch('salt.utils.timed_subprocess.TimedProc', mock_proc):

                # User default shell is '/usr/local/bin/bash'
                user_default_shell = '/usr/local/bin/bash'
                with patch.dict(
                        cmdmod.__salt__,
                    {
                        'user.info':
                        MagicMock(return_value={'shell': user_default_shell})
                    }):

                    cmd_handler.clear()
                    cmdmod._run('ls',
                                cwd=tempfile.gettempdir(),
                                runas='foobar',
                                use_vt=False)

                    self.assertRegex(
                        cmd_handler.cmd, "{} -l -c".format(user_default_shell),
                        "cmd invokes right bash session on macOS")

                # User default shell is '/bin/zsh'
                user_default_shell = '/bin/zsh'
                with patch.dict(
                        cmdmod.__salt__,
                    {
                        'user.info':
                        MagicMock(return_value={'shell': user_default_shell})
                    }):

                    cmd_handler.clear()
                    cmdmod._run('ls',
                                cwd=tempfile.gettempdir(),
                                runas='foobar',
                                use_vt=False)

                    self.assertNotRegex(
                        cmd_handler.cmd, "bash -l -c",
                        "cmd does not invoke user shell on macOS")
Example #20
0
def test_shell_properly_handled_on_macOS():
    """
    cmd.run should invoke a new bash login only
    when bash is the default shell for the selected user
    """
    class _CommandHandler:
        """
        Class for capturing cmd
        """
        def __init__(self):
            self.cmd = None

        def clear(self):
            self.cmd = None

    cmd_handler = _CommandHandler()

    def mock_proc(__cmd__, **kwargs):
        cmd_handler.cmd = " ".join(__cmd__)
        return MagicMock(return_value=MockTimedProc(stdout=None, stderr=None))

    with patch("pwd.getpwnam") as getpwnam_mock:
        with patch("salt.utils.timed_subprocess.TimedProc", mock_proc):

            # User default shell is '/usr/local/bin/bash'
            user_default_shell = "/usr/local/bin/bash"
            with patch.dict(
                    cmdmod.__salt__,
                {
                    "user.info":
                    MagicMock(return_value={"shell": user_default_shell})
                },
            ):

                cmd_handler.clear()
                cmdmod._run("ls",
                            cwd=tempfile.gettempdir(),
                            runas="foobar",
                            use_vt=False)

                assert re.search(
                    "{} -l -c".format(user_default_shell),
                    cmd_handler.cmd), "cmd invokes right bash session on macOS"

            # User default shell is '/bin/zsh'
            user_default_shell = "/bin/zsh"
            with patch.dict(
                    cmdmod.__salt__,
                {
                    "user.info":
                    MagicMock(return_value={"shell": user_default_shell})
                },
            ):

                cmd_handler.clear()
                cmdmod._run("ls",
                            cwd=tempfile.gettempdir(),
                            runas="foobar",
                            use_vt=False)

                assert not re.search(
                    "bash -l -c",
                    cmd_handler.cmd), "cmd does not invoke user shell on macOS"
 def test_run(self):
     """
     Tests end result when a command is not found
     """
     ret = cmdmod._run("foo").get("stderr")
     self.assertIn("foo", ret)