Add permission checks to Rest API (#18639)
* Add permission checks to Rest API * Clean up unnecessary method * Remove all the tuple stuff from entity check * Simplify perms * Correct param name for owner permission * Hass.io make/update user to be admin * Types
This commit is contained in:
1 parent
f9f71c4a6d
commit
3a8303137a
15 files changed
+282
-145
No files matched your search
@@ -10,7 +10,7 @@ def test_entities_none():
|
||||
"""Test entity ID policy."""
|
||||
policy = None
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is False
|
||||
assert compiled('light.kitchen', 'read') is False
|
||||
|
||||
|
||||
def test_entities_empty():
|
||||
@@ -18,7 +18,7 @@ def test_entities_empty():
|
||||
policy = {}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is False
|
||||
assert compiled('light.kitchen', 'read') is False
|
||||
|
||||
|
||||
def test_entities_false():
|
||||
@@ -33,7 +33,7 @@ def test_entities_true():
|
||||
policy = True
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
|
||||
|
||||
def test_entities_domains_true():
|
||||
@@ -43,7 +43,7 @@ def test_entities_domains_true():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
|
||||
|
||||
def test_entities_domains_domain_true():
|
||||
@@ -55,8 +55,8 @@ def test_entities_domains_domain_true():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('switch.kitchen', ('read',)) is False
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('switch.kitchen', 'read') is False
|
||||
|
||||
|
||||
def test_entities_domains_domain_false():
|
||||
@@ -77,7 +77,7 @@ def test_entities_entity_ids_true():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
|
||||
|
||||
def test_entities_entity_ids_false():
|
||||
@@ -98,8 +98,8 @@ def test_entities_entity_ids_entity_id_true():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('switch.kitchen', ('read',)) is False
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('switch.kitchen', 'read') is False
|
||||
|
||||
|
||||
def test_entities_entity_ids_entity_id_false():
|
||||
@@ -124,9 +124,9 @@ def test_entities_control_only():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', ('control',)) is False
|
||||
assert compiled('light.kitchen', ('edit',)) is False
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('light.kitchen', 'control') is False
|
||||
assert compiled('light.kitchen', 'edit') is False
|
||||
|
||||
|
||||
def test_entities_read_control():
|
||||
@@ -141,9 +141,9 @@ def test_entities_read_control():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', ('control',)) is True
|
||||
assert compiled('light.kitchen', ('edit',)) is False
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('light.kitchen', 'control') is True
|
||||
assert compiled('light.kitchen', 'edit') is False
|
||||
|
||||
|
||||
def test_entities_all_allow():
|
||||
@@ -153,9 +153,9 @@ def test_entities_all_allow():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', ('control',)) is True
|
||||
assert compiled('switch.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('light.kitchen', 'control') is True
|
||||
assert compiled('switch.kitchen', 'read') is True
|
||||
|
||||
|
||||
def test_entities_all_read():
|
||||
@@ -167,9 +167,9 @@ def test_entities_all_read():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', ('control',)) is False
|
||||
assert compiled('switch.kitchen', ('read',)) is True
|
||||
assert compiled('light.kitchen', 'read') is True
|
||||
assert compiled('light.kitchen', 'control') is False
|
||||
assert compiled('switch.kitchen', 'read') is True
|
||||
|
||||
|
||||
def test_entities_all_control():
|
||||
@@ -181,7 +181,7 @@ def test_entities_all_control():
|
||||
}
|
||||
ENTITY_POLICY_SCHEMA(policy)
|
||||
compiled = compile_entities(policy)
|
||||
assert compiled('light.kitchen', ('read',)) is False
|
||||
assert compiled('light.kitchen', ('control',)) is True
|
||||
assert compiled('switch.kitchen', ('read',)) is False
|
||||
assert compiled('switch.kitchen', ('control',)) is True
|
||||
assert compiled('light.kitchen', 'read') is False
|
||||
assert compiled('light.kitchen', 'control') is True
|
||||
assert compiled('switch.kitchen', 'read') is False
|
||||
assert compiled('switch.kitchen', 'control') is True
|
||||
@@ -1,34 +0,0 @@
|
||||
"""Tests for the auth permission system."""
|
||||
from homeassistant.core import State
|
||||
from homeassistant.auth import permissions
|
||||
|
||||
|
||||
def test_policy_perm_filter_states():
|
||||
"""Test filtering entitites."""
|
||||
states = [
|
||||
State('light.kitchen', 'on'),
|
||||
State('light.living_room', 'off'),
|
||||
State('light.balcony', 'on'),
|
||||
]
|
||||
perm = permissions.PolicyPermissions({
|
||||
'entities': {
|
||||
'entity_ids': {
|
||||
'light.kitchen': True,
|
||||
'light.balcony': True,
|
||||
}
|
||||
}
|
||||
})
|
||||
filtered = perm.filter_states(states)
|
||||
assert len(filtered) == 2
|
||||
assert filtered == [states[0], states[2]]
|
||||
|
||||
|
||||
def test_owner_permissions():
|
||||
"""Test owner permissions access all."""
|
||||
assert permissions.OwnerPermissions.check_entity('light.kitchen', 'write')
|
||||
states = [
|
||||
State('light.kitchen', 'on'),
|
||||
State('light.living_room', 'off'),
|
||||
State('light.balcony', 'on'),
|
||||
]
|
||||
assert permissions.OwnerPermissions.filter_states(states) == states
|
||||
+6
-1
@@ -14,7 +14,8 @@ from contextlib import contextmanager
|
||||
|
||||
from homeassistant import auth, core as ha, config_entries
|
||||
from homeassistant.auth import (
|
||||
models as auth_models, auth_store, providers as auth_providers)
|
||||
models as auth_models, auth_store, providers as auth_providers,
|
||||
permissions as auth_permissions)
|
||||
from homeassistant.auth.permissions import system_policies
|
||||
from homeassistant.setup import setup_component, async_setup_component
|
||||
from homeassistant.config import async_process_component_config
|
||||
@@ -400,6 +401,10 @@ class MockUser(auth_models.User):
|
||||
auth_mgr._store._users[self.id] = self
|
||||
return self
|
||||
|
||||
def mock_policy(self, policy):
|
||||
"""Mock a policy for a user."""
|
||||
self._permissions = auth_permissions.PolicyPermissions(policy)
|
||||
|
||||
|
||||
async def register_auth_provider(hass, config):
|
||||
"""Register an auth provider."""
|
||||
|
||||
@@ -72,11 +72,10 @@ def hass_ws_client(aiohttp_client):
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hass_access_token(hass):
|
||||
def hass_access_token(hass, hass_admin_user):
|
||||
"""Return an access token to access Home Assistant."""
|
||||
user = MockUser().add_to_hass(hass)
|
||||
refresh_token = hass.loop.run_until_complete(
|
||||
hass.auth.async_create_refresh_token(user, CLIENT_ID))
|
||||
hass.auth.async_create_refresh_token(hass_admin_user, CLIENT_ID))
|
||||
yield hass.auth.async_create_access_token(refresh_token)
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from unittest.mock import patch, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.auth.const import GROUP_ID_ADMIN
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.components.hassio import (
|
||||
STORAGE_KEY, async_check_config)
|
||||
@@ -106,6 +107,8 @@ async def test_setup_api_push_api_data_default(hass, aioclient_mock,
|
||||
)
|
||||
assert hassio_user is not None
|
||||
assert hassio_user.system_generated
|
||||
assert len(hassio_user.groups) == 1
|
||||
assert hassio_user.groups[0].id == GROUP_ID_ADMIN
|
||||
for token in hassio_user.refresh_tokens.values():
|
||||
if token.token == refresh_token:
|
||||
break
|
||||
@@ -113,6 +116,31 @@ async def test_setup_api_push_api_data_default(hass, aioclient_mock,
|
||||
assert False, 'refresh token not found'
|
||||
|
||||
|
||||
async def test_setup_adds_admin_group_to_user(hass, aioclient_mock,
|
||||
hass_storage):
|
||||
"""Test setup with API push default data."""
|
||||
# Create user without admin
|
||||
user = await hass.auth.async_create_system_user('Hass.io')
|
||||
assert not user.is_admin
|
||||
await hass.auth.async_create_refresh_token(user)
|
||||
|
||||
hass_storage[STORAGE_KEY] = {
|
||||
'data': {'hassio_user': user.id},
|
||||
'key': STORAGE_KEY,
|
||||
'version': 1
|
||||
}
|
||||
|
||||
with patch.dict(os.environ, MOCK_ENVIRON), \
|
||||
patch('homeassistant.auth.AuthManager.active', return_value=True):
|
||||
result = await async_setup_component(hass, 'hassio', {
|
||||
'http': {},
|
||||
'hassio': {}
|
||||
})
|
||||
assert result
|
||||
|
||||
assert user.is_admin
|
||||
|
||||
|
||||
async def test_setup_api_push_api_data_no_auth(hass, aioclient_mock,
|
||||
hass_storage):
|
||||
"""Test setup with API push default data."""
|
||||
|
||||
@@ -16,10 +16,12 @@ from tests.common import async_mock_service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_api_client(hass, aiohttp_client):
|
||||
"""Start the Hass HTTP component."""
|
||||
def mock_api_client(hass, aiohttp_client, hass_access_token):
|
||||
"""Start the Hass HTTP component and return admin API client."""
|
||||
hass.loop.run_until_complete(async_setup_component(hass, 'api', {}))
|
||||
return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
|
||||
return hass.loop.run_until_complete(aiohttp_client(hass.http.app, headers={
|
||||
'Authorization': 'Bearer {}'.format(hass_access_token)
|
||||
}))
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
@@ -405,7 +407,8 @@ def _listen_count(hass):
|
||||
return sum(hass.bus.async_listeners().values())
|
||||
|
||||
|
||||
async def test_api_error_log(hass, aiohttp_client):
|
||||
async def test_api_error_log(hass, aiohttp_client, hass_access_token,
|
||||
hass_admin_user):
|
||||
"""Test if we can fetch the error log."""
|
||||
hass.data[DATA_LOGGING] = '/some/path'
|
||||
await async_setup_component(hass, 'api', {
|
||||
@@ -416,7 +419,7 @@ async def test_api_error_log(hass, aiohttp_client):
|
||||
client = await aiohttp_client(hass.http.app)
|
||||
|
||||
resp = await client.get(const.URL_API_ERROR_LOG)
|
||||
# Verufy auth required
|
||||
# Verify auth required
|
||||
assert resp.status == 401
|
||||
|
||||
with patch(
|
||||
@@ -424,7 +427,7 @@ async def test_api_error_log(hass, aiohttp_client):
|
||||
return_value=web.Response(status=200, text='Hello')
|
||||
) as mock_file:
|
||||
resp = await client.get(const.URL_API_ERROR_LOG, headers={
|
||||
'x-ha-access': 'yolo'
|
||||
'Authorization': 'Bearer {}'.format(hass_access_token)
|
||||
})
|
||||
|
||||
assert len(mock_file.mock_calls) == 1
|
||||
@@ -432,6 +435,13 @@ async def test_api_error_log(hass, aiohttp_client):
|
||||
assert resp.status == 200
|
||||
assert await resp.text() == 'Hello'
|
||||
|
||||
# Verify we require admin user
|
||||
hass_admin_user.groups = []
|
||||
resp = await client.get(const.URL_API_ERROR_LOG, headers={
|
||||
'Authorization': 'Bearer {}'.format(hass_access_token)
|
||||
})
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_api_fire_event_context(hass, mock_api_client,
|
||||
hass_access_token):
|
||||
@@ -494,3 +504,67 @@ async def test_api_set_state_context(hass, mock_api_client, hass_access_token):
|
||||
|
||||
state = hass.states.get('light.kitchen')
|
||||
assert state.context.user_id == refresh_token.user.id
|
||||
|
||||
|
||||
async def test_event_stream_requires_admin(hass, mock_api_client,
|
||||
hass_admin_user):
|
||||
"""Test user needs to be admin to access event stream."""
|
||||
hass_admin_user.groups = []
|
||||
resp = await mock_api_client.get('/api/stream')
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_states_view_filters(hass, mock_api_client, hass_admin_user):
|
||||
"""Test filtering only visible states."""
|
||||
hass_admin_user.mock_policy({
|
||||
'entities': {
|
||||
'entity_ids': {
|
||||
'test.entity': True
|
||||
}
|
||||
}
|
||||
})
|
||||
hass.states.async_set('test.entity', 'hello')
|
||||
hass.states.async_set('test.not_visible_entity', 'invisible')
|
||||
resp = await mock_api_client.get(const.URL_API_STATES)
|
||||
assert resp.status == 200
|
||||
json = await resp.json()
|
||||
assert len(json) == 1
|
||||
assert json[0]['entity_id'] == 'test.entity'
|
||||
|
||||
|
||||
async def test_get_entity_state_read_perm(hass, mock_api_client,
|
||||
hass_admin_user):
|
||||
"""Test getting a state requires read permission."""
|
||||
hass_admin_user.mock_policy({})
|
||||
resp = await mock_api_client.get('/api/states/light.test')
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_post_entity_state_admin(hass, mock_api_client, hass_admin_user):
|
||||
"""Test updating state requires admin."""
|
||||
hass_admin_user.groups = []
|
||||
resp = await mock_api_client.post('/api/states/light.test')
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_delete_entity_state_admin(hass, mock_api_client,
|
||||
hass_admin_user):
|
||||
"""Test deleting entity requires admin."""
|
||||
hass_admin_user.groups = []
|
||||
resp = await mock_api_client.delete('/api/states/light.test')
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_post_event_admin(hass, mock_api_client, hass_admin_user):
|
||||
"""Test sending event requires admin."""
|
||||
hass_admin_user.groups = []
|
||||
resp = await mock_api_client.post('/api/events/state_changed')
|
||||
assert resp.status == 401
|
||||
|
||||
|
||||
async def test_rendering_template_admin(hass, mock_api_client,
|
||||
hass_admin_user):
|
||||
"""Test rendering a template requires admin."""
|
||||
hass_admin_user.groups = []
|
||||
resp = await mock_api_client.post('/api/template')
|
||||
assert resp.status == 401
|
||||
Reference in new issue
Block a user