2019-03-19 11:49:10 +00:00
|
|
|
import uuid
|
2021-05-17 15:56:15 +01:00
|
|
|
from unittest.mock import Mock, call
|
2018-02-20 11:22:17 +00:00
|
|
|
|
|
|
|
|
import pytest
|
2021-05-17 15:56:15 +01:00
|
|
|
from notifications_python_client.errors import HTTPError
|
2018-02-20 11:22:17 +00:00
|
|
|
|
2018-04-19 13:15:52 +01:00
|
|
|
from app import invite_api_client, service_api_client, user_api_client
|
Support registering a new authenticator
This adds Yubico's FIDO2 library and two APIs for working with the
"navigator.credentials.create()" function in JavaScript. The GET
API uses the library to generate options for the "create()" function,
and the POST API decodes and verifies the resulting credential. While
the options and response are dict-like, CBOR is necessary to encode
some of the byte-level values, which can't be represented in JSON.
Much of the code here is based on the Yubico library example [1][2].
Implementation notes:
- There are definitely better ways to alert the user about failure, but
window.alert() will do for the time being. Using location.reload() is
also a bit jarring if the page scrolls, but not a major issue.
- Ideally we would use window.fetch() to do AJAX calls, but we don't
have a polyfill for this, and we use $.ajax() elsewhere [3]. We need
to do a few weird tricks [6] to stop jQuery trashing the data.
- The FIDO2 server doesn't serve web requests; it's just a "server" in
the sense of WebAuthn terminology. It lives in its own module, since it
needs to be initialised with the app / config.
- $.ajax returns a promise-like object. Although we've used ".fail()"
elsewhere [3], I couldn't find a stub object that supports it, so I've
gone for ".catch()", and used a Promise stub object in tests.
- WebAuthn only works over HTTPS, but there's an exception for "localhost"
[4]. However, the library is a bit too strict [5], so we have to disable
origin verification to avoid needing HTTPS for dev work.
[1]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/server.py
[2]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/static/register.html
[3]: https://github.com/alphagov/notifications-admin/blob/91453d36395b7a0cf2998dfb8a5f52cc9e96640f/app/assets/javascripts/updateContent.js#L33
[4]: https://stackoverflow.com/questions/55971593/navigator-credentials-is-null-on-local-server
[5]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/fido2/rpid.py#L69
[6]: https://stackoverflow.com/questions/12394622/does-jquery-ajax-or-load-allow-for-responsetype-arraybuffer
2021-05-07 18:10:07 +01:00
|
|
|
from app.models.webauthn_credential import WebAuthnCredential
|
2018-09-26 16:41:04 +01:00
|
|
|
from tests import sample_uuid
|
2019-12-19 16:59:07 +00:00
|
|
|
from tests.conftest import SERVICE_ONE_ID
|
2018-02-21 09:26:42 +00:00
|
|
|
|
2018-09-26 16:41:04 +01:00
|
|
|
user_id = sample_uuid()
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
|
2018-02-21 09:26:42 +00:00
|
|
|
|
|
|
|
|
def test_client_gets_all_users_for_service(
|
|
|
|
|
mocker,
|
|
|
|
|
fake_uuid,
|
|
|
|
|
):
|
|
|
|
|
|
|
|
|
|
user_api_client.max_failed_login_count = 99 # doesn't matter for this test
|
|
|
|
|
mock_get = mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.get',
|
|
|
|
|
return_value={'data': [
|
|
|
|
|
{'id': fake_uuid},
|
|
|
|
|
]}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
users = user_api_client.get_users_for_service(SERVICE_ONE_ID)
|
|
|
|
|
|
|
|
|
|
mock_get.assert_called_once_with('/service/{}/users'.format(SERVICE_ONE_ID))
|
|
|
|
|
assert len(users) == 1
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
assert users[0]['id'] == fake_uuid
|
2018-02-21 10:18:56 +00:00
|
|
|
|
|
|
|
|
|
2016-02-23 12:47:48 +00:00
|
|
|
def test_client_uses_correct_find_by_email(mocker, api_user_active):
|
|
|
|
|
|
|
|
|
|
expected_url = '/user/email'
|
2021-03-05 15:05:48 +00:00
|
|
|
expected_data = {'email': api_user_active['email_address']}
|
2016-02-23 12:47:48 +00:00
|
|
|
|
2018-02-09 15:04:52 +00:00
|
|
|
user_api_client.max_failed_login_count = 1 # doesn't matter for this test
|
2021-03-05 12:43:15 +00:00
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
2016-02-23 12:47:48 +00:00
|
|
|
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
user_api_client.get_user_by_email(api_user_active['email_address'])
|
2016-02-23 12:47:48 +00:00
|
|
|
|
2021-03-05 15:05:48 +00:00
|
|
|
mock_post.assert_called_once_with(expected_url, data=expected_data)
|
2016-11-09 15:06:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_client_only_updates_allowed_attributes(mocker):
|
|
|
|
|
mocker.patch('app.notify_client.current_user', id='1')
|
|
|
|
|
with pytest.raises(TypeError) as error:
|
2018-02-09 15:04:52 +00:00
|
|
|
user_api_client.update_user_attribute('user_id', id='1')
|
2016-11-09 15:06:02 +00:00
|
|
|
assert str(error.value) == 'Not allowed to update user attributes: id'
|
2017-02-07 13:31:46 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_client_updates_password_separately(mocker, api_user_active):
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
expected_url = '/user/{}/update-password'.format(api_user_active['id'])
|
2017-02-07 13:31:46 +00:00
|
|
|
expected_params = {'_password': 'newpassword'}
|
2018-02-09 15:04:52 +00:00
|
|
|
user_api_client.max_failed_login_count = 1 # doesn't matter for this test
|
2017-02-07 13:31:46 +00:00
|
|
|
mock_update_password = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
user_api_client.update_password(api_user_active['id'], expected_params['_password'])
|
2017-02-07 13:31:46 +00:00
|
|
|
mock_update_password.assert_called_once_with(expected_url, data=expected_params)
|
2017-11-09 14:37:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_client_activates_if_pending(mocker, api_user_pending):
|
|
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
2018-02-09 15:04:52 +00:00
|
|
|
user_api_client.max_failed_login_count = 1 # doesn't matter for this test
|
2017-11-09 14:37:33 +00:00
|
|
|
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
user_api_client.activate_user(api_user_pending['id'])
|
2017-11-09 14:37:33 +00:00
|
|
|
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
mock_post.assert_called_once_with('/user/{}/activate'.format(api_user_pending['id']), data=None)
|
2018-02-09 15:01:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_client_passes_admin_url_when_sending_email_auth(
|
2021-05-12 14:57:21 +01:00
|
|
|
notify_admin,
|
2018-02-09 15:01:20 +00:00
|
|
|
mocker,
|
|
|
|
|
fake_uuid,
|
|
|
|
|
):
|
|
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
|
|
|
|
|
user_api_client.send_verify_code(fake_uuid, 'email', 'ignored@example.com')
|
|
|
|
|
|
|
|
|
|
mock_post.assert_called_once_with(
|
|
|
|
|
'/user/{}/email-code'.format(fake_uuid),
|
|
|
|
|
data={
|
|
|
|
|
'to': 'ignored@example.com',
|
|
|
|
|
'email_auth_link_host': 'http://localhost:6012',
|
|
|
|
|
}
|
|
|
|
|
)
|
2018-02-28 15:37:49 +00:00
|
|
|
|
|
|
|
|
|
2021-05-12 14:57:21 +01:00
|
|
|
def test_client_converts_admin_permissions_to_db_permissions_on_edit(notify_admin, mocker):
|
2018-02-28 15:37:49 +00:00
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
|
|
|
|
|
user_api_client.set_user_permissions('user_id', 'service_id', permissions={'send_messages', 'view_activity'})
|
|
|
|
|
|
2019-02-21 15:06:41 +00:00
|
|
|
assert sorted(mock_post.call_args[1]['data']['permissions'], key=lambda x: x['permission']) == sorted([
|
2018-02-28 15:37:49 +00:00
|
|
|
{'permission': 'send_texts'},
|
|
|
|
|
{'permission': 'send_emails'},
|
|
|
|
|
{'permission': 'send_letters'},
|
|
|
|
|
{'permission': 'view_activity'},
|
|
|
|
|
], key=lambda x: x['permission'])
|
|
|
|
|
|
|
|
|
|
|
2021-05-12 14:57:21 +01:00
|
|
|
def test_client_converts_admin_permissions_to_db_permissions_on_add_to_service(notify_admin, mocker):
|
2018-02-28 15:37:49 +00:00
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post', return_value={'data': {}})
|
|
|
|
|
|
2019-03-15 14:57:39 +00:00
|
|
|
user_api_client.add_user_to_service('service_id',
|
|
|
|
|
'user_id',
|
|
|
|
|
permissions={'send_messages', 'view_activity'},
|
|
|
|
|
folder_permissions=[])
|
2018-02-28 15:37:49 +00:00
|
|
|
|
2019-03-12 16:54:48 +00:00
|
|
|
assert sorted(mock_post.call_args[1]['data']['permissions'], key=lambda x: x['permission']) == sorted([
|
2018-02-28 15:37:49 +00:00
|
|
|
{'permission': 'send_texts'},
|
|
|
|
|
{'permission': 'send_emails'},
|
|
|
|
|
{'permission': 'send_letters'},
|
|
|
|
|
{'permission': 'view_activity'},
|
|
|
|
|
], key=lambda x: x['permission'])
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
|
(
|
|
|
|
|
'expected_cache_get_calls,'
|
|
|
|
|
'cache_value,'
|
|
|
|
|
'expected_api_calls,'
|
|
|
|
|
'expected_cache_set_calls,'
|
|
|
|
|
'expected_return_value,'
|
|
|
|
|
),
|
|
|
|
|
[
|
|
|
|
|
(
|
|
|
|
|
[
|
|
|
|
|
call('user-{}'.format(user_id))
|
|
|
|
|
],
|
|
|
|
|
b'{"data": "from cache"}',
|
|
|
|
|
[],
|
|
|
|
|
[],
|
|
|
|
|
'from cache',
|
|
|
|
|
),
|
|
|
|
|
(
|
|
|
|
|
[
|
|
|
|
|
call('user-{}'.format(user_id))
|
|
|
|
|
],
|
|
|
|
|
None,
|
|
|
|
|
[
|
|
|
|
|
call('/user/{}'.format(user_id))
|
|
|
|
|
],
|
|
|
|
|
[
|
|
|
|
|
call(
|
|
|
|
|
'user-{}'.format(user_id),
|
|
|
|
|
'{"data": "from api"}',
|
2018-04-23 17:07:41 +01:00
|
|
|
ex=604800
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
)
|
|
|
|
|
],
|
|
|
|
|
'from api',
|
|
|
|
|
),
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
def test_returns_value_from_cache(
|
2021-05-12 14:57:21 +01:00
|
|
|
notify_admin,
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
mocker,
|
|
|
|
|
expected_cache_get_calls,
|
|
|
|
|
cache_value,
|
|
|
|
|
expected_return_value,
|
|
|
|
|
expected_api_calls,
|
|
|
|
|
expected_cache_set_calls,
|
|
|
|
|
):
|
|
|
|
|
|
|
|
|
|
mock_redis_get = mocker.patch(
|
2019-02-14 14:25:31 +00:00
|
|
|
'app.extensions.RedisClient.get',
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
return_value=cache_value,
|
|
|
|
|
)
|
|
|
|
|
mock_api_get = mocker.patch(
|
|
|
|
|
'app.notify_client.NotifyAdminAPIClient.get',
|
|
|
|
|
return_value={'data': 'from api'},
|
|
|
|
|
)
|
|
|
|
|
mock_redis_set = mocker.patch(
|
2019-02-14 14:25:31 +00:00
|
|
|
'app.extensions.RedisClient.set',
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
user_api_client.get_user(user_id)
|
|
|
|
|
|
|
|
|
|
assert mock_redis_get.call_args_list == expected_cache_get_calls
|
|
|
|
|
assert mock_api_get.call_args_list == expected_api_calls
|
|
|
|
|
assert mock_redis_set.call_args_list == expected_cache_set_calls
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize('client, method, extra_args, extra_kwargs', [
|
2019-03-15 14:57:39 +00:00
|
|
|
(user_api_client, 'add_user_to_service', [SERVICE_ONE_ID, sample_uuid(), [], []], {}),
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
(user_api_client, 'update_user_attribute', [user_id], {}),
|
|
|
|
|
(user_api_client, 'reset_failed_login_count', [user_id], {}),
|
|
|
|
|
(user_api_client, 'update_user_attribute', [user_id], {}),
|
|
|
|
|
(user_api_client, 'update_password', [user_id, 'hunter2'], {}),
|
|
|
|
|
(user_api_client, 'verify_password', [user_id, 'hunter2'], {}),
|
|
|
|
|
(user_api_client, 'check_verify_code', [user_id, '', ''], {}),
|
2021-05-17 15:56:15 +01:00
|
|
|
(user_api_client, 'complete_webauthn_login_attempt', [user_id], {'is_successful': True}),
|
2019-03-15 14:57:39 +00:00
|
|
|
(user_api_client, 'add_user_to_service', [SERVICE_ONE_ID, user_id, [], []], {}),
|
2018-09-26 16:41:04 +01:00
|
|
|
(user_api_client, 'add_user_to_organisation', [sample_uuid(), user_id], {}),
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
(user_api_client, 'set_user_permissions', [user_id, SERVICE_ONE_ID, []], {}),
|
2019-12-19 16:59:07 +00:00
|
|
|
(user_api_client, 'activate_user', [user_id], {}),
|
2019-05-22 11:38:47 +01:00
|
|
|
(user_api_client, 'archive_user', [user_id], {}),
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
(service_api_client, 'remove_user_from_service', [SERVICE_ONE_ID, user_id], {}),
|
2019-04-12 17:00:11 +01:00
|
|
|
(service_api_client, 'create_service', ['', '', 0, False, user_id, sample_uuid()], {}),
|
2018-04-19 13:15:52 +01:00
|
|
|
(invite_api_client, 'accept_invite', [SERVICE_ONE_ID, user_id], {}),
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
])
|
|
|
|
|
def test_deletes_user_cache(
|
2021-05-12 14:57:21 +01:00
|
|
|
notify_admin,
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
mock_get_user,
|
|
|
|
|
mocker,
|
|
|
|
|
client,
|
|
|
|
|
method,
|
|
|
|
|
extra_args,
|
|
|
|
|
extra_kwargs,
|
|
|
|
|
):
|
|
|
|
|
mocker.patch('app.notify_client.current_user', id='1')
|
2019-02-14 14:25:31 +00:00
|
|
|
mock_redis_delete = mocker.patch('app.extensions.RedisClient.delete')
|
Cache `GET /user` response in Redis
In the same way, and for the same reasons that we’re caching the service
object.
Here’s a sample of the data returned by the API – so we should make sure
that any changes to this data invalidate the cache.
If we ever change a user’s phone number (for example) directly in the
database, then we will need to invalidate this cache manually.
```python
{
'data':{
'organisations':[
'4c707b81-4c6d-4d33-9376-17f0de6e0405'
],
'logged_in_at':'2018-04-10T11:41:03.781990Z',
'id':'2c45486e-177e-40b8-997d-5f4f81a461ca',
'email_address':'test@example.gov.uk',
'platform_admin':False,
'password_changed_at':'2018-01-01 10:10:10.100000',
'permissions':{
'42a9d4f2-1444-4e22-9133-52d9e406213f':[
'manage_api_keys',
'send_letters',
'manage_users',
'manage_templates',
'view_activity',
'send_texts',
'send_emails',
'manage_settings'
],
'a928eef8-0f25-41ca-b480-0447f29b2c20':[
'manage_users',
'manage_templates',
'manage_settings',
'send_texts',
'send_emails',
'send_letters',
'manage_api_keys',
'view_activity'
],
},
'state':'active',
'mobile_number':'07700900123',
'failed_login_count':0,
'name':'Example',
'services':[
'6078a8c0-52f5-4c4f-b724-d7d1ff2d3884',
'6afe3c1c-7fda-4d8d-aa8d-769c4bdf7803',
],
'current_session_id':'fea2ade1-db0a-4c90-93e7-c64a877ce83e',
'auth_type':'sms_auth'
}
}
```
2018-04-10 13:30:52 +01:00
|
|
|
mock_request = mocker.patch('notifications_python_client.base.BaseAPIClient.request')
|
|
|
|
|
|
|
|
|
|
getattr(client, method)(*extra_args, **extra_kwargs)
|
|
|
|
|
|
|
|
|
|
assert call('user-{}'.format(user_id)) in mock_redis_delete.call_args_list
|
|
|
|
|
assert len(mock_request.call_args_list) == 1
|
2019-03-19 11:49:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_add_user_to_service_calls_correct_endpoint_and_deletes_keys_from_cache(mocker):
|
|
|
|
|
mock_redis_delete = mocker.patch('app.extensions.RedisClient.delete')
|
|
|
|
|
|
|
|
|
|
service_id = uuid.uuid4()
|
|
|
|
|
user_id = uuid.uuid4()
|
|
|
|
|
folder_id = uuid.uuid4()
|
|
|
|
|
|
|
|
|
|
expected_url = '/service/{}/users/{}'.format(service_id, user_id)
|
|
|
|
|
data = {'permissions': [], 'folder_permissions': [folder_id]}
|
|
|
|
|
|
|
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
|
|
|
|
|
user_api_client.add_user_to_service(service_id, user_id, [], [folder_id])
|
|
|
|
|
|
|
|
|
|
mock_post.assert_called_once_with(expected_url, data=data)
|
|
|
|
|
assert mock_redis_delete.call_args_list == [
|
|
|
|
|
call('user-{user_id}'.format(user_id=user_id)),
|
2019-07-26 16:19:03 +01:00
|
|
|
call('service-{service_id}-template-folders'.format(service_id=service_id)),
|
|
|
|
|
call('service-{service_id}'.format(service_id=service_id)),
|
2019-03-19 11:49:10 +00:00
|
|
|
]
|
2021-05-07 15:00:01 +01:00
|
|
|
|
|
|
|
|
|
2021-05-13 15:54:05 +01:00
|
|
|
def test_get_webauthn_credentials_for_user(mocker, webauthn_credential, fake_uuid):
|
Support registering a new authenticator
This adds Yubico's FIDO2 library and two APIs for working with the
"navigator.credentials.create()" function in JavaScript. The GET
API uses the library to generate options for the "create()" function,
and the POST API decodes and verifies the resulting credential. While
the options and response are dict-like, CBOR is necessary to encode
some of the byte-level values, which can't be represented in JSON.
Much of the code here is based on the Yubico library example [1][2].
Implementation notes:
- There are definitely better ways to alert the user about failure, but
window.alert() will do for the time being. Using location.reload() is
also a bit jarring if the page scrolls, but not a major issue.
- Ideally we would use window.fetch() to do AJAX calls, but we don't
have a polyfill for this, and we use $.ajax() elsewhere [3]. We need
to do a few weird tricks [6] to stop jQuery trashing the data.
- The FIDO2 server doesn't serve web requests; it's just a "server" in
the sense of WebAuthn terminology. It lives in its own module, since it
needs to be initialised with the app / config.
- $.ajax returns a promise-like object. Although we've used ".fail()"
elsewhere [3], I couldn't find a stub object that supports it, so I've
gone for ".catch()", and used a Promise stub object in tests.
- WebAuthn only works over HTTPS, but there's an exception for "localhost"
[4]. However, the library is a bit too strict [5], so we have to disable
origin verification to avoid needing HTTPS for dev work.
[1]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/server.py
[2]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/static/register.html
[3]: https://github.com/alphagov/notifications-admin/blob/91453d36395b7a0cf2998dfb8a5f52cc9e96640f/app/assets/javascripts/updateContent.js#L33
[4]: https://stackoverflow.com/questions/55971593/navigator-credentials-is-null-on-local-server
[5]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/fido2/rpid.py#L69
[6]: https://stackoverflow.com/questions/12394622/does-jquery-ajax-or-load-allow-for-responsetype-arraybuffer
2021-05-07 18:10:07 +01:00
|
|
|
|
2021-05-13 15:54:05 +01:00
|
|
|
mock_get = mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.get',
|
|
|
|
|
return_value={'data': [webauthn_credential]}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
credentials = user_api_client.get_webauthn_credentials_for_user(fake_uuid)
|
|
|
|
|
|
|
|
|
|
mock_get.assert_called_once_with(f'/user/{fake_uuid}/webauthn')
|
|
|
|
|
assert len(credentials) == 1
|
|
|
|
|
assert credentials[0]['name'] == 'Test credential'
|
Support registering a new authenticator
This adds Yubico's FIDO2 library and two APIs for working with the
"navigator.credentials.create()" function in JavaScript. The GET
API uses the library to generate options for the "create()" function,
and the POST API decodes and verifies the resulting credential. While
the options and response are dict-like, CBOR is necessary to encode
some of the byte-level values, which can't be represented in JSON.
Much of the code here is based on the Yubico library example [1][2].
Implementation notes:
- There are definitely better ways to alert the user about failure, but
window.alert() will do for the time being. Using location.reload() is
also a bit jarring if the page scrolls, but not a major issue.
- Ideally we would use window.fetch() to do AJAX calls, but we don't
have a polyfill for this, and we use $.ajax() elsewhere [3]. We need
to do a few weird tricks [6] to stop jQuery trashing the data.
- The FIDO2 server doesn't serve web requests; it's just a "server" in
the sense of WebAuthn terminology. It lives in its own module, since it
needs to be initialised with the app / config.
- $.ajax returns a promise-like object. Although we've used ".fail()"
elsewhere [3], I couldn't find a stub object that supports it, so I've
gone for ".catch()", and used a Promise stub object in tests.
- WebAuthn only works over HTTPS, but there's an exception for "localhost"
[4]. However, the library is a bit too strict [5], so we have to disable
origin verification to avoid needing HTTPS for dev work.
[1]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/server.py
[2]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/static/register.html
[3]: https://github.com/alphagov/notifications-admin/blob/91453d36395b7a0cf2998dfb8a5f52cc9e96640f/app/assets/javascripts/updateContent.js#L33
[4]: https://stackoverflow.com/questions/55971593/navigator-credentials-is-null-on-local-server
[5]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/fido2/rpid.py#L69
[6]: https://stackoverflow.com/questions/12394622/does-jquery-ajax-or-load-allow-for-responsetype-arraybuffer
2021-05-07 18:10:07 +01:00
|
|
|
|
2021-05-13 15:54:05 +01:00
|
|
|
|
|
|
|
|
def test_create_webauthn_credential_for_user(mocker, webauthn_credential, fake_uuid):
|
Support registering a new authenticator
This adds Yubico's FIDO2 library and two APIs for working with the
"navigator.credentials.create()" function in JavaScript. The GET
API uses the library to generate options for the "create()" function,
and the POST API decodes and verifies the resulting credential. While
the options and response are dict-like, CBOR is necessary to encode
some of the byte-level values, which can't be represented in JSON.
Much of the code here is based on the Yubico library example [1][2].
Implementation notes:
- There are definitely better ways to alert the user about failure, but
window.alert() will do for the time being. Using location.reload() is
also a bit jarring if the page scrolls, but not a major issue.
- Ideally we would use window.fetch() to do AJAX calls, but we don't
have a polyfill for this, and we use $.ajax() elsewhere [3]. We need
to do a few weird tricks [6] to stop jQuery trashing the data.
- The FIDO2 server doesn't serve web requests; it's just a "server" in
the sense of WebAuthn terminology. It lives in its own module, since it
needs to be initialised with the app / config.
- $.ajax returns a promise-like object. Although we've used ".fail()"
elsewhere [3], I couldn't find a stub object that supports it, so I've
gone for ".catch()", and used a Promise stub object in tests.
- WebAuthn only works over HTTPS, but there's an exception for "localhost"
[4]. However, the library is a bit too strict [5], so we have to disable
origin verification to avoid needing HTTPS for dev work.
[1]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/server.py
[2]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/examples/server/static/register.html
[3]: https://github.com/alphagov/notifications-admin/blob/91453d36395b7a0cf2998dfb8a5f52cc9e96640f/app/assets/javascripts/updateContent.js#L33
[4]: https://stackoverflow.com/questions/55971593/navigator-credentials-is-null-on-local-server
[5]: https://github.com/Yubico/python-fido2/blob/c42d9628a4f33d20c4401096fa8d3fc466d5b77f/fido2/rpid.py#L69
[6]: https://stackoverflow.com/questions/12394622/does-jquery-ajax-or-load-allow-for-responsetype-arraybuffer
2021-05-07 18:10:07 +01:00
|
|
|
credential = WebAuthnCredential(webauthn_credential)
|
2021-05-13 15:54:05 +01:00
|
|
|
|
|
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
expected_url = f'/user/{fake_uuid}/webauthn'
|
|
|
|
|
|
|
|
|
|
user_api_client.create_webauthn_credential_for_user(fake_uuid, credential)
|
|
|
|
|
mock_post.assert_called_once_with(expected_url, data=credential.serialize())
|
2021-05-17 15:56:15 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_complete_webauthn_login_attempt_returns_true_and_no_message_normally(fake_uuid, mocker):
|
|
|
|
|
mock_post = mocker.patch('app.notify_client.user_api_client.UserApiClient.post')
|
|
|
|
|
|
|
|
|
|
resp = user_api_client.complete_webauthn_login_attempt(fake_uuid, is_successful=True)
|
|
|
|
|
|
|
|
|
|
expected_data = {'successful': True}
|
2021-06-03 12:46:31 +01:00
|
|
|
mock_post.assert_called_once_with(f'/user/{fake_uuid}/complete/webauthn-login', data=expected_data)
|
2021-05-17 15:56:15 +01:00
|
|
|
assert resp == (True, '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_complete_webauthn_login_attempt_returns_false_and_message_on_403(fake_uuid, mocker):
|
|
|
|
|
mock_post = mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.post',
|
|
|
|
|
side_effect=HTTPError(
|
|
|
|
|
response=Mock(
|
|
|
|
|
status_code=403,
|
|
|
|
|
json=Mock(
|
|
|
|
|
return_value={'message': 'forbidden'}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
resp = user_api_client.complete_webauthn_login_attempt(fake_uuid, is_successful=True)
|
|
|
|
|
|
|
|
|
|
expected_data = {'successful': True}
|
2021-06-03 12:46:31 +01:00
|
|
|
mock_post.assert_called_once_with(f'/user/{fake_uuid}/complete/webauthn-login', data=expected_data)
|
2021-05-17 15:56:15 +01:00
|
|
|
|
|
|
|
|
assert resp == (False, 'forbidden')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_complete_webauthn_login_attempt_raises_on_api_error(fake_uuid, mocker):
|
|
|
|
|
mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.post',
|
|
|
|
|
side_effect=HTTPError(response=Mock(status_code=503, message='error'))
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
with pytest.raises(HTTPError):
|
|
|
|
|
user_api_client.complete_webauthn_login_attempt(fake_uuid, is_successful=True)
|
2022-02-02 16:24:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_reset_password(
|
|
|
|
|
mocker,
|
|
|
|
|
fake_uuid,
|
|
|
|
|
):
|
|
|
|
|
mock_post = mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.post'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
user_api_client.send_reset_password_url('test@example.com')
|
|
|
|
|
|
|
|
|
|
mock_post.assert_called_once_with(
|
|
|
|
|
'/user/reset-password',
|
|
|
|
|
data={
|
|
|
|
|
'email': 'test@example.com',
|
|
|
|
|
'admin_base_url': 'http://localhost:6012',
|
|
|
|
|
},
|
|
|
|
|
)
|
2022-03-07 15:11:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_send_registration_email(
|
|
|
|
|
mocker,
|
|
|
|
|
fake_uuid,
|
|
|
|
|
):
|
|
|
|
|
mock_post = mocker.patch(
|
|
|
|
|
'app.notify_client.user_api_client.UserApiClient.post'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
user_api_client.send_verify_email(fake_uuid, 'test@example.com')
|
|
|
|
|
|
|
|
|
|
mock_post.assert_called_once_with(
|
|
|
|
|
f'/user/{fake_uuid}/email-verification',
|
|
|
|
|
data={
|
|
|
|
|
'to': 'test@example.com',
|
|
|
|
|
'admin_base_url': 'http://localhost:6012',
|
|
|
|
|
},
|
|
|
|
|
)
|