summaryrefslogtreecommitdiffstats
path: root/tests/auth_fc/test_auth_fc.py
blob: 48ddb318e65ead0364a20187afc75d714be15dcd (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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# -*- coding: utf-8 -*-
# authentic2-auth-fc - authentic2 authentication for FranceConnect
# Copyright (C) 2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import contextlib
import pytest
import re
import urlparse
import httmock
import mock
import json
import base64
from jwcrypto import jwk, jwt
import datetime

import requests

from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.utils.timezone import now

from authentic2.a2_rbac.utils import get_default_ou
from authentic2.utils import timestamp_from_datetime, make_url

from authentic2_auth_fc import models
from authentic2_auth_fc.utils import requests_retry_session


User = get_user_model()


class FcMock(object):
    code = 'zzz'
    sub = '1234'
    client_id = 'xxx'
    client_secret = 'yyy'
    access_token = 'uuu'
    iss = 'https://fcp.integ01.dev-franceconnect.fr/'
    user_info__family_name = u'Frédérique'
    user_info__given_name = u'Ÿuñe'

    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

    def check_authorization_url(self, url):
        callback = reverse('fc-login-or-link')
        assert url.startswith('https://fcp.integ01')
        query_string = url.split('?')[1]
        parsed = {x: y[0] for x, y in urlparse.parse_qs(query_string).items()}
        assert 'redirect_uri' in parsed
        assert callback in parsed['redirect_uri']
        assert 'client_id' in parsed
        assert parsed['client_id'] == 'xxx'
        assert 'scope' in parsed
        assert set(parsed['scope'].split()) == set(['openid', 'profile', 'birth', 'email'])
        assert 'state' in parsed
        assert 'nonce' in parsed
        assert parsed['state'] == parsed['nonce']
        assert 'response_type' in parsed
        assert parsed['response_type'] == 'code'
        return parsed['state'], parsed['redirect_uri']

    @contextlib.contextmanager
    def mock(self, response_or_url, callback=None, **kwargs):
        old_dict = self.__dict__.copy()
        self.__dict__.update(**kwargs)
        exp = getattr(self, 'exp', timestamp_from_datetime(now() + datetime.timedelta(seconds=1000)))

        if hasattr(response_or_url, 'location'):
            location = response_or_url.location
        else:
            location = response_or_url

        state, redirect_uri = self.check_authorization_url(location)

        @httmock.urlmatch(path=r'.*/token$')
        def access_token_response(url, request):
            parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
            assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                              'grant_type'])
            assert parsed['code'] == self.code
            assert parsed['client_id'] == self.client_id
            assert parsed['client_secret'] == self.client_secret
            assert parsed['grant_type'] == 'authorization_code'
            assert parsed['redirect_uri'] == redirect_uri
            id_token = {
                'sub': self.sub,
                'aud': self.client_id,
                'nonce': state,
                'exp': exp,
                'iss': self.iss,
            }
            return json.dumps({
                'access_token': self.access_token,
                'id_token': hmac_jwt(id_token, 'yyy')
            })

        @httmock.urlmatch(path=r'.*userinfo$')
        def user_info_response(url, request):
            assert request.headers['Authorization'] == 'Bearer uuu'
            user_info = {
                'sub': self.sub,
            }
            for key in dir(self):
                if key.startswith('user_info__'):
                    user_info[key[len('user_info__'):]] = getattr(self, key)
            return json.dumps(user_info)

        callback_url = make_url(redirect_uri, params={'code': self.code, 'state': state})
        try:
            with httmock.HTTMock(access_token_response, user_info_response):
                yield callback_url
        finally:
            self.__dict__.update(old_dict)


@pytest.fixture
def fc(fc_settings):
    yield FcMock()


def path(url):
    return urlparse.urlparse(url).path


def path_and_query(url):
    parsed = urlparse.urlparse(url)
    return parsed.path + '?' + parsed.query


def get_links_from_mail(mail):
    '''Extract links from mail sent by Django'''
    return re.findall('https?://[^ \n]*', mail.body)


def hmac_jwt(payload, key):
    header = {'alg': 'HS256'}
    k = jwk.JWK(kty='oct', k=base64.b64encode(key.encode('utf-8')))
    t = jwt.JWT(header=header, claims=payload)
    t.make_signed_token(k)
    return t.serialize()


