1# Copyright 2016 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
5from autotest_lib.client.common_lib import error
6from autotest_lib.client.cros.enterprise import enterprise_policy_base
7
8
9class policy_CookiesSessionOnlyForUrls(
10        enterprise_policy_base.EnterprisePolicyTest):
11    """
12    Test effect of CookiesSessionOnlyForUrls policy on Chrome OS.
13
14    The test verifies ChromeOS behaviour and appearance for a set of valid
15    values of the CookiesSessionOnlyForUrls user policy, when user policy
16    DefaultCookiesSetting=2 (block cookies for all URLs). Generally, cookies
17    shall not be stored for any visted page, except for those whose domain
18    matches an URL pattern specified in CookiesSessionOnlyForUrls. Also,
19    these URL patterns shall have their behavior set to 'Clear on exit',
20    indicating that they are marked for deletion when Chrome exits.
21
22    If the policy value Not set, then no visited page is allowed to store
23    cookies. In the same way, if the URL of the visited page is not listed in
24    the policy, then the visted page is not allowed to store cookies. If the
25    URL of the visited page is listed in the policy, then the page is allowed
26    to store cookies for the current session only. The corresponding test
27    cases are NotSet_Block, UrlNotIn_Block, and UrlIsIn_Allow.
28
29    Note that this test does not verify that cookies set to 'Clear on exit'
30    are actually deleted when the session ends. That functionality is tested
31    by the Chrome team.
32
33    """
34    version = 1
35
36    def initialize(self, **kwargs):
37        """Initialize this test."""
38        self._initialize_test_constants()
39        super(policy_CookiesSessionOnlyForUrls, self).initialize(**kwargs)
40        self.start_webserver()
41
42
43    def _initialize_test_constants(self):
44        """Initialize test-specific constants, some from class constants."""
45        self.POLICY_NAME = 'CookiesSessionOnlyForUrls'
46        self.COOKIE_NAME = 'cookie1'
47        self.TEST_FILE = 'cookie_status.html'
48        self.TEST_URL = '%s/%s' % (self.WEB_HOST, self.TEST_FILE)
49        self.COOKIE_EXCEPTIONS_PAGE = (
50            'chrome://settings-frame/contentExceptions#cookies')
51        self.COOKIE_ALLOWED_MULTIPLE_URLS = ['https://testingwebsite.html',
52                                             self.WEB_HOST,
53                                             'http://doesnotmatter.com']
54        self.COOKIE_BLOCKED_MULTIPLE_URLS = ['https://testingwebsite.html',
55                                             'https://somewebsite.com',
56                                             'http://doesnotmatter.com']
57        self.TEST_CASES = {
58            'UrlIsIn_Allow': self.COOKIE_ALLOWED_MULTIPLE_URLS,
59            'UrlNotIn_Block': self.COOKIE_BLOCKED_MULTIPLE_URLS,
60            'NotSet_Block': None
61        }
62        self.SUPPORTING_POLICIES = {'DefaultCookiesSetting': 2}
63
64
65    def _is_cookie_blocked(self, url):
66        """
67        Return True if cookie is blocked for the URL, else return False.
68
69        @param url: URL of the page to load.
70
71        """
72        tab = self.navigate_to_url(url)
73        cookie_value = tab.GetCookieByName(self.COOKIE_NAME)
74        tab.Close()
75        return cookie_value is None
76
77
78    def _is_cookie_clear_on_exit(self, url):
79        """
80        Return True if cookie for |url| has behavior set to 'Clear on exit'.
81
82        @param url: string url pattern for cookie exception.
83        @returns: True if cookie behavior is set to 'Clear on exit'.
84        """
85        js_cmd = ('''
86          var exception_area=document.getElementById('content-settings-exceptions-area');
87          var contents=exception_area.getElementsByClassName('content-area')[0];
88          var contents_children = contents.children;
89          var cookie_idx = -1;
90          var cookie_behavior = '';
91          for (var i=0; i<contents_children.length; i++) {
92            var content = contents_children[i];
93            var type = content.getAttribute('contenttype');
94            if (type == 'cookies') {
95              var cookie_items = content.getElementsByClassName('deletable-item');
96              for (var j=0; j<cookie_items.length; j++) {
97                var cookie_item = cookie_items[j];
98                var cookie_pattern = cookie_item.getElementsByClassName('exception-pattern')[0];
99                var pattern = cookie_pattern.innerText.trim();
100                var cookie_setting = cookie_item.getElementsByClassName('exception-setting')[0];
101                var setting = cookie_setting.innerText.trim();
102                if (pattern == '%s') {
103                  cookie_idx = j;
104                  cookie_behavior = setting;
105                  break;
106                }
107              }
108              break;
109            }
110            if (cookie_idx >= 0) { break; }
111          }
112          cookie_behavior;
113        ''' % url)
114        tab = self.navigate_to_url(self.COOKIE_EXCEPTIONS_PAGE)
115        cookie_behavior = self.get_elements_from_page(tab, js_cmd)
116        tab.Close()
117        return cookie_behavior == 'Clear on exit'
118
119
120    def _test_cookies_allowed_for_urls(self, policy_value):
121        """
122        Verify CrOS enforces CookiesSessionOnlyForUrls policy value.
123
124        When CookiesSessionOnlyForUrls policy is set to a list of one or more
125        more urls, verify that cookies are allowed for a page that matches a
126        URL pattern in the list, but are blocked for a page whose URL pattern
127        is not in the list. When set to None, verify that cookies are
128        blocked for all URLs.
129
130        @param policy_value: policy value expected.
131
132        @raises: TestFail if cookies are blocked/not blocked based on the
133                 policy value.
134
135        """
136        cookie_is_blocked = self._is_cookie_blocked(self.TEST_URL)
137        if policy_value and self.WEB_HOST in policy_value:
138            if cookie_is_blocked:
139                raise error.TestFail('Cookie should be allowed.')
140        else:
141            if not cookie_is_blocked:
142                raise error.TestFail('Cookie should be blocked.')
143
144        cookie_is_clear_on_exit = self._is_cookie_clear_on_exit(self.WEB_HOST)
145        if policy_value and self.WEB_HOST in policy_value:
146            if not cookie_is_clear_on_exit:
147                raise error.TestFail('Cookie should be Clear on exit.')
148        else:
149            if cookie_is_clear_on_exit:
150                raise error.TestFail('Cookie should not be Clear on exit.')
151
152
153    def run_once(self, case):
154        """
155        Setup and run the test configured for the specified test case.
156
157        @param case: Name of the test case to run.
158
159        """
160        case_value = self.TEST_CASES[case]
161        self.SUPPORTING_POLICIES[self.POLICY_NAME] = case_value
162        self.setup_case(user_policies=self.SUPPORTING_POLICIES)
163        self._test_cookies_allowed_for_urls(case_value)
164