Foundation for users (#13968)

* Add initial user foundation to Home Assistant

* Address comments

* Address comments

* Allow non-ascii passwords

* One more utf-8 hmac compare digest

* Add new line
This commit is contained in:
Paulus Schoutsen authored and Pascal Vizeli committed 2018-05-01 18:20:41 +02:00
1 parent b994c10d7f
commit cdd45e7878
22 files changed
+1774 -59

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
"""Tests for the auth component."""
from aiohttp.helpers import BasicAuth
from homeassistant import auth
from homeassistant.setup import async_setup_component
from tests.common import ensure_auth_manager_loaded
BASE_CONFIG = [{
'name': 'Example',
'type': 'insecure_example',
'users': [{
'username': 'test-user',
'password': 'test-pass',
'name': 'Test Name'
}]
}]
CLIENT_ID = 'test-id'
CLIENT_SECRET = 'test-secret'
CLIENT_AUTH = BasicAuth(CLIENT_ID, CLIENT_SECRET)
async def async_setup_auth(hass, aiohttp_client, provider_configs=BASE_CONFIG,
setup_api=False):
"""Helper to setup authentication and create a HTTP client."""
hass.auth = await auth.auth_manager_from_config(hass, provider_configs)
ensure_auth_manager_loaded(hass.auth)
await async_setup_component(hass, 'auth', {
'http': {
'api_password': 'bla'
}
})
client = auth.Client('Test Client', CLIENT_ID, CLIENT_SECRET)
hass.auth._store.clients[client.id] = client
if setup_api:
await async_setup_component(hass, 'api', {})
return await aiohttp_client(hass.http.app)
+70
View File
@@ -0,0 +1,70 @@
"""Tests for the client validator."""
from aiohttp.helpers import BasicAuth
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components.auth.client import verify_client
from homeassistant.components.http.view import HomeAssistantView
from . import async_setup_auth
@pytest.fixture
def mock_view(hass):
"""Register a view that verifies client id/secret."""
hass.loop.run_until_complete(async_setup_component(hass, 'http', {}))
clients = []
class ClientView(HomeAssistantView):
url = '/'
name = 'bla'
@verify_client
async def get(self, request, client_id):
"""Handle GET request."""
clients.append(client_id)
hass.http.register_view(ClientView)
return clients
async def test_verify_client(hass, aiohttp_client, mock_view):
"""Test that verify client can extract client auth from a request."""
http_client = await async_setup_auth(hass, aiohttp_client)
client = await hass.auth.async_create_client('Hello')
resp = await http_client.get('/', auth=BasicAuth(client.id, client.secret))
assert resp.status == 200
assert mock_view == [client.id]
async def test_verify_client_no_auth_header(hass, aiohttp_client, mock_view):
"""Test that verify client will decline unknown client id."""
http_client = await async_setup_auth(hass, aiohttp_client)
resp = await http_client.get('/')
assert resp.status == 401
assert mock_view == []
async def test_verify_client_invalid_client_id(hass, aiohttp_client,
mock_view):
"""Test that verify client will decline unknown client id."""
http_client = await async_setup_auth(hass, aiohttp_client)
client = await hass.auth.async_create_client('Hello')
resp = await http_client.get('/', auth=BasicAuth('invalid', client.secret))
assert resp.status == 401
assert mock_view == []
async def test_verify_client_invalid_client_secret(hass, aiohttp_client,
mock_view):
"""Test that verify client will decline incorrect client secret."""
http_client = await async_setup_auth(hass, aiohttp_client)
client = await hass.auth.async_create_client('Hello')
resp = await http_client.get('/', auth=BasicAuth(client.id, 'invalid'))
assert resp.status == 401
assert mock_view == []
+53
View File
@@ -0,0 +1,53 @@
"""Integration tests for the auth component."""
from . import async_setup_auth, CLIENT_AUTH
async def test_login_new_user_and_refresh_token(hass, aiohttp_client):
"""Test logging in with new user and refreshing tokens."""
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
resp = await client.post('/auth/login_flow', json={
'handler': ['insecure_example', None]
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'username': 'test-user',
'password': 'test-pass',
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
code = step['result']
# Exchange code for tokens
resp = await client.post('/auth/token', data={
'grant_type': 'authorization_code',
'code': code
}, auth=CLIENT_AUTH)
assert resp.status == 200
tokens = await resp.json()
assert hass.auth.async_get_access_token(tokens['access_token']) is not None
# Use refresh token to get more tokens.
resp = await client.post('/auth/token', data={
'grant_type': 'refresh_token',
'refresh_token': tokens['refresh_token']
}, auth=CLIENT_AUTH)
assert resp.status == 200
tokens = await resp.json()
assert 'refresh_token' not in tokens
assert hass.auth.async_get_access_token(tokens['access_token']) is not None
# Test using access token to hit API.
resp = await client.get('/api/')
assert resp.status == 401
resp = await client.get('/api/', headers={
'authorization': 'Bearer {}'.format(tokens['access_token'])
})
assert resp.status == 200
@@ -0,0 +1,150 @@
"""Tests for the link user flow."""
from . import async_setup_auth, CLIENT_AUTH, CLIENT_ID
async def async_get_code(hass, aiohttp_client):
"""Helper for link user tests that returns authorization code."""
config = [{
'name': 'Example',
'type': 'insecure_example',
'users': [{
'username': 'test-user',
'password': 'test-pass',
'name': 'Test Name'
}]
}, {
'name': 'Example',
'id': '2nd auth',
'type': 'insecure_example',
'users': [{
'username': '2nd-user',
'password': '2nd-pass',
'name': '2nd Name'
}]
}]
client = await async_setup_auth(hass, aiohttp_client, config)
resp = await client.post('/auth/login_flow', json={
'handler': ['insecure_example', None]
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'username': 'test-user',
'password': 'test-pass',
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
code = step['result']
# Exchange code for tokens
resp = await client.post('/auth/token', data={
'grant_type': 'authorization_code',
'code': code
}, auth=CLIENT_AUTH)
assert resp.status == 200
tokens = await resp.json()
access_token = hass.auth.async_get_access_token(tokens['access_token'])
assert access_token is not None
user = access_token.refresh_token.user
assert len(user.credentials) == 1
# Now authenticate with the 2nd flow
resp = await client.post('/auth/login_flow', json={
'handler': ['insecure_example', '2nd auth']
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'username': '2nd-user',
'password': '2nd-pass',
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
return {
'user': user,
'code': step['result'],
'client': client,
'tokens': tokens,
}
async def test_link_user(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
tokens = info['tokens']
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': code
}, headers={
'authorization': 'Bearer {}'.format(tokens['access_token'])
})
assert resp.status == 200
assert len(info['user'].credentials) == 2
async def test_link_user_invalid_client_id(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
tokens = info['tokens']
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': 'invalid',
'code': code
}, headers={
'authorization': 'Bearer {}'.format(tokens['access_token'])
})
assert resp.status == 400
assert len(info['user'].credentials) == 1
async def test_link_user_invalid_code(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
tokens = info['tokens']
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': 'invalid'
}, headers={
'authorization': 'Bearer {}'.format(tokens['access_token'])
})
assert resp.status == 400
assert len(info['user'].credentials) == 1
async def test_link_user_invalid_auth(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': code,
}, headers={'authorization': 'Bearer invalid'})
assert resp.status == 401
assert len(info['user'].credentials) == 1
@@ -0,0 +1,66 @@
"""Tests for the login flow."""
from aiohttp.helpers import BasicAuth
from . import async_setup_auth, CLIENT_AUTH
async def test_fetch_auth_providers(hass, aiohttp_client):
"""Test fetching auth providers."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.get('/auth/providers', auth=CLIENT_AUTH)
assert await resp.json() == [{
'name': 'Example',
'type': 'insecure_example',
'id': None
}]
async def test_fetch_auth_providers_require_valid_client(hass, aiohttp_client):
"""Test fetching auth providers."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.get('/auth/providers',
auth=BasicAuth('invalid', 'bla'))
assert resp.status == 401
async def test_cannot_get_flows_in_progress(hass, aiohttp_client):
"""Test we cannot get flows in progress."""
client = await async_setup_auth(hass, aiohttp_client, [])
resp = await client.get('/auth/login_flow')
assert resp.status == 405
async def test_invalid_username_password(hass, aiohttp_client):
"""Test we cannot get flows in progress."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.post('/auth/login_flow', json={
'handler': ['insecure_example', None]
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
# Incorrect username
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'username': 'wrong-user',
'password': 'test-pass',
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'
# Incorrect password
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'username': 'test-user',
'password': 'wrong-pass',
}, auth=CLIENT_AUTH)
assert resp.status == 200
step = await resp.json()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'