def test_login_redirect(app, fc_settings):
    url = reverse('fc-login-or-link')
    response = app.get(url, status=302)
    assert response['Location'].startswith('https://fcp.integ01')


def check_authorization_url(url):
    callback = reverse('fc-login-or-link')
    assert url.startswith('https://fcp.integ01')
    query_string = url.split('?')[1]
    parsed = {x: y[0] for x, y in urlparse.parse_qs(query_string).items()}
    assert 'redirect_uri' in parsed
    assert callback in parsed['redirect_uri']
    assert 'client_id' in parsed
    assert parsed['client_id'] == 'xxx'
    assert 'scope' in parsed
    assert set(parsed['scope'].split()) == set(['openid', 'profile', 'birth', 'email'])
    assert 'state' in parsed
    assert 'nonce' in parsed
    assert parsed['state'] == parsed['nonce']
    assert 'response_type' in parsed
    assert parsed['response_type'] == 'code'
    assert parsed['acr_values'] == 'eidas1'
    return parsed['state']


def test_nocreate(app, fc_settings, fc, caplog, hooks):
    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click(href='callback')

    with fc.mock(response) as callback_url:
        response = app.get(callback_url)

    assert User.objects.count() == 0
    assert response.location.startswith('/login/')


def test_create_expired(app, fc_settings, fc, caplog, hooks):
    fc_settings.A2_FC_CREATE = True

    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click(href='callback')

    exp = timestamp_from_datetime(now() - datetime.timedelta(seconds=1000))
    with fc.mock(response, exp=exp) as callback_url:
        response = app.get(callback_url)

    assert User.objects.count() == 0


def test_create(app, fc_settings, fc, caplog, hooks):
    fc_settings.A2_FC_CREATE = True

    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click(href='callback')

    with fc.mock(response) as callback_url:
        response = app.get(callback_url)
    assert User.objects.count() == 1
    user = User.objects.get()
    assert user.verified_attributes.first_name == u'Ÿuñe'
    assert user.verified_attributes.last_name == u'Frédérique'
    assert path(response['Location']) == '/idp/'
    assert hooks.event[1]['kwargs']['name'] == 'login'
    assert hooks.event[1]['kwargs']['service'] == 'portail'
    # we must be connected
    assert app.session['_auth_user_id']
    assert models.FcAccount.objects.count() == 1
    response = app.get('/accounts/')
    response = response.click('Delete link')
    response.form.set('new_password1', 'ikKL1234')
    response.form.set('new_password2', 'ikKL1234')
    response = response.form.submit(name='unlink')
    assert 'The link with the FranceConnect account has been deleted' in response.content
    assert models.FcAccount.objects.count() == 0
    continue_url = response.pyquery('a#a2-continue').attr['href']
    state = urlparse.parse_qs(urlparse.urlparse(continue_url).query)['state'][0]
    assert app.session['fc_states'][state]['next'] == '/accounts/'
    response = app.get(reverse('fc-logout') + '?state=' + state)
    assert path(response['Location']) == '/accounts/'


def test_link_by_email(app, fc, fc_settings, caplog):
    user = User.objects.create(
        email='john.doe@example.com',
        first_name='John',
        last_name='Doe',
        ou=get_default_ou())
    user.set_password('toto')
    user.save()

    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click(href='callback')

    assert models.FcAccount.objects.count() == 0
    with fc.mock(response, user_info__email='jOhn.dOe@eXample.com') as callback_url:
        response = app.get(callback_url)

    assert User.objects.count() == 1
    assert app.session['_auth_user_id']
    assert models.FcAccount.objects.filter(user=user, sub=fc.sub, order=0).count() == 1

    # logout, test unlinking when logging with password
    app.session.flush()
    response = app.get('/login/')
    response.form.set('username', User.objects.get().email)
    response.form.set('password', 'toto')
    response = response.form.submit(name='login-password-submit').follow()

    response = app.get('/accounts/')
    response = response.click('Delete link')
    assert 'new_password1' not in response.form.fields
    response = response.form.submit(name='unlink').follow()
    assert 'The link with the FranceConnect account has been deleted' in response.content
    assert response.request.path == '/accounts/'


