User management (#15420)

* User management

* Lint

* Fix dict

* Reuse data instance

* OrderedDict all the way
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2018-07-13 15:31:20 +02:00
1 parent 84858f5c19
commit 70fe463ef0
21 files changed
+982 -116

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
"""Test config entries API."""
from unittest.mock import PropertyMock, patch
import pytest
from homeassistant.auth import models as auth_models
from homeassistant.components.config import auth as auth_config
from tests.common import MockUser, CLIENT_ID
@pytest.fixture(autouse=True)
def auth_active(hass):
"""Mock that auth is active."""
with patch('homeassistant.auth.AuthManager.active',
PropertyMock(return_value=True)):
yield
@pytest.fixture(autouse=True)
def setup_config(hass, aiohttp_client):
"""Fixture that sets up the auth provider homeassistant module."""
hass.loop.run_until_complete(auth_config.async_setup(hass))
async def test_list_requires_owner(hass, hass_ws_client, hass_access_token):
"""Test get users requires auth."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_LIST,
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
async def test_list(hass, hass_ws_client):
"""Test get users."""
owner = MockUser(
id='abc',
name='Test Owner',
is_owner=True,
).add_to_hass(hass)
owner.credentials.append(auth_models.Credentials(
auth_provider_type='homeassistant',
auth_provider_id=None,
data={},
))
system = MockUser(
id='efg',
name='Test Hass.io',
system_generated=True
).add_to_hass(hass)
inactive = MockUser(
id='hij',
name='Inactive User',
is_active=False,
).add_to_hass(hass)
refresh_token = await hass.auth.async_create_refresh_token(
owner, CLIENT_ID)
access_token = hass.auth.async_create_access_token(refresh_token)
client = await hass_ws_client(hass, access_token)
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_LIST,
})
result = await client.receive_json()
assert result['success'], result
data = result['result']
assert len(data) == 3
assert data[0] == {
'id': owner.id,
'name': 'Test Owner',
'is_owner': True,
'is_active': True,
'system_generated': False,
'credentials': [{'type': 'homeassistant'}]
}
assert data[1] == {
'id': system.id,
'name': 'Test Hass.io',
'is_owner': False,
'is_active': True,
'system_generated': True,
'credentials': [],
}
assert data[2] == {
'id': inactive.id,
'name': 'Inactive User',
'is_owner': False,
'is_active': False,
'system_generated': False,
'credentials': [],
}
async def test_delete_requires_owner(hass, hass_ws_client, hass_access_token):
"""Test delete command requires an owner."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_DELETE,
'user_id': 'abcd',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
async def test_delete_unable_self_account(hass, hass_ws_client,
hass_access_token):
"""Test we cannot delete our own account."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_DELETE,
'user_id': hass_access_token.refresh_token.user.id,
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
async def test_delete_unknown_user(hass, hass_ws_client, hass_access_token):
"""Test we cannot delete an unknown user."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_DELETE,
'user_id': 'abcd',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'not_found'
async def test_delete(hass, hass_ws_client, hass_access_token):
"""Test delete command works."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
test_user = MockUser(
id='efg',
).add_to_hass(hass)
assert len(await hass.auth.async_get_users()) == 2
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_DELETE,
'user_id': test_user.id,
})
result = await client.receive_json()
assert result['success'], result
assert len(await hass.auth.async_get_users()) == 1
async def test_create(hass, hass_ws_client, hass_access_token):
"""Test create command works."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
assert len(await hass.auth.async_get_users()) == 1
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_CREATE,
'name': 'Paulus',
})
result = await client.receive_json()
assert result['success'], result
assert len(await hass.auth.async_get_users()) == 2
data_user = result['result']['user']
user = await hass.auth.async_get_user(data_user['id'])
assert user is not None
assert user.name == data_user['name']
assert user.is_active
assert not user.is_owner
assert not user.system_generated
async def test_create_requires_owner(hass, hass_ws_client, hass_access_token):
"""Test create command requires an owner."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_config.WS_TYPE_CREATE,
'name': 'YO',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
@@ -0,0 +1,229 @@
"""Test config entries API."""
import pytest
from homeassistant.auth.providers import homeassistant as prov_ha
from homeassistant.components.config import (
auth_provider_homeassistant as auth_ha)
from tests.common import MockUser, register_auth_provider
@pytest.fixture(autouse=True)
def setup_config(hass, aiohttp_client):
"""Fixture that sets up the auth provider homeassistant module."""
hass.loop.run_until_complete(register_auth_provider(hass, {
'type': 'homeassistant'
}))
hass.loop.run_until_complete(auth_ha.async_setup(hass))
async def test_create_auth_system_generated_user(hass, hass_access_token,
hass_ws_client):
"""Test we can't add auth to system generated users."""
system_user = MockUser(system_generated=True).add_to_hass(hass)
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_CREATE,
'user_id': system_user.id,
'username': 'test-user',
'password': 'test-pass',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'system_generated'
async def test_create_auth_user_already_credentials():
"""Test we can't create auth for user with pre-existing credentials."""
# assert False
async def test_create_auth_unknown_user(hass_ws_client, hass,
hass_access_token):
"""Test create pointing at unknown user."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_CREATE,
'user_id': 'test-id',
'username': 'test-user',
'password': 'test-pass',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'not_found'
async def test_create_auth_requires_owner(hass, hass_ws_client,
hass_access_token):
"""Test create requires owner to call API."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_CREATE,
'user_id': 'test-id',
'username': 'test-user',
'password': 'test-pass',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
async def test_create_auth(hass, hass_ws_client, hass_access_token,
hass_storage):
"""Test create auth command works."""
client = await hass_ws_client(hass, hass_access_token)
user = MockUser().add_to_hass(hass)
hass_access_token.refresh_token.user.is_owner = True
assert len(user.credentials) == 0
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_CREATE,
'user_id': user.id,
'username': 'test-user',
'password': 'test-pass',
})
result = await client.receive_json()
assert result['success'], result
assert len(user.credentials) == 1
creds = user.credentials[0]
assert creds.auth_provider_type == 'homeassistant'
assert creds.auth_provider_id is None
assert creds.data == {
'username': 'test-user'
}
assert prov_ha.STORAGE_KEY in hass_storage
entry = hass_storage[prov_ha.STORAGE_KEY]['data']['users'][0]
assert entry['username'] == 'test-user'
async def test_create_auth_duplicate_username(hass, hass_ws_client,
hass_access_token, hass_storage):
"""Test we can't create auth with a duplicate username."""
client = await hass_ws_client(hass, hass_access_token)
user = MockUser().add_to_hass(hass)
hass_access_token.refresh_token.user.is_owner = True
hass_storage[prov_ha.STORAGE_KEY] = {
'version': 1,
'data': {
'users': [{
'username': 'test-user'
}]
}
}
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_CREATE,
'user_id': user.id,
'username': 'test-user',
'password': 'test-pass',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'username_exists'
async def test_delete_removes_just_auth(hass_ws_client, hass, hass_storage,
hass_access_token):
"""Test deleting an auth without being connected to a user."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
hass_storage[prov_ha.STORAGE_KEY] = {
'version': 1,
'data': {
'users': [{
'username': 'test-user'
}]
}
}
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_DELETE,
'username': 'test-user',
})
result = await client.receive_json()
assert result['success'], result
assert len(hass_storage[prov_ha.STORAGE_KEY]['data']['users']) == 0
async def test_delete_removes_credential(hass, hass_ws_client,
hass_access_token, hass_storage):
"""Test deleting auth that is connected to a user."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
user = MockUser().add_to_hass(hass)
user.credentials.append(
await hass.auth.auth_providers[0].async_get_or_create_credentials({
'username': 'test-user'}))
hass_storage[prov_ha.STORAGE_KEY] = {
'version': 1,
'data': {
'users': [{
'username': 'test-user'
}]
}
}
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_DELETE,
'username': 'test-user',
})
result = await client.receive_json()
assert result['success'], result
assert len(hass_storage[prov_ha.STORAGE_KEY]['data']['users']) == 0
async def test_delete_requires_owner(hass, hass_ws_client, hass_access_token):
"""Test delete requires owner."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_DELETE,
'username': 'test-user',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'unauthorized'
async def test_delete_unknown_auth(hass, hass_ws_client, hass_access_token):
"""Test trying to delete an unknown auth username."""
client = await hass_ws_client(hass, hass_access_token)
hass_access_token.refresh_token.user.is_owner = True
await client.send_json({
'id': 5,
'type': auth_ha.WS_TYPE_DELETE,
'username': 'test-user',
})
result = await client.receive_json()
assert not result['success'], result
assert result['error']['code'] == 'auth_not_found'
+16 -1
View File
@@ -2,6 +2,7 @@
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components import websocket_api
from tests.common import MockUser, CLIENT_ID
@@ -9,13 +10,27 @@ from tests.common import MockUser, CLIENT_ID
@pytest.fixture
def hass_ws_client(aiohttp_client):
"""Websocket client fixture connected to websocket server."""
async def create_client(hass):
async def create_client(hass, access_token=None):
"""Create a websocket client."""
wapi = hass.components.websocket_api
assert await async_setup_component(hass, 'websocket_api')
client = await aiohttp_client(hass.http.app)
websocket = await client.ws_connect(wapi.URL)
auth_resp = await websocket.receive_json()
if auth_resp['type'] == wapi.TYPE_AUTH_OK:
assert access_token is None, \
'Access token given but no auth required'
return websocket
assert access_token is not None, 'Access token required for fixture'
await websocket.send_json({
'type': websocket_api.TYPE_AUTH,
'access_token': access_token.token
})
auth_ok = await websocket.receive_json()
assert auth_ok['type'] == wapi.TYPE_AUTH_OK
+14 -27
View File
@@ -1,13 +1,12 @@
"""The tests for the Home Assistant HTTP component."""
# pylint: disable=protected-access
from ipaddress import ip_network
from unittest.mock import patch, Mock
from unittest.mock import patch
import pytest
from aiohttp import BasicAuth, web
from aiohttp.web_exceptions import HTTPUnauthorized
from homeassistant.auth.models import AccessToken, RefreshToken
from homeassistant.components.http.auth import setup_auth
from homeassistant.components.http.const import KEY_AUTHENTICATED
from homeassistant.components.http.real_ip import setup_real_ip
@@ -16,8 +15,6 @@ from homeassistant.setup import async_setup_component
from . import mock_real_ip
ACCESS_TOKEN = 'tk.1234'
API_PASSWORD = 'test1234'
# Don't add 127.0.0.1/::1 as trusted, as it may interfere with other test cases
@@ -39,33 +36,21 @@ async def mock_handler(request):
return web.Response(status=200)
def mock_async_get_access_token(token):
"""Return if token is valid."""
if token == ACCESS_TOKEN:
return Mock(spec=AccessToken,
token=ACCESS_TOKEN,
refresh_token=Mock(spec=RefreshToken))
else:
return None
@pytest.fixture
def app():
def app(hass):
"""Fixture to setup a web.Application."""
app = web.Application()
mock_auth = Mock(async_get_access_token=mock_async_get_access_token)
app['hass'] = Mock(auth=mock_auth)
app['hass'] = hass
app.router.add_get('/', mock_handler)
setup_real_ip(app, False, [])
return app
@pytest.fixture
def app2():
def app2(hass):
"""Fixture to setup a web.Application without real_ip middleware."""
app = web.Application()
mock_auth = Mock(async_get_access_token=mock_async_get_access_token)
app['hass'] = Mock(auth=mock_auth)
app['hass'] = hass
app.router.add_get('/', mock_handler)
return app
@@ -171,33 +156,35 @@ async def test_access_with_trusted_ip(app2, aiohttp_client):
async def test_auth_active_access_with_access_token_in_header(
app, aiohttp_client):
app, aiohttp_client, hass_access_token):
"""Test access with access token in header."""
token = hass_access_token.token
setup_auth(app, [], True, api_password=None)
client = await aiohttp_client(app)
req = await client.get(
'/', headers={'Authorization': 'Bearer {}'.format(ACCESS_TOKEN)})
'/', headers={'Authorization': 'Bearer {}'.format(token)})
assert req.status == 200
req = await client.get(
'/', headers={'AUTHORIZATION': 'Bearer {}'.format(ACCESS_TOKEN)})
'/', headers={'AUTHORIZATION': 'Bearer {}'.format(token)})
assert req.status == 200
req = await client.get(
'/', headers={'authorization': 'Bearer {}'.format(ACCESS_TOKEN)})
'/', headers={'authorization': 'Bearer {}'.format(token)})
assert req.status == 200
req = await client.get(
'/', headers={'Authorization': ACCESS_TOKEN})
'/', headers={'Authorization': token})
assert req.status == 401
req = await client.get(
'/', headers={'Authorization': 'BEARER {}'.format(ACCESS_TOKEN)})
'/', headers={'Authorization': 'BEARER {}'.format(token)})
assert req.status == 401
hass_access_token.refresh_token.user.is_active = False
req = await client.get(
'/', headers={'Authorization': 'Bearer wrong-pass'})
'/', headers={'Authorization': 'Bearer {}'.format(token)})
assert req.status == 401