This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+94 -85
View File
@@ -7,139 +7,148 @@ from tests.common import MockUser
async def test_validate(hass):
"""Test validating pin."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "insecure_example",
"data": [{"user_id": "test-user", "pin": "123456"}],
},
)
result = await auth_module.async_validate(
'test-user', {'pin': '123456'})
result = await auth_module.async_validate("test-user", {"pin": "123456"})
assert result is True
result = await auth_module.async_validate(
'test-user', {'pin': 'invalid'})
result = await auth_module.async_validate("test-user", {"pin": "invalid"})
assert result is False
result = await auth_module.async_validate(
'invalid-user', {'pin': '123456'})
result = await auth_module.async_validate("invalid-user", {"pin": "123456"})
assert result is False
async def test_setup_user(hass):
"""Test setup user."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': []
})
auth_module = await auth_mfa_module_from_config(
hass, {"type": "insecure_example", "data": []}
)
await auth_module.async_setup_user(
'test-user', {'pin': '123456'})
await auth_module.async_setup_user("test-user", {"pin": "123456"})
assert len(auth_module._data) == 1
result = await auth_module.async_validate(
'test-user', {'pin': '123456'})
result = await auth_module.async_validate("test-user", {"pin": "123456"})
assert result is True
async def test_depose_user(hass):
"""Test despose user."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "insecure_example",
"data": [{"user_id": "test-user", "pin": "123456"}],
},
)
assert len(auth_module._data) == 1
await auth_module.async_depose_user('test-user')
await auth_module.async_depose_user("test-user")
assert len(auth_module._data) == 0
async def test_is_user_setup(hass):
"""Test is user setup."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
assert await auth_module.async_is_user_setup('test-user') is True
assert await auth_module.async_is_user_setup('invalid-user') is False
auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "insecure_example",
"data": [{"user_id": "test-user", "pin": "123456"}],
},
)
assert await auth_module.async_is_user_setup("test-user") is True
assert await auth_module.async_is_user_setup("invalid-user") is False
async def test_login(hass):
"""Test login flow with auth module."""
hass.auth = await auth.auth_manager_from_config(hass, [{
'type': 'insecure_example',
'users': [{'username': 'test-user', 'password': 'test-pass'}],
}], [{
'type': 'insecure_example',
'data': [{'user_id': 'mock-user', 'pin': '123456'}]
}])
hass.auth = await auth.auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[
{
"type": "insecure_example",
"data": [{"user_id": "mock-user", "pin": "123456"}],
}
],
)
user = MockUser(
id='mock-user',
is_owner=False,
is_active=False,
name='Paulus',
id="mock-user", is_owner=False, is_active=False, name="Paulus"
).add_to_auth_manager(hass.auth)
await hass.auth.async_link_user(user, Credentials(
id='mock-id',
auth_provider_type='insecure_example',
auth_provider_id=None,
data={'username': 'test-user'},
is_new=False,
))
await hass.auth.async_link_user(
user,
Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'test-user',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result["flow_id"], {"username": "test-user", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['data_schema'].schema.get('pin') == str
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("pin") == str
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'pin': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_code'
result["flow_id"], {"pin": "invalid-code"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_code"
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'pin': '123456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data'].id == 'mock-user'
result["flow_id"], {"pin": "123456"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"].id == "mock-user"
async def test_setup_flow(hass):
"""Test validating pin."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "insecure_example",
"data": [{"user_id": "test-user", "pin": "123456"}],
},
)
flow = await auth_module.async_setup_flow('new-user')
flow = await auth_module.async_setup_flow("new-user")
result = await flow.async_step_init()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await flow.async_step_init({'pin': 'abcdefg'})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert auth_module._data[1]['user_id'] == 'new-user'
assert auth_module._data[1]['pin'] == 'abcdefg'
result = await flow.async_step_init({"pin": "abcdefg"})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert auth_module._data[1]["user_id"] == "new-user"
assert auth_module._data[1]["pin"] == "abcdefg"
+212 -232
View File
@@ -8,84 +8,73 @@ from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.components.notify import NOTIFY_SERVICE_SCHEMA
from tests.common import MockUser, async_mock_service
MOCK_CODE = '123456'
MOCK_CODE_2 = '654321'
MOCK_CODE = "123456"
MOCK_CODE_2 = "654321"
async def test_validating_mfa(hass):
"""Test validating mfa code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
await notify_auth_module.async_setup_user('test-user', {
'notify_service': 'dummy'
})
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
with patch('pyotp.HOTP.verify', return_value=True):
assert await notify_auth_module.async_validate(
'test-user', {'code': MOCK_CODE})
with patch("pyotp.HOTP.verify", return_value=True):
assert await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
async def test_validating_mfa_invalid_code(hass):
"""Test validating an invalid mfa code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
await notify_auth_module.async_setup_user('test-user', {
'notify_service': 'dummy'
})
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
with patch('pyotp.HOTP.verify', return_value=False):
assert await notify_auth_module.async_validate(
'test-user', {'code': MOCK_CODE}) is False
with patch("pyotp.HOTP.verify", return_value=False):
assert (
await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_invalid_user(hass):
"""Test validating an mfa code with invalid user."""
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
await notify_auth_module.async_setup_user('test-user', {
'notify_service': 'dummy'
})
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
assert await notify_auth_module.async_validate(
'invalid-user', {'code': MOCK_CODE}) is False
assert (
await notify_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_counter(hass):
"""Test counter will move only after generate code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
await notify_auth_module.async_setup_user('test-user', {
'counter': 0,
'notify_service': 'dummy',
})
async_mock_service(hass, 'notify', 'dummy')
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user(
"test-user", {"counter": 0, "notify_service": "dummy"}
)
async_mock_service(hass, "notify", "dummy")
assert notify_auth_module._user_settings
notify_setting = list(notify_auth_module._user_settings.values())[0]
init_count = notify_setting.counter
assert init_count is not None
with patch('pyotp.HOTP.at', return_value=MOCK_CODE):
await notify_auth_module.async_initialize_login_mfa_step('test-user')
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
await notify_auth_module.async_initialize_login_mfa_step("test-user")
notify_setting = list(notify_auth_module._user_settings.values())[0]
after_generate_count = notify_setting.counter
assert after_generate_count != init_count
with patch('pyotp.HOTP.verify', return_value=True):
assert await notify_auth_module.async_validate(
'test-user', {'code': MOCK_CODE})
with patch("pyotp.HOTP.verify", return_value=True):
assert await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
notify_setting = list(notify_auth_module._user_settings.values())[0]
assert after_generate_count == notify_setting.counter
with patch('pyotp.HOTP.verify', return_value=False):
assert await notify_auth_module.async_validate(
'test-user', {'code': MOCK_CODE}) is False
with patch("pyotp.HOTP.verify", return_value=False):
assert (
await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
notify_setting = list(notify_auth_module._user_settings.values())[0]
assert after_generate_count == notify_setting.counter
@@ -93,99 +82,96 @@ async def test_validating_mfa_counter(hass):
async def test_setup_depose_user(hass):
"""Test set up and despose user."""
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
await notify_auth_module.async_setup_user('test-user', {})
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {})
assert len(notify_auth_module._user_settings) == 1
await notify_auth_module.async_setup_user('test-user', {})
await notify_auth_module.async_setup_user("test-user", {})
assert len(notify_auth_module._user_settings) == 1
await notify_auth_module.async_depose_user('test-user')
await notify_auth_module.async_depose_user("test-user")
assert len(notify_auth_module._user_settings) == 0
await notify_auth_module.async_setup_user(
'test-user2', {'secret': 'secret-code'})
await notify_auth_module.async_setup_user("test-user2", {"secret": "secret-code"})
assert len(notify_auth_module._user_settings) == 1
async def test_login_flow_validates_mfa(hass):
"""Test login flow with mfa enabled."""
hass.auth = await auth_manager_from_config(hass, [{
'type': 'insecure_example',
'users': [{'username': 'test-user', 'password': 'test-pass'}],
}], [{
'type': 'notify',
}])
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "notify"}],
)
user = MockUser(
id='mock-user',
is_owner=False,
is_active=False,
name='Paulus',
id="mock-user", is_owner=False, is_active=False, name="Paulus"
).add_to_auth_manager(hass.auth)
await hass.auth.async_link_user(user, auth_models.Credentials(
id='mock-id',
auth_provider_type='insecure_example',
auth_provider_id=None,
data={'username': 'test-user'},
is_new=False,
))
await hass.auth.async_link_user(
user,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
notify_calls = async_mock_service(hass, 'notify', 'test-notify',
NOTIFY_SERVICE_SCHEMA)
notify_calls = async_mock_service(
hass, "notify", "test-notify", NOTIFY_SERVICE_SCHEMA
)
await hass.auth.async_enable_user_mfa(user, 'notify', {
'notify_service': 'test-notify',
})
await hass.auth.async_enable_user_mfa(
user, "notify", {"notify_service": "test-notify"}
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_configure(result['flow_id'], {
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.auth.login_flow.async_configure(result['flow_id'], {
'username': 'test-user',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
with patch('pyotp.HOTP.at', return_value=MOCK_CODE):
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result['flow_id'],
{
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['data_schema'].schema.get('code') == str
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") == str
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 1
notify_call = notify_calls[0]
assert notify_call.domain == 'notify'
assert notify_call.service == 'test-notify'
message = notify_call.data['message']
assert notify_call.domain == "notify"
assert notify_call.service == "test-notify"
message = notify_call.data["message"]
message.hass = hass
assert MOCK_CODE in message.async_render()
with patch('pyotp.HOTP.verify', return_value=False):
with patch("pyotp.HOTP.verify", return_value=False):
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['errors']['base'] == 'invalid_code'
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
# wait service call finished
await hass.async_block_till_done()
@@ -194,205 +180,202 @@ async def test_login_flow_validates_mfa(hass):
assert len(notify_calls) == 1
# retry twice
with patch('pyotp.HOTP.verify', return_value=False), \
patch('pyotp.HOTP.at', return_value=MOCK_CODE_2):
with patch("pyotp.HOTP.verify", return_value=False), patch(
"pyotp.HOTP.at", return_value=MOCK_CODE_2
):
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['errors']['base'] == 'invalid_code'
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
# after the 3rd failure, flow abort
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_ABORT
assert result['reason'] == 'too_many_retry'
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "too_many_retry"
# wait service call finished
await hass.async_block_till_done()
# restart login
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
with patch('pyotp.HOTP.at', return_value=MOCK_CODE):
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result['flow_id'],
{
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['data_schema'].schema.get('code') == str
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") == str
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 2
notify_call = notify_calls[1]
assert notify_call.domain == 'notify'
assert notify_call.service == 'test-notify'
message = notify_call.data['message']
assert notify_call.domain == "notify"
assert notify_call.service == "test-notify"
message = notify_call.data["message"]
message.hass = hass
assert MOCK_CODE in message.async_render()
with patch('pyotp.HOTP.verify', return_value=True):
with patch("pyotp.HOTP.verify", return_value=True):
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': MOCK_CODE})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data'].id == 'mock-user'
result["flow_id"], {"code": MOCK_CODE}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"].id == "mock-user"
async def test_setup_user_notify_service(hass):
"""Test allow select notify service during mfa setup."""
notify_calls = async_mock_service(
hass, 'notify', 'test1', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'notify', 'test2', NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify',
})
notify_calls = async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "test2", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
services = notify_auth_module.aync_get_available_notify_services()
assert services == ['test1', 'test2']
assert services == ["test1", "test2"]
flow = await notify_auth_module.async_setup_flow('test-user')
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'init'
schema = step['data_schema']
schema({'notify_service': 'test2'})
assert step["type"] == data_entry_flow.RESULT_TYPE_FORM
assert step["step_id"] == "init"
schema = step["data_schema"]
schema({"notify_service": "test2"})
with patch('pyotp.HOTP.at', return_value=MOCK_CODE):
step = await flow.async_step_init({'notify_service': 'test1'})
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'setup'
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
step = await flow.async_step_init({"notify_service": "test1"})
assert step["type"] == data_entry_flow.RESULT_TYPE_FORM
assert step["step_id"] == "setup"
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 1
notify_call = notify_calls[0]
assert notify_call.domain == 'notify'
assert notify_call.service == 'test1'
message = notify_call.data['message']
assert notify_call.domain == "notify"
assert notify_call.service == "test1"
message = notify_call.data["message"]
message.hass = hass
assert MOCK_CODE in message.async_render()
with patch('pyotp.HOTP.at', return_value=MOCK_CODE_2):
step = await flow.async_step_setup({'code': 'invalid'})
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'setup'
assert step['errors']['base'] == 'invalid_code'
with patch("pyotp.HOTP.at", return_value=MOCK_CODE_2):
step = await flow.async_step_setup({"code": "invalid"})
assert step["type"] == data_entry_flow.RESULT_TYPE_FORM
assert step["step_id"] == "setup"
assert step["errors"]["base"] == "invalid_code"
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 2
notify_call = notify_calls[1]
assert notify_call.domain == 'notify'
assert notify_call.service == 'test1'
message = notify_call.data['message']
assert notify_call.domain == "notify"
assert notify_call.service == "test1"
message = notify_call.data["message"]
message.hass = hass
assert MOCK_CODE_2 in message.async_render()
with patch('pyotp.HOTP.verify', return_value=True):
step = await flow.async_step_setup({'code': MOCK_CODE_2})
assert step['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
with patch("pyotp.HOTP.verify", return_value=True):
step = await flow.async_step_setup({"code": MOCK_CODE_2})
assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
async def test_include_exclude_config(hass):
"""Test allow include exclude config."""
async_mock_service(hass, 'notify', 'include1', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'notify', 'include2', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'notify', 'exclude1', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'notify', 'exclude2', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'other', 'include3', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, 'other', 'exclude3', NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "include1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "include2", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "exclude1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "exclude2", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "other", "include3", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "other", "exclude3", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify',
'exclude': ['exclude1', 'exclude2', 'exclude3'],
})
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "exclude": ["exclude1", "exclude2", "exclude3"]}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ['include1', 'include2']
assert services == ["include1", "include2"]
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify',
'include': ['include1', 'include2', 'include3'],
})
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "include": ["include1", "include2", "include3"]}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ['include1', 'include2']
assert services == ["include1", "include2"]
# exclude has high priority than include
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify',
'include': ['include1', 'include2', 'include3'],
'exclude': ['exclude1', 'exclude2', 'include2'],
})
notify_auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "notify",
"include": ["include1", "include2", "include3"],
"exclude": ["exclude1", "exclude2", "include2"],
},
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ['include1']
assert services == ["include1"]
async def test_setup_user_no_notify_service(hass):
"""Test setup flow abort if there is no avilable notify service."""
async_mock_service(hass, 'notify', 'test1', NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify',
'exclude': 'test1',
})
async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "exclude": "test1"}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == []
flow = await notify_auth_module.async_setup_flow('test-user')
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step['type'] == data_entry_flow.RESULT_TYPE_ABORT
assert step['reason'] == 'no_available_service'
assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert step["reason"] == "no_available_service"
async def test_not_raise_exception_when_service_not_exist(hass):
"""Test login flow will not raise exception when notify service error."""
hass.auth = await auth_manager_from_config(hass, [{
'type': 'insecure_example',
'users': [{'username': 'test-user', 'password': 'test-pass'}],
}], [{
'type': 'notify',
}])
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "notify"}],
)
user = MockUser(
id='mock-user',
is_owner=False,
is_active=False,
name='Paulus',
id="mock-user", is_owner=False, is_active=False, name="Paulus"
).add_to_auth_manager(hass.auth)
await hass.auth.async_link_user(user, auth_models.Credentials(
id='mock-id',
auth_provider_type='insecure_example',
auth_provider_id=None,
data={'username': 'test-user'},
is_new=False,
))
await hass.auth.async_link_user(
user,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
await hass.auth.async_enable_user_mfa(user, 'notify', {
'notify_service': 'invalid-notify',
})
await hass.auth.async_enable_user_mfa(
user, "notify", {"notify_service": "invalid-notify"}
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
with patch('pyotp.HOTP.at', return_value=MOCK_CODE):
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result['flow_id'],
{
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_ABORT
assert result['reason'] == 'unknown_error'
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "unknown_error"
# wait service call finished
await hass.async_block_till_done()
@@ -408,13 +391,10 @@ async def test_race_condition_in_data_loading(hass):
counter += 1
await asyncio.sleep(0)
notify_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'notify'
})
with patch('homeassistant.helpers.storage.Store.async_load',
new=mock_load):
task1 = notify_auth_module.async_validate('user', {'code': 'value'})
task2 = notify_auth_module.async_validate('user', {'code': 'value'})
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = notify_auth_module.async_validate("user", {"code": "value"})
task2 = notify_auth_module.async_validate("user", {"code": "value"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
+80 -85
View File
@@ -7,128 +7,126 @@ from homeassistant.auth import models as auth_models, auth_manager_from_config
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from tests.common import MockUser
MOCK_CODE = '123456'
MOCK_CODE = "123456"
async def test_validating_mfa(hass):
"""Test validating mfa code."""
totp_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'totp'
})
await totp_auth_module.async_setup_user('test-user', {})
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
with patch('pyotp.TOTP.verify', return_value=True):
assert await totp_auth_module.async_validate(
'test-user', {'code': MOCK_CODE})
with patch("pyotp.TOTP.verify", return_value=True):
assert await totp_auth_module.async_validate("test-user", {"code": MOCK_CODE})
async def test_validating_mfa_invalid_code(hass):
"""Test validating an invalid mfa code."""
totp_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'totp'
})
await totp_auth_module.async_setup_user('test-user', {})
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
with patch('pyotp.TOTP.verify', return_value=False):
assert await totp_auth_module.async_validate(
'test-user', {'code': MOCK_CODE}) is False
with patch("pyotp.TOTP.verify", return_value=False):
assert (
await totp_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_invalid_user(hass):
"""Test validating an mfa code with invalid user."""
totp_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'totp'
})
await totp_auth_module.async_setup_user('test-user', {})
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
assert await totp_auth_module.async_validate(
'invalid-user', {'code': MOCK_CODE}) is False
assert (
await totp_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_setup_depose_user(hass):
"""Test despose user."""
totp_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'totp'
})
result = await totp_auth_module.async_setup_user('test-user', {})
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
result = await totp_auth_module.async_setup_user("test-user", {})
assert len(totp_auth_module._users) == 1
result2 = await totp_auth_module.async_setup_user('test-user', {})
result2 = await totp_auth_module.async_setup_user("test-user", {})
assert len(totp_auth_module._users) == 1
assert result != result2
await totp_auth_module.async_depose_user('test-user')
await totp_auth_module.async_depose_user("test-user")
assert len(totp_auth_module._users) == 0
result = await totp_auth_module.async_setup_user(
'test-user2', {'secret': 'secret-code'})
assert result == 'secret-code'
"test-user2", {"secret": "secret-code"}
)
assert result == "secret-code"
assert len(totp_auth_module._users) == 1
async def test_login_flow_validates_mfa(hass):
"""Test login flow with mfa enabled."""
hass.auth = await auth_manager_from_config(hass, [{
'type': 'insecure_example',
'users': [{'username': 'test-user', 'password': 'test-pass'}],
}], [{
'type': 'totp',
}])
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "totp"}],
)
user = MockUser(
id='mock-user',
is_owner=False,
is_active=False,
name='Paulus',
id="mock-user", is_owner=False, is_active=False, name="Paulus"
).add_to_auth_manager(hass.auth)
await hass.auth.async_link_user(user, auth_models.Credentials(
id='mock-id',
auth_provider_type='insecure_example',
auth_provider_id=None,
data={'username': 'test-user'},
is_new=False,
))
await hass.auth.async_link_user(
user,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
await hass.auth.async_enable_user_mfa(user, 'totp', {})
await hass.auth.async_enable_user_mfa(user, "totp", {})
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_configure(result['flow_id'], {
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.auth.login_flow.async_configure(result['flow_id'], {
'username': 'test-user',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.auth.login_flow.async_configure(result['flow_id'], {
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['data_schema'].schema.get('code') == str
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") == str
with patch('pyotp.TOTP.verify', return_value=False):
with patch("pyotp.TOTP.verify", return_value=False):
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['errors']['base'] == 'invalid_code'
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
with patch('pyotp.TOTP.verify', return_value=True):
with patch("pyotp.TOTP.verify", return_value=True):
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'code': MOCK_CODE})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data'].id == 'mock-user'
result["flow_id"], {"code": MOCK_CODE}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"].id == "mock-user"
async def test_race_condition_in_data_loading(hass):
@@ -141,13 +139,10 @@ async def test_race_condition_in_data_loading(hass):
counter += 1
await asyncio.sleep(0)
totp_auth_module = await auth_mfa_module_from_config(hass, {
'type': 'totp'
})
with patch('homeassistant.helpers.storage.Store.async_load',
new=mock_load):
task1 = totp_auth_module.async_validate('user', {'code': 'value'})
task2 = totp_auth_module.async_validate('user', {'code': 'value'})
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = totp_auth_module.async_validate("user", {"code": "value"})
task2 = totp_auth_module.async_validate("user", {"code": "value"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
+89 -144
View File
@@ -3,7 +3,9 @@ import pytest
import voluptuous as vol
from homeassistant.auth.permissions.entities import (
compile_entities, ENTITY_POLICY_SCHEMA)
compile_entities,
ENTITY_POLICY_SCHEMA,
)
from homeassistant.auth.permissions.models import PermissionLookup
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.device_registry import DeviceEntry
@@ -15,7 +17,7 @@ def test_entities_none():
"""Test entity ID policy."""
policy = None
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is False
assert compiled("light.kitchen", "read") is False
def test_entities_empty():
@@ -23,7 +25,7 @@ def test_entities_empty():
policy = {}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is False
assert compiled("light.kitchen", "read") is False
def test_entities_false():
@@ -38,235 +40,178 @@ def test_entities_true():
policy = True
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is True
assert compiled("light.kitchen", "read") is True
def test_entities_domains_true():
"""Test entity ID policy."""
policy = {
'domains': True
}
policy = {"domains": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is True
assert compiled("light.kitchen", "read") is True
def test_entities_domains_domain_true():
"""Test entity ID policy."""
policy = {
'domains': {
'light': True
}
}
policy = {"domains": {"light": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test entity ID policy."""
policy = {
'domains': {
'light': False
}
}
policy = {"domains": {"light": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_true():
"""Test entity ID policy."""
policy = {
'entity_ids': True
}
policy = {"entity_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is True
assert compiled("light.kitchen", "read") is True
def test_entities_entity_ids_false():
"""Test entity ID policy."""
policy = {
'entity_ids': False
}
policy = {"entity_ids": False}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_entity_id_true():
"""Test entity ID policy."""
policy = {
'entity_ids': {
'light.kitchen': True
}
}
policy = {"entity_ids": {"light.kitchen": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test entity ID policy."""
policy = {
'entity_ids': {
'light.kitchen': False
}
}
policy = {"entity_ids": {"light.kitchen": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_control_only():
"""Test policy granting control only."""
policy = {
'entity_ids': {
'light.kitchen': {
'read': True,
}
}
}
policy = {"entity_ids": {"light.kitchen": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test policy granting control only."""
policy = {
'domains': {
'light': {
'read': True,
'control': True,
}
}
}
policy = {"domains": {"light": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test policy allowing all entities."""
policy = {
'all': True
}
policy = {"all": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test policy applying read to all entities."""
policy = {
'all': {
'read': True
}
}
policy = {"all": {"read": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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():
"""Test entity ID policy applying control to all."""
policy = {
'all': {
'control': True
}
}
policy = {"all": {"control": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
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
def test_entities_device_id_boolean(hass):
"""Test entity ID policy applying control on device id."""
entity_registry = mock_registry(hass, {
'test_domain.allowed': RegistryEntry(
entity_id='test_domain.allowed',
unique_id='1234',
platform='test_platform',
device_id='mock-allowed-dev-id'
),
'test_domain.not_allowed': RegistryEntry(
entity_id='test_domain.not_allowed',
unique_id='5678',
platform='test_platform',
device_id='mock-not-allowed-dev-id'
),
})
entity_registry = mock_registry(
hass,
{
"test_domain.allowed": RegistryEntry(
entity_id="test_domain.allowed",
unique_id="1234",
platform="test_platform",
device_id="mock-allowed-dev-id",
),
"test_domain.not_allowed": RegistryEntry(
entity_id="test_domain.not_allowed",
unique_id="5678",
platform="test_platform",
device_id="mock-not-allowed-dev-id",
),
},
)
device_registry = mock_device_registry(hass)
policy = {
'device_ids': {
'mock-allowed-dev-id': {
'read': True,
}
}
}
policy = {"device_ids": {"mock-allowed-dev-id": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, PermissionLookup(
entity_registry, device_registry
))
assert compiled('test_domain.allowed', 'read') is True
assert compiled('test_domain.allowed', 'control') is False
assert compiled('test_domain.not_allowed', 'read') is False
assert compiled('test_domain.not_allowed', 'control') is False
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("test_domain.allowed", "read") is True
assert compiled("test_domain.allowed", "control") is False
assert compiled("test_domain.not_allowed", "read") is False
assert compiled("test_domain.not_allowed", "control") is False
def test_entities_areas_true():
"""Test entity ID policy for areas."""
policy = {
'area_ids': True
}
policy = {"area_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled('light.kitchen', 'read') is True
assert compiled("light.kitchen", "read") is True
def test_entities_areas_area_true(hass):
"""Test entity ID policy for areas with specific area."""
entity_registry = mock_registry(hass, {
'light.kitchen': RegistryEntry(
entity_id='light.kitchen',
unique_id='1234',
platform='test_platform',
device_id='mock-dev-id'
),
})
device_registry = mock_device_registry(hass, {
'mock-dev-id': DeviceEntry(
id='mock-dev-id',
area_id='mock-area-id'
)
})
entity_registry = mock_registry(
hass,
{
"light.kitchen": RegistryEntry(
entity_id="light.kitchen",
unique_id="1234",
platform="test_platform",
device_id="mock-dev-id",
)
},
)
device_registry = mock_device_registry(
hass, {"mock-dev-id": DeviceEntry(id="mock-dev-id", area_id="mock-area-id")}
)
policy = {
'area_ids': {
'mock-area-id': {
'read': True,
'control': True,
}
}
}
policy = {"area_ids": {"mock-area-id": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, PermissionLookup(
entity_registry, device_registry
))
assert compiled('light.kitchen', 'read') is True
assert compiled('light.kitchen', 'control') is True
assert compiled('light.kitchen', 'edit') is False
assert compiled('switch.kitchen', 'read') is False
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("light.kitchen", "edit") is False
assert compiled("switch.kitchen", "read") is False
+8 -26
View File
@@ -5,39 +5,21 @@ from homeassistant.auth.permissions.merge import merge_policies
def test_merging_permissions_true_rules_dict():
"""Test merging policy with two entities."""
policy1 = {
'something_else': True,
'entities': {
'entity_ids': {
'light.kitchen': True,
}
}
}
policy2 = {
'entities': {
'entity_ids': True
}
"something_else": True,
"entities": {"entity_ids": {"light.kitchen": True}},
}
policy2 = {"entities": {"entity_ids": True}}
assert merge_policies([policy1, policy2]) == {
'something_else': True,
'entities': {
'entity_ids': True
}
"something_else": True,
"entities": {"entity_ids": True},
}
def test_merging_permissions_multiple_subcategories():
"""Test merging policy with two entities."""
policy1 = {
'entities': None
}
policy2 = {
'entities': {
'entity_ids': True,
}
}
policy3 = {
'entities': True
}
policy1 = {"entities": None}
policy2 = {"entities": {"entity_ids": True}}
policy3 = {"entities": True}
assert merge_policies([policy1, policy2]) == policy2
assert merge_policies([policy1, policy3]) == policy3
+13 -10
View File
@@ -1,6 +1,9 @@
"""Test system policies."""
from homeassistant.auth.permissions import (
PolicyPermissions, system_policies, POLICY_SCHEMA)
PolicyPermissions,
system_policies,
POLICY_SCHEMA,
)
def test_admin_policy():
@@ -9,9 +12,9 @@ def test_admin_policy():
POLICY_SCHEMA(system_policies.ADMIN_POLICY)
perms = PolicyPermissions(system_policies.ADMIN_POLICY, None)
assert perms.check_entity('light.kitchen', 'read')
assert perms.check_entity('light.kitchen', 'control')
assert perms.check_entity('light.kitchen', 'edit')
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit")
def test_user_policy():
@@ -20,9 +23,9 @@ def test_user_policy():
POLICY_SCHEMA(system_policies.USER_POLICY)
perms = PolicyPermissions(system_policies.USER_POLICY, None)
assert perms.check_entity('light.kitchen', 'read')
assert perms.check_entity('light.kitchen', 'control')
assert perms.check_entity('light.kitchen', 'edit')
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit")
def test_read_only_policy():
@@ -31,6 +34,6 @@ def test_read_only_policy():
POLICY_SCHEMA(system_policies.READ_ONLY_POLICY)
perms = PolicyPermissions(system_policies.READ_ONLY_POLICY, None)
assert perms.check_entity('light.kitchen', 'read')
assert not perms.check_entity('light.kitchen', 'control')
assert not perms.check_entity('light.kitchen', 'edit')
assert perms.check_entity("light.kitchen", "read")
assert not perms.check_entity("light.kitchen", "control")
assert not perms.check_entity("light.kitchen", "edit")
+4 -13
View File
@@ -5,17 +5,8 @@ from homeassistant.auth.permissions import util
def test_test_all():
"""Test if we can test the all group."""
for val in (
None,
{},
{'all': None},
{'all': {}},
):
assert util.test_all(val, 'read') is False
for val in (None, {}, {"all": None}, {"all": {}}):
assert util.test_all(val, "read") is False
for val in (
True,
{'all': True},
{'all': {'read': True}},
):
assert util.test_all(val, 'read') is True
for val in (True, {"all": True}, {"all": {"read": True}}):
assert util.test_all(val, "read") is True
+36 -43
View File
@@ -23,30 +23,31 @@ def store(hass):
@pytest.fixture
def provider(hass, store):
"""Mock provider."""
return command_line.CommandLineAuthProvider(hass, store, {
CONF_TYPE: "command_line",
command_line.CONF_COMMAND: os.path.join(
os.path.dirname(__file__), "test_command_line_cmd.sh"
),
command_line.CONF_ARGS: [],
command_line.CONF_META: False,
})
return command_line.CommandLineAuthProvider(
hass,
store,
{
CONF_TYPE: "command_line",
command_line.CONF_COMMAND: os.path.join(
os.path.dirname(__file__), "test_command_line_cmd.sh"
),
command_line.CONF_ARGS: [],
command_line.CONF_META: False,
},
)
@pytest.fixture
def manager(hass, store, provider):
"""Mock manager."""
return AuthManager(hass, store, {
(provider.type, provider.id): provider
}, {})
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(manager, provider):
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials({
"username": "good-user",
"password": "good-pass",
})
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "good-pass"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
@@ -59,16 +60,13 @@ async def test_match_existing_credentials(store, provider):
id=uuid.uuid4(),
auth_provider_type="command_line",
auth_provider_id=None,
data={
"username": "good-user"
},
data={"username": "good-user"},
is_new=False,
)
provider.async_credentials = Mock(return_value=mock_coro([existing]))
credentials = await provider.async_get_or_create_credentials({
"username": "good-user",
"password": "irrelevant",
})
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "irrelevant"}
)
assert credentials is existing
@@ -96,10 +94,9 @@ async def test_good_auth_with_meta(manager, provider):
await provider.async_validate_login("good-user", "good-pass")
credentials = await provider.async_get_or_create_credentials({
"username": "good-user",
"password": "good-pass",
})
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "good-pass"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
@@ -109,10 +106,9 @@ async def test_good_auth_with_meta(manager, provider):
async def test_utf_8_username_password(provider):
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials({
"username": "ßßß",
"password": "äöü",
})
credentials = await provider.async_get_or_create_credentials(
{"username": "ßßß", "password": "äöü"}
)
assert credentials.is_new is True
@@ -122,17 +118,15 @@ async def test_login_flow_validates(provider):
result = await flow.async_step_init()
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await flow.async_step_init({
"username": "bad-user",
"password": "bad-pass",
})
result = await flow.async_step_init(
{"username": "bad-user", "password": "bad-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']["base"] == "invalid_auth"
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init({
"username": "good-user",
"password": "good-pass",
})
result = await flow.async_step_init(
{"username": "good-user", "password": "good-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"]["username"] == "good-user"
@@ -140,9 +134,8 @@ async def test_login_flow_validates(provider):
async def test_strip_username(provider):
"""Test authentication works with username with whitespace around."""
flow = await provider.async_login_flow({})
result = await flow.async_step_init({
"username": "\t\ngood-user ",
"password": "good-pass",
})
result = await flow.async_step_init(
{"username": "\t\ngood-user ", "password": "good-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"]["username"] == "good-user"
+117 -127
View File
@@ -8,7 +8,9 @@ import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, auth_store
from homeassistant.auth.providers import (
auth_provider_from_config, homeassistant as hass_auth)
auth_provider_from_config,
homeassistant as hass_auth,
)
from tests.common import mock_coro
@@ -33,261 +35,249 @@ def legacy_data(hass):
async def test_validating_password_invalid_user(data, hass):
"""Test validating an invalid user."""
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('non-existing', 'pw')
data.validate_login("non-existing", "pw")
async def test_not_allow_set_id():
"""Test we are not allowed to set an ID in config."""
hass = Mock()
with pytest.raises(vol.Invalid):
await auth_provider_from_config(hass, None, {
'type': 'homeassistant',
'id': 'invalid',
})
await auth_provider_from_config(
hass, None, {"type": "homeassistant", "id": "invalid"}
)
async def test_new_users_populate_values(hass, data):
"""Test that we populate data for new users."""
data.add_auth('hello', 'test-pass')
data.add_auth("hello", "test-pass")
await data.async_save()
manager = await auth_manager_from_config(hass, [{
'type': 'homeassistant'
}], [])
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
credentials = await provider.async_get_or_create_credentials({
'username': 'hello'
})
credentials = await provider.async_get_or_create_credentials({"username": "hello"})
user = await manager.async_get_or_create_user(credentials)
assert user.name == 'hello'
assert user.name == "hello"
assert user.is_active
async def test_changing_password_raises_invalid_user(data, hass):
"""Test that changing password raises invalid user."""
with pytest.raises(hass_auth.InvalidUser):
data.change_password('non-existing', 'pw')
data.change_password("non-existing", "pw")
# Modern mode
async def test_adding_user(data, hass):
"""Test adding a user."""
data.add_auth('test-user', 'test-pass')
data.validate_login(' test-user ', 'test-pass')
data.add_auth("test-user", "test-pass")
data.validate_login(" test-user ", "test-pass")
async def test_adding_user_duplicate_username(data, hass):
"""Test adding a user with duplicate username."""
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidUser):
data.add_auth('TEST-user ', 'other-pass')
data.add_auth("TEST-user ", "other-pass")
async def test_validating_password_invalid_password(data, hass):
"""Test validating an invalid password."""
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login(' test-user ', 'invalid-pass')
data.validate_login(" test-user ", "invalid-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('test-user', 'test-pass ')
data.validate_login("test-user", "test-pass ")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('test-user', 'Test-pass')
data.validate_login("test-user", "Test-pass")
async def test_changing_password(data, hass):
"""Test adding a user."""
data.add_auth('test-user', 'test-pass')
data.change_password('TEST-USER ', 'new-pass')
data.add_auth("test-user", "test-pass")
data.change_password("TEST-USER ", "new-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('test-user', 'test-pass')
data.validate_login("test-user", "test-pass")
data.validate_login('test-UsEr', 'new-pass')
data.validate_login("test-UsEr", "new-pass")
async def test_login_flow_validates(data, hass):
"""Test login flow."""
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
await data.async_save()
provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass),
{'type': 'homeassistant'})
provider = hass_auth.HassAuthProvider(
hass, auth_store.AuthStore(hass), {"type": "homeassistant"}
)
flow = await provider.async_login_flow({})
result = await flow.async_step_init()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await flow.async_step_init({
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init({
'username': 'TEST-user ',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await flow.async_step_init(
{"username": "TEST-user ", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init({
'username': 'test-USER',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data']['username'] == 'test-USER'
result = await flow.async_step_init(
{"username": "test-USER", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"]["username"] == "test-USER"
async def test_saving_loading(data, hass):
"""Test saving and loading JSON."""
data.add_auth('test-user', 'test-pass')
data.add_auth('second-user', 'second-pass')
data.add_auth("test-user", "test-pass")
data.add_auth("second-user", "second-pass")
await data.async_save()
data = hass_auth.Data(hass)
await data.async_load()
data.validate_login('test-user ', 'test-pass')
data.validate_login('second-user ', 'second-pass')
data.validate_login("test-user ", "test-pass")
data.validate_login("second-user ", "second-pass")
async def test_get_or_create_credentials(hass, data):
"""Test that we can get or create credentials."""
manager = await auth_manager_from_config(hass, [{
'type': 'homeassistant'
}], [])
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
provider.data = data
credentials1 = await provider.async_get_or_create_credentials({
'username': 'hello'
})
with patch.object(provider, 'async_credentials',
return_value=mock_coro([credentials1])):
credentials2 = await provider.async_get_or_create_credentials({
'username': 'hello '
})
credentials1 = await provider.async_get_or_create_credentials({"username": "hello"})
with patch.object(
provider, "async_credentials", return_value=mock_coro([credentials1])
):
credentials2 = await provider.async_get_or_create_credentials(
{"username": "hello "}
)
assert credentials1 is credentials2
# Legacy mode
async def test_legacy_adding_user(legacy_data, hass):
"""Test in legacy mode adding a user."""
legacy_data.add_auth('test-user', 'test-pass')
legacy_data.validate_login('test-user', 'test-pass')
legacy_data.add_auth("test-user", "test-pass")
legacy_data.validate_login("test-user", "test-pass")
async def test_legacy_adding_user_duplicate_username(legacy_data, hass):
"""Test in legacy mode adding a user with duplicate username."""
legacy_data.add_auth('test-user', 'test-pass')
legacy_data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidUser):
legacy_data.add_auth('test-user', 'other-pass')
legacy_data.add_auth("test-user", "other-pass")
# Not considered duplicate
legacy_data.add_auth('test-user ', 'test-pass')
legacy_data.add_auth('Test-user', 'test-pass')
legacy_data.add_auth("test-user ", "test-pass")
legacy_data.add_auth("Test-user", "test-pass")
async def test_legacy_validating_password_invalid_password(legacy_data, hass):
"""Test in legacy mode validating an invalid password."""
legacy_data.add_auth('test-user', 'test-pass')
legacy_data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login('test-user', 'invalid-pass')
legacy_data.validate_login("test-user", "invalid-pass")
async def test_legacy_changing_password(legacy_data, hass):
"""Test in legacy mode adding a user."""
user = 'test-user'
legacy_data.add_auth(user, 'test-pass')
legacy_data.change_password(user, 'new-pass')
user = "test-user"
legacy_data.add_auth(user, "test-pass")
legacy_data.change_password(user, "new-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login(user, 'test-pass')
legacy_data.validate_login(user, "test-pass")
legacy_data.validate_login(user, 'new-pass')
legacy_data.validate_login(user, "new-pass")
async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass):
"""Test in legacy mode that we initialize an empty config."""
with pytest.raises(hass_auth.InvalidUser):
legacy_data.change_password('non-existing', 'pw')
legacy_data.change_password("non-existing", "pw")
async def test_legacy_login_flow_validates(legacy_data, hass):
"""Test in legacy mode login flow."""
legacy_data.add_auth('test-user', 'test-pass')
legacy_data.add_auth("test-user", "test-pass")
await legacy_data.async_save()
provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass),
{'type': 'homeassistant'})
provider = hass_auth.HassAuthProvider(
hass, auth_store.AuthStore(hass), {"type": "homeassistant"}
)
flow = await provider.async_login_flow({})
result = await flow.async_step_init()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await flow.async_step_init({
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init({
'username': 'test-user',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await flow.async_step_init(
{"username": "test-user", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init({
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data']['username'] == 'test-user'
result = await flow.async_step_init(
{"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"]["username"] == "test-user"
async def test_legacy_saving_loading(legacy_data, hass):
"""Test in legacy mode saving and loading JSON."""
legacy_data.add_auth('test-user', 'test-pass')
legacy_data.add_auth('second-user', 'second-pass')
legacy_data.add_auth("test-user", "test-pass")
legacy_data.add_auth("second-user", "second-pass")
await legacy_data.async_save()
legacy_data = hass_auth.Data(hass)
await legacy_data.async_load()
legacy_data.is_legacy = True
legacy_data.validate_login('test-user', 'test-pass')
legacy_data.validate_login('second-user', 'second-pass')
legacy_data.validate_login("test-user", "test-pass")
legacy_data.validate_login("second-user", "second-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login('test-user ', 'test-pass')
legacy_data.validate_login("test-user ", "test-pass")
async def test_legacy_get_or_create_credentials(hass, legacy_data):
"""Test in legacy mode that we can get or create credentials."""
manager = await auth_manager_from_config(hass, [{
'type': 'homeassistant'
}], [])
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
provider.data = legacy_data
credentials1 = await provider.async_get_or_create_credentials({
'username': 'hello'
})
credentials1 = await provider.async_get_or_create_credentials({"username": "hello"})
with patch.object(provider, 'async_credentials',
return_value=mock_coro([credentials1])):
credentials2 = await provider.async_get_or_create_credentials({
'username': 'hello'
})
with patch.object(
provider, "async_credentials", return_value=mock_coro([credentials1])
):
credentials2 = await provider.async_get_or_create_credentials(
{"username": "hello"}
)
assert credentials1 is credentials2
with patch.object(provider, 'async_credentials',
return_value=mock_coro([credentials1])):
credentials3 = await provider.async_get_or_create_credentials({
'username': 'hello '
})
with patch.object(
provider, "async_credentials", return_value=mock_coro([credentials1])
):
credentials3 = await provider.async_get_or_create_credentials(
{"username": "hello "}
)
assert credentials1 is not credentials3
@@ -304,12 +294,12 @@ async def test_race_condition_in_data_loading(hass):
counter += 1
await asyncio.sleep(0)
provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass),
{'type': 'homeassistant'})
with patch('homeassistant.helpers.storage.Store.async_load',
new=mock_load):
task1 = provider.async_validate_login('user', 'pass')
task2 = provider.async_validate_login('user', 'pass')
provider = hass_auth.HassAuthProvider(
hass, auth_store.AuthStore(hass), {"type": "homeassistant"}
)
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = provider.async_validate_login("user", "pass")
task2 = provider.async_validate_login("user", "pass")
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert isinstance(results[0], hass_auth.InvalidAuth)
+30 -38
View File
@@ -19,40 +19,38 @@ def store(hass):
@pytest.fixture
def provider(hass, store):
"""Mock provider."""
return insecure_example.ExampleAuthProvider(hass, store, {
'type': 'insecure_example',
'users': [
{
'name': 'Test Name',
'username': 'user-test',
'password': 'password-test',
},
{
'username': '🎉',
'password': '😎',
}
]
})
return insecure_example.ExampleAuthProvider(
hass,
store,
{
"type": "insecure_example",
"users": [
{
"name": "Test Name",
"username": "user-test",
"password": "password-test",
},
{"username": "🎉", "password": "😎"},
],
},
)
@pytest.fixture
def manager(hass, store, provider):
"""Mock manager."""
return AuthManager(hass, store, {
(provider.type, provider.id): provider
}, {})
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(manager, provider):
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials({
'username': 'user-test',
'password': 'password-test',
})
credentials = await provider.async_get_or_create_credentials(
{"username": "user-test", "password": "password-test"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
assert user.name == 'Test Name'
assert user.name == "Test Name"
assert user.is_active
@@ -60,39 +58,33 @@ async def test_match_existing_credentials(store, provider):
"""See if we match existing users."""
existing = auth_models.Credentials(
id=uuid.uuid4(),
auth_provider_type='insecure_example',
auth_provider_type="insecure_example",
auth_provider_id=None,
data={
'username': 'user-test'
},
data={"username": "user-test"},
is_new=False,
)
provider.async_credentials = Mock(return_value=mock_coro([existing]))
credentials = await provider.async_get_or_create_credentials({
'username': 'user-test',
'password': 'password-test',
})
credentials = await provider.async_get_or_create_credentials(
{"username": "user-test", "password": "password-test"}
)
assert credentials is existing
async def test_verify_username(provider):
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login(
'non-existing-user', 'password-test')
await provider.async_validate_login("non-existing-user", "password-test")
async def test_verify_password(provider):
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login(
'user-test', 'incorrect-password')
await provider.async_validate_login("user-test", "incorrect-password")
async def test_utf_8_username_password(provider):
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials({
'username': '🎉',
'password': '😎',
})
credentials = await provider.async_get_or_create_credentials(
{"username": "🎉", "password": "😎"}
)
assert credentials.is_new is True
@@ -15,18 +15,15 @@ def store(hass):
@pytest.fixture
def provider(hass, store):
"""Mock provider."""
return legacy_api_password.LegacyApiPasswordAuthProvider(hass, store, {
'type': 'legacy_api_password',
'api_password': 'test-password',
})
return legacy_api_password.LegacyApiPasswordAuthProvider(
hass, store, {"type": "legacy_api_password", "api_password": "test-password"}
)
@pytest.fixture
def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {
(provider.type, provider.id): provider
}, {})
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(manager, provider):
@@ -50,31 +47,23 @@ async def test_only_one_credentials(manager, provider):
async def test_verify_login(hass, provider):
"""Test login using legacy api password auth provider."""
provider.async_validate_login('test-password')
provider.async_validate_login("test-password")
with pytest.raises(legacy_api_password.InvalidAuthError):
provider.async_validate_login('invalid-password')
provider.async_validate_login("invalid-password")
async def test_login_flow_works(hass, manager):
"""Test wrong config."""
result = await manager.login_flow.async_init(
handler=('legacy_api_password', None)
)
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await manager.login_flow.async_init(handler=("legacy_api_password", None))
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await manager.login_flow.async_configure(
flow_id=result['flow_id'],
user_input={
'password': 'not-hello'
}
flow_id=result["flow_id"], user_input={"password": "not-hello"}
)
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"]["base"] == "invalid_auth"
result = await manager.login_flow.async_configure(
flow_id=result['flow_id'],
user_input={
'password': 'test-password'
}
flow_id=result["flow_id"], user_input={"password": "test-password"}
)
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
+156 -136
View File
@@ -19,15 +19,19 @@ def store(hass):
def provider(hass, store):
"""Mock provider."""
return tn_auth.TrustedNetworksAuthProvider(
hass, store, tn_auth.CONFIG_SCHEMA({
'type': 'trusted_networks',
'trusted_networks': [
'192.168.0.1',
'192.168.128.0/24',
'::1',
'fd00::/8',
],
})
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
}
),
)
@@ -35,21 +39,25 @@ def provider(hass, store):
def provider_with_user(hass, store):
"""Mock provider with trusted users config."""
return tn_auth.TrustedNetworksAuthProvider(
hass, store, tn_auth.CONFIG_SCHEMA({
'type': 'trusted_networks',
'trusted_networks': [
'192.168.0.1',
'192.168.128.0/24',
'::1',
'fd00::/8',
],
# user_id will be injected in test
'trusted_users': {
'192.168.0.1': [],
'192.168.128.0/24': [],
'fd00::/8': [],
},
})
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
# user_id will be injected in test
"trusted_users": {
"192.168.0.1": [],
"192.168.128.0/24": [],
"fd00::/8": [],
},
}
),
)
@@ -57,80 +65,81 @@ def provider_with_user(hass, store):
def provider_bypass_login(hass, store):
"""Mock provider with allow_bypass_login config."""
return tn_auth.TrustedNetworksAuthProvider(
hass, store, tn_auth.CONFIG_SCHEMA({
'type': 'trusted_networks',
'trusted_networks': [
'192.168.0.1',
'192.168.128.0/24',
'::1',
'fd00::/8',
],
'allow_bypass_login': True,
})
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
"allow_bypass_login": True,
}
),
)
@pytest.fixture
def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {
(provider.type, provider.id): provider
}, {})
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
@pytest.fixture
def manager_with_user(hass, store, provider_with_user):
"""Mock manager with trusted user."""
return auth.AuthManager(hass, store, {
(provider_with_user.type, provider_with_user.id): provider_with_user
}, {})
return auth.AuthManager(
hass,
store,
{(provider_with_user.type, provider_with_user.id): provider_with_user},
{},
)
@pytest.fixture
def manager_bypass_login(hass, store, provider_bypass_login):
"""Mock manager with allow bypass login."""
return auth.AuthManager(hass, store, {
(provider_bypass_login.type, provider_bypass_login.id):
provider_bypass_login
}, {})
return auth.AuthManager(
hass,
store,
{(provider_bypass_login.type, provider_bypass_login.id): provider_bypass_login},
{},
)
async def test_trusted_networks_credentials(manager, provider):
"""Test trusted_networks credentials related functions."""
owner = await manager.async_create_user("test-owner")
tn_owner_cred = await provider.async_get_or_create_credentials({
'user': owner.id
})
tn_owner_cred = await provider.async_get_or_create_credentials({"user": owner.id})
assert tn_owner_cred.is_new is False
assert any(cred.id == tn_owner_cred.id for cred in owner.credentials)
user = await manager.async_create_user("test-user")
tn_user_cred = await provider.async_get_or_create_credentials({
'user': user.id
})
tn_user_cred = await provider.async_get_or_create_credentials({"user": user.id})
assert tn_user_cred.id != tn_owner_cred.id
assert tn_user_cred.is_new is False
assert any(cred.id == tn_user_cred.id for cred in user.credentials)
with pytest.raises(tn_auth.InvalidUserError):
await provider.async_get_or_create_credentials({
'user': 'invalid-user'
})
await provider.async_get_or_create_credentials({"user": "invalid-user"})
async def test_validate_access(provider):
"""Test validate access from trusted networks."""
provider.async_validate_access(ip_address('192.168.0.1'))
provider.async_validate_access(ip_address('192.168.128.10'))
provider.async_validate_access(ip_address('::1'))
provider.async_validate_access(ip_address('fd01:db8::ff00:42:8329'))
provider.async_validate_access(ip_address("192.168.0.1"))
provider.async_validate_access(ip_address("192.168.128.10"))
provider.async_validate_access(ip_address("::1"))
provider.async_validate_access(ip_address("fd01:db8::ff00:42:8329"))
with pytest.raises(tn_auth.InvalidAuthError):
provider.async_validate_access(ip_address('192.168.0.2'))
provider.async_validate_access(ip_address("192.168.0.2"))
with pytest.raises(tn_auth.InvalidAuthError):
provider.async_validate_access(ip_address('127.0.0.1'))
provider.async_validate_access(ip_address("127.0.0.1"))
with pytest.raises(tn_auth.InvalidAuthError):
provider.async_validate_access(ip_address('2001:db8::ff00:42:8329'))
provider.async_validate_access(ip_address("2001:db8::ff00:42:8329"))
async def test_login_flow(manager, provider):
@@ -139,103 +148,105 @@ async def test_login_flow(manager, provider):
user = await manager.async_create_user("test-user")
# not from trusted network
flow = await provider.async_login_flow(
{'ip_address': ip_address('127.0.0.1')})
flow = await provider.async_login_flow({"ip_address": ip_address("127.0.0.1")})
step = await flow.async_step_init()
assert step['type'] == 'abort'
assert step['reason'] == 'not_whitelisted'
assert step["type"] == "abort"
assert step["reason"] == "not_whitelisted"
# from trusted network, list users
flow = await provider.async_login_flow(
{'ip_address': ip_address('192.168.0.1')})
flow = await provider.async_login_flow({"ip_address": ip_address("192.168.0.1")})
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
assert schema({'user': owner.id})
schema = step["data_schema"]
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({'user': 'invalid-user'})
assert schema({"user": "invalid-user"})
# login with valid user
step = await flow.async_step_init({'user': user.id})
assert step['type'] == 'create_entry'
assert step['data']['user'] == user.id
step = await flow.async_step_init({"user": user.id})
assert step["type"] == "create_entry"
assert step["data"]["user"] == user.id
async def test_trusted_users_login(manager_with_user, provider_with_user):
"""Test available user list changed per different IP."""
owner = await manager_with_user.async_create_user("test-owner")
sys_user = await manager_with_user.async_create_system_user(
"test-sys-user") # system user will not be available to select
"test-sys-user"
) # system user will not be available to select
user = await manager_with_user.async_create_user("test-user")
# change the trusted users config
config = provider_with_user.config['trusted_users']
assert ip_network('192.168.0.1') in config
config[ip_network('192.168.0.1')] = [owner.id]
assert ip_network('192.168.128.0/24') in config
config[ip_network('192.168.128.0/24')] = [sys_user.id, user.id]
config = provider_with_user.config["trusted_users"]
assert ip_network("192.168.0.1") in config
config[ip_network("192.168.0.1")] = [owner.id]
assert ip_network("192.168.128.0/24") in config
config[ip_network("192.168.128.0/24")] = [sys_user.id, user.id]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('127.0.0.1')})
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step['type'] == 'abort'
assert step['reason'] == 'not_whitelisted'
assert step["type"] == "abort"
assert step["reason"] == "not_whitelisted"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('192.168.0.1')})
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# only owner listed
assert schema({'user': owner.id})
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({'user': user.id})
assert schema({"user": user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('192.168.128.1')})
{"ip_address": ip_address("192.168.128.1")}
)
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# only user listed
assert schema({'user': user.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({'user': owner.id})
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({'user': sys_user.id})
assert schema({"user": sys_user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('::1')})
flow = await provider_with_user.async_login_flow({"ip_address": ip_address("::1")})
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# both owner and user listed
assert schema({'user': owner.id})
assert schema({'user': user.id})
assert schema({"user": owner.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({'user': sys_user.id})
assert schema({"user": sys_user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('fd00::1')})
{"ip_address": ip_address("fd00::1")}
)
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# no user listed
with pytest.raises(vol.Invalid):
assert schema({'user': owner.id})
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({'user': user.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({'user': sys_user.id})
assert schema({"user": sys_user.id})
async def test_trusted_group_login(manager_with_user, provider_with_user):
@@ -244,46 +255,52 @@ async def test_trusted_group_login(manager_with_user, provider_with_user):
# create a user in user group
user = await manager_with_user.async_create_user("test-user")
await manager_with_user.async_update_user(
user, group_ids=[auth.const.GROUP_ID_USER])
user, group_ids=[auth.const.GROUP_ID_USER]
)
# change the trusted users config
config = provider_with_user.config['trusted_users']
assert ip_network('192.168.0.1') in config
config[ip_network('192.168.0.1')] = [{'group': [auth.const.GROUP_ID_USER]}]
assert ip_network('192.168.128.0/24') in config
config[ip_network('192.168.128.0/24')] = [
owner.id, {'group': [auth.const.GROUP_ID_USER]}]
config = provider_with_user.config["trusted_users"]
assert ip_network("192.168.0.1") in config
config[ip_network("192.168.0.1")] = [{"group": [auth.const.GROUP_ID_USER]}]
assert ip_network("192.168.128.0/24") in config
config[ip_network("192.168.128.0/24")] = [
owner.id,
{"group": [auth.const.GROUP_ID_USER]},
]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('127.0.0.1')})
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step['type'] == 'abort'
assert step['reason'] == 'not_whitelisted'
assert step["type"] == "abort"
assert step["reason"] == "not_whitelisted"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('192.168.0.1')})
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# only user listed
print(user.id)
assert schema({'user': user.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({'user': owner.id})
assert schema({"user": owner.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{'ip_address': ip_address('192.168.128.1')})
{"ip_address": ip_address("192.168.128.1")}
)
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step["step_id"] == "init"
schema = step['data_schema']
schema = step["data_schema"]
# both owner and user listed
assert schema({'user': owner.id})
assert schema({'user': user.id})
assert schema({"user": owner.id})
assert schema({"user": user.id})
async def test_bypass_login_flow(manager_bypass_login, provider_bypass_login):
@@ -292,25 +309,28 @@ async def test_bypass_login_flow(manager_bypass_login, provider_bypass_login):
# not from trusted network
flow = await provider_bypass_login.async_login_flow(
{'ip_address': ip_address('127.0.0.1')})
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step['type'] == 'abort'
assert step['reason'] == 'not_whitelisted'
assert step["type"] == "abort"
assert step["reason"] == "not_whitelisted"
# from trusted network, only one available user, bypass the login flow
flow = await provider_bypass_login.async_login_flow(
{'ip_address': ip_address('192.168.0.1')})
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step['type'] == 'create_entry'
assert step['data']['user'] == owner.id
assert step["type"] == "create_entry"
assert step["data"]["user"] == owner.id
user = await manager_bypass_login.async_create_user("test-user")
# from trusted network, two available user, show up login form
flow = await provider_bypass_login.async_login_flow(
{'ip_address': ip_address('192.168.0.1')})
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
schema = step['data_schema']
schema = step["data_schema"]
# both owner and user listed
assert schema({'user': owner.id})
assert schema({'user': user.id})
assert schema({"user": owner.id})
assert schema({"user": user.id})
+35 -52
View File
@@ -9,10 +9,10 @@ from homeassistant.auth import auth_store
async def test_loading_no_group_data_format(hass, hass_storage):
"""Test we correctly load old data without any groups."""
hass_storage[auth_store.STORAGE_KEY] = {
'version': 1,
'data': {
'credentials': [],
'users': [
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
@@ -26,7 +26,7 @@ async def test_loading_no_group_data_format(hass, hass_storage):
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
}
},
],
"refresh_tokens": [
{
@@ -37,7 +37,7 @@ async def test_loading_no_group_data_format(hass, hass_storage):
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id"
"user_id": "user-id",
},
{
"access_token_expiration": 1800.0,
@@ -47,7 +47,7 @@ async def test_loading_no_group_data_format(hass, hass_storage):
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "system-id"
"user_id": "system-id",
},
{
"access_token_expiration": 1800.0,
@@ -56,10 +56,10 @@ async def test_loading_no_group_data_format(hass, hass_storage):
"id": "hidden-because-no-jwt-id",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id"
"user_id": "user-id",
},
]
}
],
},
}
store = auth_store.AuthStore(hass)
@@ -87,29 +87,29 @@ async def test_loading_no_group_data_format(hass, hass_storage):
assert owner.groups == [admin_group]
assert len(owner.refresh_tokens) == 1
owner_token = list(owner.refresh_tokens.values())[0]
assert owner_token.id == 'user-token-id'
assert owner_token.id == "user-token-id"
assert system.system_generated is True
assert system.groups == []
assert len(system.refresh_tokens) == 1
system_token = list(system.refresh_tokens.values())[0]
assert system_token.id == 'system-token-id'
assert system_token.id == "system-token-id"
async def test_loading_all_access_group_data_format(hass, hass_storage):
"""Test we correctly load old data with single group."""
hass_storage[auth_store.STORAGE_KEY] = {
'version': 1,
'data': {
'credentials': [],
'users': [
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
'group_ids': ['abcd-all-access']
"group_ids": ["abcd-all-access"],
},
{
"id": "system-id",
@@ -117,14 +117,9 @@ async def test_loading_all_access_group_data_format(hass, hass_storage):
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
}
],
"groups": [
{
"id": "abcd-all-access",
"name": "All Access",
}
},
],
"groups": [{"id": "abcd-all-access", "name": "All Access"}],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
@@ -134,7 +129,7 @@ async def test_loading_all_access_group_data_format(hass, hass_storage):
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id"
"user_id": "user-id",
},
{
"access_token_expiration": 1800.0,
@@ -144,7 +139,7 @@ async def test_loading_all_access_group_data_format(hass, hass_storage):
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "system-id"
"user_id": "system-id",
},
{
"access_token_expiration": 1800.0,
@@ -153,10 +148,10 @@ async def test_loading_all_access_group_data_format(hass, hass_storage):
"id": "hidden-because-no-jwt-id",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id"
"user_id": "user-id",
},
]
}
],
},
}
store = auth_store.AuthStore(hass)
@@ -184,13 +179,13 @@ async def test_loading_all_access_group_data_format(hass, hass_storage):
assert owner.groups == [admin_group]
assert len(owner.refresh_tokens) == 1
owner_token = list(owner.refresh_tokens.values())[0]
assert owner_token.id == 'user-token-id'
assert owner_token.id == "user-token-id"
assert system.system_generated is True
assert system.groups == []
assert len(system.refresh_tokens) == 1
system_token = list(system.refresh_tokens.values())[0]
assert system_token.id == 'system-token-id'
assert system_token.id == "system-token-id"
async def test_loading_empty_data(hass, hass_storage):
@@ -223,20 +218,11 @@ async def test_system_groups_store_id_and_name(hass, hass_storage):
store = auth_store.AuthStore(hass)
await store._async_load()
data = store._data_to_save()
assert len(data['users']) == 0
assert data['groups'] == [
{
'id': auth_store.GROUP_ID_ADMIN,
'name': auth_store.GROUP_NAME_ADMIN,
},
{
'id': auth_store.GROUP_ID_USER,
'name': auth_store.GROUP_NAME_USER,
},
{
'id': auth_store.GROUP_ID_READ_ONLY,
'name': auth_store.GROUP_NAME_READ_ONLY,
},
assert len(data["users"]) == 0
assert data["groups"] == [
{"id": auth_store.GROUP_ID_ADMIN, "name": auth_store.GROUP_NAME_ADMIN},
{"id": auth_store.GROUP_ID_USER, "name": auth_store.GROUP_NAME_USER},
{"id": auth_store.GROUP_ID_READ_ONLY, "name": auth_store.GROUP_NAME_READ_ONLY},
]
@@ -244,16 +230,13 @@ async def test_loading_race_condition(hass):
"""Test only one storage load called when concurrent loading occurred ."""
store = auth_store.AuthStore(hass)
with asynctest.patch(
'homeassistant.helpers.entity_registry.async_get_registry',
"homeassistant.helpers.entity_registry.async_get_registry"
) as mock_ent_registry, asynctest.patch(
'homeassistant.helpers.device_registry.async_get_registry',
"homeassistant.helpers.device_registry.async_get_registry"
) as mock_dev_registry, asynctest.patch(
'homeassistant.helpers.storage.Store.async_load',
"homeassistant.helpers.storage.Store.async_load"
) as mock_load:
results = await asyncio.gather(
store.async_get_users(),
store.async_get_users(),
)
results = await asyncio.gather(store.async_get_users(), store.async_get_users())
mock_ent_registry.assert_called_once_with(hass)
mock_dev_registry.assert_called_once_with(hass)
+512 -476
View File
File diff suppressed because it is too large. Load diff
+10 -25
View File
@@ -6,38 +6,23 @@ def test_owner_fetching_owner_permissions():
"""Test we fetch the owner permissions for an owner user."""
group = models.Group(name="Test Group", policy={})
owner = models.User(
name="Test User",
perm_lookup=None,
groups=[group],
is_owner=True
name="Test User", perm_lookup=None, groups=[group], is_owner=True
)
assert owner.permissions is permissions.OwnerPermissions
def test_permissions_merged():
"""Test we merge the groups permissions."""
group = models.Group(name="Test Group", policy={
'entities': {
'domains': {
'switch': True
}
}
})
group2 = models.Group(name="Test Group", policy={
'entities': {
'entity_ids': {
'light.kitchen': True
}
}
})
user = models.User(
name="Test User",
perm_lookup=None,
groups=[group, group2]
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
group2 = models.Group(
name="Test Group", policy={"entities": {"entity_ids": {"light.kitchen": True}}}
)
user = models.User(name="Test User", perm_lookup=None, groups=[group, group2])
# Make sure we cache instance
assert user.permissions is user.permissions
assert user.permissions.check_entity('switch.bla', 'read') is True
assert user.permissions.check_entity('light.kitchen', 'read') is True
assert user.permissions.check_entity('light.not_kitchen', 'read') is False
assert user.permissions.check_entity("switch.bla", "read") is True
assert user.permissions.check_entity("light.kitchen", "read") is True
assert user.permissions.check_entity("light.not_kitchen", "read") is False