def test_login_email_is_unique_and_already_linked(app, fc_settings, caplog):
    callback = reverse('fc-login-or-link')
    response = app.get(callback, status=302)
    location = response['Location']
    state = check_authorization_url(location)

    EMAIL = 'john.doe@example.com'
    SUB = '1234'
    user = User.objects.create(email=EMAIL, first_name='John', last_name='Doe')
    models.FcAccount.objects.create(user=user, sub='4567', token='xxx', user_info='{}')

    @httmock.urlmatch(path=r'.*/token$')
    def access_token_response(url, request):
        parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
        assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                          'grant_type'])
        assert parsed['code'] == 'zzz'
        assert parsed['client_id'] == 'xxx'
        assert parsed['client_secret'] == 'yyy'
        assert parsed['grant_type'] == 'authorization_code'
        assert callback in parsed['redirect_uri']
        id_token = {
            'sub': SUB,
            'aud': 'xxx',
            'nonce': state,
            'exp': timestamp_from_datetime(now() + datetime.timedelta(seconds=1000)),
            'iss': 'https://fcp.integ01.dev-franceconnect.fr/',
        }
        return json.dumps({
            'access_token': 'uuu',
            'id_token': hmac_jwt(id_token, 'yyy')
        })

    @httmock.urlmatch(path=r'.*userinfo$')
    def user_info_response(url, request):
        assert request.headers['Authorization'] == 'Bearer uuu'
        return json.dumps({
            'sub': '1234',
            'family_name': u'Frédérique',
            'given_name': u'Ÿuñe',
            'email': EMAIL,
        })

    fc_settings.A2_EMAIL_IS_UNIQUE = True
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '?code=zzz&state=%s' % state, status=302)
        assert 'is already linked' in str(response)
    assert User.objects.count() == 1
    assert '_auth_user_id' not in app.session


def test_requests_proxies_support(app, fc_settings, caplog):
    session = requests_retry_session()
    assert session.proxies == {}
    other_session = requests.Session()
    other_session.proxies = {'http': 'http://example.net'}
    session = requests_retry_session(session=other_session)
    assert session is other_session
    assert session.proxies == {'http': 'http://example.net'}
    fc_settings.REQUESTS_PROXIES = {'https': 'http://pubproxy.com/api/proxy'}
    session = requests_retry_session()
    assert session.proxies == {'https': 'http://pubproxy.com/api/proxy'}

    with mock.patch('authentic2_auth_fc.utils.requests.Session.send') as mocked_send:
        mocked_send.return_value = mock.Mock(status_code=200, content='whatever')
        session.get('https://example.net/')
        assert mocked_send.call_args[1]['proxies'] == {'https': 'http://pubproxy.com/api/proxy'}


def test_password_reset(app, mailoutbox):
    user = User.objects.create(email='john.doe@example.com')
    response = app.get('/login/')
    response = response.click('Reset it!').maybe_follow()
    response.form['email'] = user.email
    assert len(mailoutbox) == 0
    response = response.form.submit()
    assert len(mailoutbox) == 1
    url = get_links_from_mail(mailoutbox[0])[0]
    app.get(url, status=302)
    models.FcAccount.objects.create(user=user, sub='xxx', token='aaa')
    response = app.get(url)
    assert 'new_password1' in response.form.fields


