~roadmr/canonical-identity-provider/fix-deprecation-warnings-1

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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# encoding: utf-8

import csv
import random
import tempfile

from datetime import date
from StringIO import StringIO

from django.contrib.auth.hashers import check_password, make_password
from django.core.management import CommandError, call_command
from django.db import DatabaseError, connection
from django.utils.timezone import now
from mock import Mock, patch
from psycopg2 import InternalError

from identityprovider.management.commands.import_leak_data import Command
from identityprovider.models import Account, LeakedCredential
from identityprovider.tests.utils import SSOBaseTestCase
from identityprovider.utils import (
    encrypt_launchpad_password,
    generate_random_string,
)


class ImportLeakDataCommandTestCase(SSOBaseTestCase):
    def setUp(self):
        super(ImportLeakDataCommandTestCase, self).setUp()
        self.command = Command()
        # disable output
        self.command.verbosity = 0
        self.command.stdout = Mock()
        self.command.stderr = Mock()
        self.command.source = 'the-source'
        self.command.date_leaked = now().date()

    def make_string(self):
        length = random.randint(1, 16)
        return generate_random_string(length)

    def make_email(self):
        return "%s@dom.ain" % self.make_string()

    def make_row(self, flat=False):
        email = self.make_email()
        raw_password = self.make_string()
        hashed_password = make_password(raw_password)
        row = [email, hashed_password, raw_password]
        if flat:
            return ','.join(row)
        return row

    def make_input_file(self, rows=1, content=None):
        input_file = tempfile.NamedTemporaryFile()
        if content is not None:
            input_file.write(content)
        else:
            for row in range(rows):
                input_file.write(self.make_row(flat=True))
        input_file.flush()
        return input_file

    def make_items(self, count=1, source='source', date_leaked=None):
        if date_leaked is None:
            date_leaked = now().date()
        rows = [self.make_row() for i in range(count)]
        items = [
            LeakedCredential(email=row[0], password=row[1],
                             source=source, when_leaked=date_leaked)
            for row in rows]
        return items

    def test_missing_input_file(self):
        with self.assertRaises(CommandError) as ctx:
            call_command('import_leak_data', verbosity=0)
        self.assertEqual(
            str(ctx.exception),
            'Error: Need to specify an input file and a leak source.')

    def test_missing_leak_source(self):
        with self.assertRaises(CommandError) as ctx:
            call_command('import_leak_data', 'input.csv', verbosity=0)
        self.assertEqual(str(ctx.exception), 'Error: too few arguments')

    def test_too_many_arguments(self):
        with self.assertRaises(CommandError) as ctx:
            call_command('import_leak_data', 'input.csv', 'source',
                         'something', verbosity=0)
        self.assertEqual(
            str(ctx.exception), 'Error: unrecognized arguments: something')

    def test_no_date_leaked(self):
        input_file = self.make_input_file()

        with patch('identityprovider.management.commands.import_leak_data.'
                   'now') as mock_now:
            mock_now.return_value = now()
            self.command.handle(filename=input_file.name, source='source',
                                read_batch_size=1000)
        self.assertEqual(
            self.command.date_leaked, mock_now.return_value.date())

    def test_invalid_date_leaked(self):
        with self.assertRaises(CommandError) as ctx:
            call_command('import_leak_data', 'input.csv', 'source',
                         date_leaked='foo', verbosity=0)
        self.assertEqual(str(ctx.exception),
                         "option --date-leaked: invalid date: 'foo'")

    def test_valid_date_leaked(self):
        input_file = self.make_input_file()

        date_leaked = date(2013, 11, 16)
        self.command.handle(filename=input_file.name, source='source',
                            read_batch_size=1000, date_leaked='2013-11-16')
        self.assertEqual(self.command.date_leaked, date_leaked)

    def test_dry_run_mode(self):
        input_file = self.make_input_file()

        name = ('identityprovider.management.commands.import_leak_data'
                '.Command.make_items')
        with patch(name) as mock_make_items:
            call_command('import_leak_data', input_file.name, 'source',
                         dry_run=True, verbosity=0)
        self.assertFalse(mock_make_items.called)

    def test_no_dry_run_mode(self):
        input_file = self.make_input_file()

        name = ('identityprovider.management.commands.import_leak_data'
                '.Command.make_items')
        with patch(name) as mock_make_items:
            call_command('import_leak_data', input_file.name, 'source',
                         verbosity=0)
        self.assertTrue(mock_make_items.called)

    def test_read_rows_no_data(self):
        input_file = StringIO()
        reader = csv.reader(input_file)

        rows = self.command.read_rows(reader, 10)
        self.assertEqual(rows, [])

    def test_read_rows_partial_data(self):
        input_file = StringIO("""email1,hash1,password1
email2,hash2,password2
email3,hash3,password3
""")
        reader = csv.reader(input_file)

        rows = self.command.read_rows(reader, 10)
        self.assertEqual(rows, [
            ['email1', 'hash1', 'password1'], ['email2', 'hash2', 'password2'],
            ['email3', 'hash3', 'password3'],
        ])

    def test_read_rows_full_data(self):
        input_file = StringIO("""email1,hash1,password1
email2,hash2,password2
email3,hash3,password3
""")
        reader = csv.reader(input_file)

        rows = self.command.read_rows(reader, 2)
        self.assertEqual(rows, [
            ['email1', 'hash1', 'password1'], ['email2', 'hash2', 'password2'],
        ])

    def test_read_rows_unicode_data(self):
        raw_password = u'päŞwöṙd'
        row = u"user@dom.ain,%s,%s" % (make_password(raw_password),
                                       raw_password)
        input_file = self.make_input_file(
            content=row.encode('utf-8'))
        call_command('import_leak_data', input_file.name, 'source',
                     verbosity=0)
        item = LeakedCredential.objects.get(email='user@dom.ain',
                                            source='source')
        self.assertNotEqual(item.password, raw_password)
        self.assertTrue(check_password(raw_password, item.password))

    def test_make_items_clean_data(self):
        rows = [['user1@dom.ain', make_password('password1'), 'password1'],
                ['user2@dom.ain', make_password('password2'), 'password2']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 2)
        for item, row in zip(items, rows):
            self.assertEqual(item.email, row[0])
            self.assertEqual(item.password, row[1])
            self.assertNotEqual(item.password, row[2])
            self.assertTrue(check_password(row[2], item.password))
            self.assertEqual(item.source, 'the-source')
            self.assertEqual(item.when_leaked, now().date())

    def test_make_items_invalid_hash(self):
        """
        Ensure invalid hash with no plaintext is rejected.
        """
        rows = [['user1@dom.ain', '3wSZL7LArdlTo', '']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 0)

    def test_make_items_no_password_and_valid_hash(self):
        """
        Ensure valid hash with no plaintext is stored verbatim.
        """
        pw_hash = make_password('password1')
        rows = [['user1@dom.ain', pw_hash, '']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].password, pw_hash)

    def test_make_items_password_and_empty_hash(self):
        """
        Ensure hash is generated from plaintext-based hash if the
        hash is empty.
        """
        rows = [['user1@dom.ain', '', 'password1']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 1)
        self.assertTrue(check_password('password1', items[0].password))

    def test_make_items_password_and_unusable_hash(self):
        """
        Ensure hash is replaced with plaintext-based hash if the
        hash is not django-usable
        """
        rows = [['user1@dom.ain', 'discardable_hash', 'password1']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 1)
        self.assertTrue(check_password('password1', items[0].password))

    def test_make_items_password_and_usable_hash(self):
        """
        Ensure hash is stored verbatim if it's django-usable
        """
        pw_hash = make_password('password1')
        rows = [['user1@dom.ain', pw_hash, 'password1']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].password, pw_hash)

    def test_make_items_noisy_data(self):
        rows = [['user1', 'hash1', 'password1'],
                ['user2@dom.ain', 'hash2', 'password2'],
                ['user3@dom.ain', '', '']]
        items = list(self.command.make_items(rows, None))
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].email, 'user2@dom.ain')
        self.assertTrue(check_password('password2', items[0].password))
        self.assertEqual(items[0].source, 'the-source')
        self.assertEqual(items[0].when_leaked, now().date())

    def test_insert_items_no_batching(self):
        items = self.make_items(count=10)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.bulk_create') as mock_bulk_create:
            with patch(prefix + '.get_or_create') as mock_get_or_create:
                self.command.insert_items(items, None)
        self.assertFalse(mock_bulk_create.called)
        self.assertEqual(mock_get_or_create.call_count, 10)

    def test_insert_items_in_batches(self):
        items = self.make_items(count=10)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.bulk_create') as mock_bulk_create:
            with patch(prefix + '.get_or_create') as mock_get_or_create:
                self.command.insert_items(items, 10)
        self.assertEqual(mock_bulk_create.call_count, 1)
        self.assertFalse(mock_get_or_create.called)

    def test_insert_items_in_batches_with_errors(self):
        items = self.make_items(count=10)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.bulk_create') as mock_bulk_create:
            with patch(prefix + '.get_or_create') as mock_get_or_create:
                mock_bulk_create.side_effect = InternalError
                # now attempt the bulk insert
                self.command.insert_items(items, 5)
        self.assertEqual(mock_bulk_create.call_count, 2)
        self.assertEqual(mock_get_or_create.call_count, 10)

    def test_insert_items_in_batches_with_errors_rollback_single_batch(self):
        real_bulk_create = LeakedCredential.objects.bulk_create

        def bulk_create_with_failure(*args, **kwargs):
            if mock_bulk_create.call_count == 1:
                return real_bulk_create(*args, **kwargs)
            raise InternalError()
        mock_bulk_create = Mock(side_effect=bulk_create_with_failure)

        real_get_or_create = LeakedCredential.objects.get_or_create
        mock_get_or_create = Mock(side_effect=real_get_or_create)

        items = self.make_items(count=10)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.bulk_create', mock_bulk_create):
            with patch(prefix + '.get_or_create', mock_get_or_create):
                # now attempt the bulk insert
                self.command.insert_items(items, 5)
        self.assertEqual(mock_bulk_create.call_count, 2)
        self.assertEqual(mock_get_or_create.call_count, 5)
        self.assertEqual(LeakedCredential.objects.all().count(), 10)

    def test_insert_items_in_batches_with_error_updating_sequence(self):
        # Get next ID and prepare the expectation for test verification
        cursor = connection.cursor()
        cursor.execute(
            "select nextval('identityprovider_leakedcredential_id_seq')")
        expected_next_id = cursor.fetchone()[0] + 1
        # Make 10 items and try to insert 5 of them with database error
        items = self.make_items(count=10)
        name = ('identityprovider.management.commands.import_leak_data'
                '.Command.set_sequence')
        with patch(name) as mock_set_sequence:
            mock_set_sequence.side_effect = DatabaseError
            self.command.insert_items(items, 5)
        self.assertEqual(LeakedCredential.objects.all().count(), 10)
        # Ensure the sequence didn't "eat" IDs for the 5 failed items
        cursor = connection.cursor()
        cursor.execute(
            "select nextval('identityprovider_leakedcredential_id_seq')")
        next_id = cursor.fetchone()[0]
        self.assertEqual(next_id, expected_next_id)

    def test_error_in_insert_fallback(self):
        items = self.make_items(count=5)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.bulk_create') as mock_bulk_create:
            mock_bulk_create.side_effect = InternalError
            with patch(prefix + '.get_or_create') as mock_get_or_create:
                mock_get_or_create.side_effect = InternalError
                self.command.insert_items(items, 10)
        self.assertEqual(self.command.stderr.write.call_count, 5)
        self.assertEqual(LeakedCredential.objects.all().count(), 0)

    def test_error_in_insert(self):
        items = self.make_items(count=5)
        prefix = ('identityprovider.management.commands.import_leak_data'
                  '.LeakedCredential.objects')
        with patch(prefix + '.get_or_create') as mock_get_or_create:
            mock_get_or_create.side_effect = InternalError
            # insert unbatched to trigger the error
            self.command.insert_items(items, None)
        self.assertEqual(mock_get_or_create.call_count, 5)
        self.assertEqual(self.command.stderr.write.call_count, 5)
        self.assertEqual(LeakedCredential.objects.all().count(), 0)

    def test_make_item_with_matching_account_using_launchpad(self):
        encrypted = encrypt_launchpad_password('foo', salt='salt')
        account = self.factory.make_account(password=encrypted,
                                            password_encrypted=True)
        email = account.preferredemail.email

        name = 'identityprovider.emailutils.send_password_reset_email'
        with patch(name) as mock_send_email:
            item = self.command.make_item([email, make_password('foo'), 'foo'])

        self.assertEqual(item.email, email)
        self.assertNotEqual(item.password, encrypted)
        self.assertTrue(check_password('foo', item.password))
        self.assertEqual(item.source, 'the-source')
        self.assertEqual(item.when_leaked, now().date())

        # refresh account
        account = Account.objects.get(id=account.id)
        self.assertTrue(account.need_password_reset)
        mock_send_email.assert_called_once_with(
            account, email, reason='password_leak|the-source')

    def test_make_item_with_matching_account_using_pbkdf2(self):
        encrypted = make_password('foo', salt='salt', hasher='pbkdf2_sha256')
        account = self.factory.make_account(password=encrypted,
                                            password_encrypted=True)
        email = account.preferredemail.email

        name = 'identityprovider.emailutils.send_password_reset_email'
        with patch(name) as mock_send_email:
            item = self.command.make_item([email, make_password('foo'), 'foo'])

        self.assertEqual(item.email, email)
        self.assertNotEqual(item.password, encrypted)
        self.assertTrue(check_password('foo', item.password))
        self.assertEqual(item.source, 'the-source')
        self.assertEqual(item.when_leaked, now().date())

        # refresh account
        account = Account.objects.get(id=account.id)
        self.assertTrue(account.need_password_reset)
        mock_send_email.assert_called_once_with(
            account, email, reason='password_leak|the-source')

    def test_make_item_without_matching_account(self):
        row = self.make_row()

        item = self.command.make_item(row)

        self.assertEqual(item.email, row[0])
        self.assertEqual(item.password, row[1])
        self.assertTrue(check_password(row[2], item.password))
        self.assertEqual(item.source, 'the-source')
        self.assertEqual(item.when_leaked, now().date())

    def test_make_item_invalid_email(self):
        item = self.command.make_item(['foo', 'foo', 'foo'])
        self.assertIsNone(item)

    def test_make_item_no_password(self):
        item = self.command.make_item(['user@dom.ain', '', ''])
        self.assertIsNone(item)

    def test_make_item_when_no_accountpassword(self):
        account = self.factory.make_account(email='user@dom.ain',
                                            password='password')
        account.accountpassword.delete()

        item = self.command.make_item(
            ['user@dom.ain', make_password('password'), 'password'])

        self.assertIsNotNone(item)
        account = Account.objects.get(id=account.id)
        self.assertIsNone(account.need_password_reset)