summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/services/eip/tests/test_eipbootstrapper.py
blob: 6640a8606a6eed613333275aabdf31bf1f2c7ed7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# -*- coding: utf-8 -*-
# test_eipbootstrapper.py
# Copyright (C) 2013 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.


"""
Tests for the EIP Boostrapper checks

These will be whitebox tests since we want to make sure the private
implementation is checking what we expect.
"""

import os
import mock
import tempfile
import time
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from nose.twistedtools import deferred, reactor
from twisted.internet import threads
from requests.models import Response

from leap.bitmask.services.eip.eipbootstrapper import EIPBootstrapper
from leap.bitmask.services.eip.eipconfig import EIPConfig
from leap.bitmask.config.providerconfig import ProviderConfig
from leap.bitmask.crypto.tests import fake_provider
from leap.bitmask.crypto.srpauth import SRPAuth
from leap.bitmask import util
from leap.common.testing.basetest import BaseLeapTest
from leap.common.files import mkdir_p


class EIPBootstrapperActiveTest(BaseLeapTest):
    @classmethod
    def setUpClass(cls):
        BaseLeapTest.setUpClass()
        factory = fake_provider.get_provider_factory()
        http = reactor.listenTCP(0, factory)
        https = reactor.listenSSL(
            0, factory,
            fake_provider.OpenSSLServerContextFactory())
        get_port = lambda p: p.getHost().port
        cls.http_port = get_port(http)
        cls.https_port = get_port(https)

    def setUp(self):
        self.eb = EIPBootstrapper()
        self.old_pp = util.get_path_prefix
        self.old_save = EIPConfig.save
        self.old_load = EIPConfig.load
        self.old_si = SRPAuth.get_session_id

    def tearDown(self):
        util.get_path_prefix = self.old_pp
        EIPConfig.save = self.old_save
        EIPConfig.load = self.old_load
        SRPAuth.get_session_id = self.old_si

    def _download_config_test_template(self, ifneeded, new):
        """
        All download config tests have the same structure, so this is
        a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param new: if True uses time.time() as mtime for the mocked
                    eip-service file, otherwise it uses 100 (a really
                    old mtime)
        :type new: float or int (will be coersed)
        """
        pc = ProviderConfig()
        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        self.eb._provider_config = pc

        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")

        # This is to ignore https checking, since it's not the point
        # of this test
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    pc.get_domain())
        mkdir_p(provider_dir)
        eip_config_path = os.path.join(provider_dir,
                                       "eip-service.json")

        with open(eip_config_path, "w") as ec:
            ec.write("A")

        # set mtime to something really new
        if new:
            os.utime(eip_config_path, (-1, time.time()))
        else:
            os.utime(eip_config_path, (-1, 100))

    @deferred()
    def test_download_config_not_modified(self):
        self._download_config_test_template(True, True)

        d = threads.deferToThread(self.eb._download_config)

        def check(*args):
            self.assertFalse(self.eb._eip_config.save.called)
        d.addCallback(check)
        return d

    @deferred()
    def test_download_config_modified(self):
        self._download_config_test_template(True, False)

        d = threads.deferToThread(self.eb._download_config)

        def check(*args):
            self.assertTrue(self.eb._eip_config.save.called)
        d.addCallback(check)
        return d

    @deferred()
    def test_download_config_ignores_mtime(self):
        self._download_config_test_template(False, True)

        d = threads.deferToThread(self.eb._download_config)

        def check(*args):
            self.eb._eip_config.save.assert_called_once_with(
                ("leap",
                 "providers",
                 self.eb._provider_config.get_domain(),
                 "eip-service.json"))
        d.addCallback(check)
        return d

    def _download_certificate_test_template(self, ifneeded, createcert):
        """
        All download client certificate tests have the same structure,
        so this is a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param createcert: if True it creates a dummy file to play the
                           part of a downloaded certificate
        :type createcert: bool

        :returns: the temp eip cert path and the dummy cert contents
        :rtype: tuple of str, str
        """
        pc = ProviderConfig()
        ec = EIPConfig()
        self.eb._provider_config = pc
        self.eb._eip_config = ec

        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    "somedomain")
        mkdir_p(provider_dir)
        eip_cert_path = os.path.join(provider_dir,
                                     "cert")

        ec.get_client_cert_path = mock.MagicMock(
            return_value=eip_cert_path)

        cert_content = "A"
        if createcert:
            with open(eip_cert_path, "w") as ec:
                ec.write(cert_content)

        return eip_cert_path, cert_content

    def test_download_client_certificate_not_modified(self):
        cert_path, old_cert_content = self._download_certificate_test_template(
            True, True)

        with mock.patch('leap.common.certs.should_redownload',
                        new_callable=mock.MagicMock,
                        return_value=False):
            self.eb._download_client_certificates()
            with open(cert_path, "r") as c:
                self.assertEqual(c.read(), old_cert_content)

    @deferred()
    def test_download_client_certificate_old_cert(self):
        cert_path, old_cert_content = self._download_certificate_test_template(
            True, True)

        def wrapper(*args):
            with mock.patch('leap.common.certs.should_redownload',
                            new_callable=mock.MagicMock,
                            return_value=True):
                with mock.patch('leap.common.certs.is_valid_pemfile',
                                new_callable=mock.MagicMock,
                                return_value=True):
                    self.eb._download_client_certificates()

        def check(*args):
            with open(cert_path, "r") as c:
                self.assertNotEqual(c.read(), old_cert_content)
        d = threads.deferToThread(wrapper)
        d.addCallback(check)

        return d

    @deferred()
    def test_download_client_certificate_no_cert(self):
        cert_path, _ = self._download_certificate_test_template(
            True, False)

        def wrapper(*args):
            with mock.patch('leap.common.certs.should_redownload',
                            new_callable=mock.MagicMock,
                            return_value=False):
                with mock.patch('leap.common.certs.is_valid_pemfile',
                                new_callable=mock.MagicMock,
                                return_value=True):
                    self.eb._download_client_certificates()

        def check(*args):
            self.assertTrue(os.path.exists(cert_path))
        d = threads.deferToThread(wrapper)
        d.addCallback(check)

        return d

    @deferred()
    def test_download_client_certificate_force_not_valid(self):
        cert_path, old_cert_content = self._download_certificate_test_template(
            True, True)

        def wrapper(*args):
            with mock.patch('leap.common.certs.should_redownload',
                            new_callable=mock.MagicMock,
                            return_value=True):
                with mock.patch('leap.common.certs.is_valid_pemfile',
                                new_callable=mock.MagicMock,
                                return_value=True):
                    self.eb._download_client_certificates()

        def check(*args):
            with open(cert_path, "r") as c:
                self.assertNotEqual(c.read(), old_cert_content)
        d = threads.deferToThread(wrapper)
        d.addCallback(check)

        return d

    @deferred()
    def test_download_client_certificate_invalid_download(self):
        cert_path, _ = self._download_certificate_test_template(
            False, False)

        def wrapper(*args):
            with mock.patch('leap.common.certs.should_redownload',
                            new_callable=mock.MagicMock,
                            return_value=True):
                with mock.patch('leap.common.certs.is_valid_pemfile',
                                new_callable=mock.MagicMock,
                                return_value=False):
                    with self.assertRaises(Exception):
                        self.eb._download_client_certificates()
        d = threads.deferToThread(wrapper)

        return d

    @deferred()
    def test_download_client_certificate_uses_session_id(self):
        _, _ = self._download_certificate_test_template(
            False, False)

        SRPAuth.get_session_id = mock.MagicMock(return_value="1")

        def check_cookie(*args, **kwargs):
            cookies = kwargs.get("cookies", None)
            self.assertEqual(cookies, {'_session_id': '1'})
            return Response()

        def wrapper(*args):
            with mock.patch('leap.common.certs.should_redownload',
                            new_callable=mock.MagicMock,
                            return_value=False):
                with mock.patch('leap.common.certs.is_valid_pemfile',
                                new_callable=mock.MagicMock,
                                return_value=True):
                    with mock.patch('requests.sessions.Session.get',
                                    new_callable=mock.MagicMock,
                                    side_effect=check_cookie):
                        with mock.patch('requests.models.Response.content',
                                        new_callable=mock.PropertyMock,
                                        return_value="A"):
                            self.eb._download_client_certificates()

        d = threads.deferToThread(wrapper)

        return d

    @deferred()
    def test_run_eip_setup_checks(self):
        self.eb._download_config = mock.MagicMock()
        self.eb._download_client_certificates = mock.MagicMock()

        d = self.eb.run_eip_setup_checks(ProviderConfig())

        def check(*args):
            self.eb._download_config.assert_called_once_with()
            self.eb._download_client_certificates.assert_called_once_with(None)
        d.addCallback(check)
        return d