def test_registration1(app, fc_settings, caplog, hooks):
    exp = timestamp_from_datetime(now() + datetime.timedelta(seconds=1000))
    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click(href="callback")
    # 1. Try a login
    # 2. Verify we come back to login page
    # 3. Check presence of registration link
    # 4. Follow it
    location = response['Location']
    state = check_authorization_url(location)

    @httmock.urlmatch(path=r'.*/token$')
    def access_token_response(url, request):
        parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
        assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                          'grant_type'])
        assert parsed['code'] == 'zzz'
        assert parsed['client_id'] == 'xxx'
        assert parsed['client_secret'] == 'yyy'
        assert parsed['grant_type'] == 'authorization_code'
        assert callback in parsed['redirect_uri']
        id_token = {
            'sub': '1234',
            'aud': 'xxx',
            'nonce': state,
            'exp': exp,
            'iss': 'https://fcp.integ01.dev-franceconnect.fr/',
            'email': 'john.doe@example.com',
        }
        return json.dumps({
            'access_token': 'uuu',
            'id_token': hmac_jwt(id_token, 'yyy')
        })

    @httmock.urlmatch(path=r'.*userinfo$')
    def user_info_response(url, request):
        assert request.headers['Authorization'] == 'Bearer uuu'
        return json.dumps({
            'sub': '1234',
            'family_name': u'Frédérique',
            'given_name': u'Ÿuñe',
            'email': 'john.doe@example.com',
        })

    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert User.objects.count() == 0
    assert path(response['Location']) == '/login/'
    response = response.follow()
    response = response.click(href='/accounts/fc/register')
    location = response['Location']
    location.startswith('http://testserver/accounts/activate/')
    response = response.follow()
    assert hooks.calls['event'][0]['kwargs']['service'] == 'portail'
    # we must be connected
    assert app.session['_auth_user_id']
    assert path_and_query(response['Location']) == path_and_query(callback)
    response = response.follow()
    location = response['Location']
    state = check_authorization_url(location)
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert models.FcAccount.objects.count() == 1
    user = User.objects.get()
    assert user.verified_attributes.first_name == u'Ÿuñe'
    assert user.verified_attributes.last_name == u'Frédérique'
    response = app.get('/accounts/')
    response = response.click('Delete link')
    response.form.set('new_password1', 'ikKL1234')
    response.form.set('new_password2', 'ikKL1234')
    response = response.form.submit(name='unlink')
    assert 'The link with the FranceConnect account has been deleted' in response.content
    assert models.FcAccount.objects.count() == 0
    continue_url = response.pyquery('a#a2-continue').attr['href']
    state = urlparse.parse_qs(urlparse.urlparse(continue_url).query)['state'][0]
    assert app.session['fc_states'][state]['next'] == '/accounts/'
    response = app.get(reverse('fc-logout') + '?state=' + state)
    assert path(response['Location']) == '/accounts/'


def test_registration2(app, fc_settings, caplog, hooks):
    exp = timestamp_from_datetime(now() + datetime.timedelta(seconds=1000))
    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click("Register")
    response = response.click(href='callback')
    # 1. Try a login
    # 2. Verify we come back to login page
    # 3. Check presence of registration link
    # 4. Follow it
    location = response['Location']
    state = check_authorization_url(location)

    @httmock.urlmatch(path=r'.*/token$')
    def access_token_response(url, request):
        parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
        assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                          'grant_type'])
        assert parsed['code'] == 'zzz'
        assert parsed['client_id'] == 'xxx'
        assert parsed['client_secret'] == 'yyy'
        assert parsed['grant_type'] == 'authorization_code'
        assert callback in parsed['redirect_uri']
        id_token = {
            'sub': '1234',
            'aud': 'xxx',
            'nonce': state,
            'exp': exp,
            'iss': 'https://fcp.integ01.dev-franceconnect.fr/',
            'email': 'john.doe@example.com',
        }
        return json.dumps({
            'access_token': 'uuu',
            'id_token': hmac_jwt(id_token, 'yyy')
        })

    @httmock.urlmatch(path=r'.*userinfo$')
    def user_info_response(url, request):
        assert request.headers['Authorization'] == 'Bearer uuu'
        return json.dumps({
            'sub': '1234',
            'family_name': u'Frédérique',
            'given_name': u'Ÿuñe',
            'email': 'john.doe@example.com',
        })

    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert User.objects.count() == 0
    assert path(response['Location']) == '/accounts/fc/register/'
    response = response.follow()
    location = response['Location']
    location.startswith('http://testserver/accounts/activate/')
    response = response.follow()
    assert hooks.calls['event'][0]['kwargs']['service'] == 'portail'
    assert hooks.calls['event'][1]['kwargs']['service'] == 'portail'
    # we must be connected
    assert app.session['_auth_user_id']
    # remove the registration parameter
    callback = callback.replace('&registration=', '')
    callback = callback.replace('?registration=', '?')
    callback = callback.replace('?&', '?')
    assert path_and_query(response['Location']) == path_and_query(callback)
    response = response.follow()
    location = response['Location']
    state = check_authorization_url(location)
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert models.FcAccount.objects.count() == 1
    user = User.objects.get()
    assert user.verified_attributes.first_name == u'Ÿuñe'
    assert user.verified_attributes.last_name == u'Frédérique'
    response = app.get('/accounts/')
    response = response.click('Delete link')
    response.form.set('new_password1', 'ikKL1234')
    response.form.set('new_password2', 'ikKL1234')
    response = response.form.submit(name='unlink')
    assert 'The link with the FranceConnect account has been deleted' in response.content
    assert models.FcAccount.objects.count() == 0
    continue_url = response.pyquery('a#a2-continue').attr['href']
    state = urlparse.parse_qs(urlparse.urlparse(continue_url).query)['state'][0]
    assert app.session['fc_states'][state]['next'] == '/accounts/'
    response = app.get(reverse('fc-logout') + '?state=' + state)
    assert path(response['Location']) == '/accounts/'


