1# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import dbus, logging, os, pwd
6
7from autotest_lib.client.bin import test, utils
8from autotest_lib.client.common_lib import error
9from autotest_lib.client.cros import constants
10
11class security_EnableChromeTesting(test.test):
12    version = 1
13
14    def _set_user(self, username):
15        user_info = pwd.getpwnam(username)
16        os.setegid(user_info[3])
17        os.seteuid(user_info[2])
18        self._set_user_environment(username)
19
20    def _reset_user(self):
21        uid = os.getuid()
22        username = pwd.getpwuid(uid)[0]
23        os.seteuid(uid)
24        os.setegid(os.getgid())
25        self._set_user_environment(username)
26
27    def _set_user_environment(self, username):
28        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
29            if name in os.environ:
30                os.environ[name] = username
31
32    def _ps(self, proc=constants.BROWSER):
33        pscmd = 'ps -C %s -o pid --no-header | head -1' % proc
34        return utils.system_output(pscmd)
35
36    def run_once(self):
37        self._set_user('chronos')
38
39        bus = dbus.SystemBus()
40        proxy = bus.get_object('org.chromium.SessionManager',
41                               '/org/chromium/SessionManager')
42        session_manager = dbus.Interface(proxy,
43                                         'org.chromium.SessionManagerInterface')
44
45        chrome_pid = self._ps()
46
47        # Try DBus call and make sure it fails.
48        try:
49            # DBus cannot infer the type of an empty Python list.
50            # Pass an empty dbus.Array with the correct signature, taken from
51            # platform/login_manager/org.chromium.SessionManagerInterface.xml.
52            empty_string_array = dbus.Array(signature="as")
53            session_manager.EnableChromeTesting(True, empty_string_array)
54        except dbus.exceptions.DBusException as dbe:
55            logging.error(dbe)
56        else:
57            raise error.TestFail('DBus EnableChromeTesting call '
58                                 'succeeded when it should fail.')
59
60        # Make sure Chrome didn't restart.
61        if chrome_pid != self._ps():
62            raise error.TestFail('Chrome restarted during test.')
63
64        self._reset_user()
65