def test_can_change_password(app, fc_settings, caplog, hooks):
    exp = timestamp_from_datetime(now() + datetime.timedelta(seconds=1000))
    response = app.get('/login/?service=portail&next=/idp/')
    response = response.click("Register")
    response = response.click(href='callback')
    # 1. Try a login
    # 2. Verify we come back to login page
    # 3. Check presence of registration link
    # 4. Follow it
    location = response['Location']
    state = check_authorization_url(location)

    sub = '1234'

    @httmock.urlmatch(path=r'.*/token$')
    def access_token_response(url, request):
        parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
        assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                          'grant_type'])
        assert parsed['code'] == 'zzz'
        assert parsed['client_id'] == 'xxx'
        assert parsed['client_secret'] == 'yyy'
        assert parsed['grant_type'] == 'authorization_code'
        assert callback in parsed['redirect_uri']
        id_token = {
            'sub': sub,
            'aud': 'xxx',
            'nonce': state,
            'exp': exp,
            'iss': 'https://fcp.integ01.dev-franceconnect.fr/',
            'email': 'john.doe@example.com',
        }
        return json.dumps({
            'access_token': 'uuu',
            'id_token': hmac_jwt(id_token, 'yyy')
        })

    @httmock.urlmatch(path=r'.*userinfo$')
    def user_info_response(url, request):
        assert request.headers['Authorization'] == 'Bearer uuu'
        return json.dumps({
            'sub': sub,
            'family_name': u'Frédérique',
            'given_name': u'Ÿuñe',
            'email': 'john.doe@example.com',
        })

    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert User.objects.count() == 0
    assert path(response['Location']) == '/accounts/fc/register/'
    response = response.follow()
    location = response['Location']
    location.startswith('http://testserver/accounts/activate/')
    response = response.follow()
    assert hooks.calls['event'][0]['kwargs']['service'] == 'portail'
    assert hooks.calls['event'][1]['kwargs']['service'] == 'portail'
    # we must be connected
    assert app.session['_auth_user_id']
    # remove the registration parameter
    callback = callback.replace('&registration=', '')
    callback = callback.replace('?registration=', '?')
    callback = callback.replace('?&', '?')
    assert path_and_query(response['Location']) == path_and_query(callback)
    response = response.follow()
    location = response['Location']
    state = check_authorization_url(location)
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    assert models.FcAccount.objects.count() == 1
    user = User.objects.get()
    assert user.verified_attributes.first_name == u'Ÿuñe'
    assert user.verified_attributes.last_name == u'Frédérique'
    response = app.get('/accounts/')
    assert len(response.pyquery('[href*="password/change"]')) == 0

    # Login with password
    user = User.objects.get()
    user.set_password('test')
    user.save()
    app.session.flush()
    response = app.get('/login/')
    response.form.set('username', User.objects.get().email)
    response.form.set('password', 'test')
    response = response.form.submit(name='login-password-submit').follow()
    response = app.get('/accounts/')
    assert len(response.pyquery('[href*="password/change"]')) > 0

    # Relogin with FC
    app.session.flush()
    response = app.get('/login/?service=portail&next=/accounts/')
    response = response.click(href='callback')
    location = response['Location']
    state = check_authorization_url(location)
    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    # we must be connected
    assert app.session['_auth_user_id']
    assert path(response['Location']) == '/accounts/'
    response = response.follow()
    assert len(response.pyquery('[href*="password/change"]')) == 0

    # Try to relink
    response = app.get('/fc/callback/?next=/accounts/')
    location = response['Location']
    state = check_authorization_url(location)
    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    response = response.follow()
    assert 'Your local account has been updated' in response.text

    # Try to relink with another sub
    response = app.get('/fc/callback/?next=/accounts/')
    location = response['Location']
    state = check_authorization_url(location)
    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    sub = 'xyz'
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    response = response.follow()
    assert 'Your account is already linked to a FranceConnect account' in response.text
    sub = '1234'

    # Unlink
    response = response.click('Delete link')
    response.form.set('new_password1', 'ikKL1234')
    response.form.set('new_password2', 'ikKL1234')
    response = response.form.submit(name='unlink')
    continue_url = response.pyquery('a#a2-continue').attr['href']
    state = urlparse.parse_qs(urlparse.urlparse(continue_url).query)['state'][0]
    assert app.session['fc_states'][state]['next'] == '/accounts/'
    response = app.get(reverse('fc-logout') + '?state=' + state)
    assert path(response['Location']) == '/accounts/'
    response = response.follow()
    assert len(response.pyquery('[href*="password/change"]')) > 0


def test_migration_0002(migration):
    migrate_from = [('authentic2_auth_fc', '0001_initial')]
    # it's a two-parts migration, as it contains data and schema changes.
    migrate_to = [('authentic2_auth_fc', '0003_fcaccount_order2')]

    old_apps = migration.before(migrate_from)

    User = old_apps.get_model('custom_user', 'User')
    FcAccount = old_apps.get_model('authentic2_auth_fc', 'FcAccount')
    user1 = User.objects.create(username='user1')
    user2 = User.objects.create(username='user2')
    user3 = User.objects.create(username='user3')
    FcAccount.objects.create(user=user1, sub='sub1')
    FcAccount.objects.create(user=user1, sub='sub2')
    FcAccount.objects.create(user=user2, sub='sub2')
    FcAccount.objects.create(user=user2, sub='sub3')
    FcAccount.objects.create(user=user3, sub='sub3')
    assert len(set(FcAccount.objects.values_list('user_id', flat=True))) == 3
    assert len(set(FcAccount.objects.values_list('sub', flat=True))) == 3
    assert FcAccount.objects.count() == 5

    # execute migration
    new_apps = migration.apply(migrate_to)
    FcAccount = new_apps.get_model('authentic2_auth_fc', 'FcAccount')
    assert len(set(FcAccount.objects.values_list('user_id', 'order'))) == 5
    assert len(set(FcAccount.objects.values_list('sub', 'order'))) == 5


def test_link_with_already_linked_sub(app, simple_user, fc_settings, caplog, hooks):
    sub = '1234'

    other_user = User.objects.create()
    models.FcAccount.objects.create(
        user=other_user,
        sub='1234',
        user_info='',
        order=0,
        token='')

    response = app.get('/accounts/').follow()
    response.form.set('username', simple_user.username)
    response.form.set('password', simple_user.username)
    response = response.form.submit(name='login-password-submit').follow()
    response = response.click('Link')

    exp = timestamp_from_datetime(now() + datetime.timedelta(seconds=1000))
    # 1. Try a login
    # 2. Verify we come back to login page
    # 3. Check presence of registration link
    # 4. Follow it
    location = response['Location']
    state = check_authorization_url(location)

    @httmock.urlmatch(path=r'.*/token$')
    def access_token_response(url, request):
        parsed = {x: y[0] for x, y in urlparse.parse_qs(request.body).items()}
        assert set(parsed.keys()) == set(['code', 'client_id', 'client_secret', 'redirect_uri',
                                          'grant_type'])
        assert parsed['code'] == 'zzz'
        assert parsed['client_id'] == 'xxx'
        assert parsed['client_secret'] == 'yyy'
        assert parsed['grant_type'] == 'authorization_code'
        assert callback in parsed['redirect_uri']
        id_token = {
            'sub': sub,
            'aud': 'xxx',
            'nonce': state,
            'exp': exp,
            'iss': 'https://fcp.integ01.dev-franceconnect.fr/',
            'email': 'john.doe@example.com',
        }
        return json.dumps({
            'access_token': 'uuu',
            'id_token': hmac_jwt(id_token, 'yyy')
        })

    @httmock.urlmatch(path=r'.*userinfo$')
    def user_info_response(url, request):
        assert request.headers['Authorization'] == 'Bearer uuu'
        return json.dumps({
            'sub': sub,
            'family_name': u'Frédérique',
            'given_name': u'Ÿuñe',
            'email': 'john.doe@example.com',
        })

    callback = urlparse.parse_qs(urlparse.urlparse(location).query)['redirect_uri'][0]
    with httmock.HTTMock(access_token_response, user_info_response):
        response = app.get(callback + '&code=zzz&state=%s' % state, status=302)
    response = response.follow()
    assert 'is already linked with another account.' in response.text