init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for the Home Assistant auth module."""

View File

@@ -0,0 +1 @@
"""Tests for the multi-factor auth modules."""

View File

@@ -0,0 +1,157 @@
"""Test the example module auth module."""
from homeassistant import auth, data_entry_flow
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.auth.models import Credentials
from homeassistant.core import HomeAssistant
from tests.common import MockUser
async def test_validate(hass: HomeAssistant) -> None:
"""Test validating pin."""
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"})
assert result is True
result = await auth_module.async_validate("test-user", {"pin": "invalid"})
assert result is False
result = await auth_module.async_validate("invalid-user", {"pin": "123456"})
assert result is False
async def test_setup_user(hass: HomeAssistant) -> None:
"""Test setup user."""
auth_module = await auth_mfa_module_from_config(
hass, {"type": "insecure_example", "data": []}
)
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"})
assert result is True
async def test_depose_user(hass: HomeAssistant) -> None:
"""Test despose user."""
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")
assert len(auth_module._data) == 0
async def test_is_user_setup(hass: HomeAssistant) -> None:
"""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
async def test_login(hass: HomeAssistant) -> None:
"""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"}],
}
],
)
user = MockUser(
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,
),
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("pin") is str
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"pin": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_setup_flow(hass: HomeAssistant) -> None:
"""Test validating pin."""
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")
result = await flow.async_step_init()
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await flow.async_step_init({"pin": "abcdefg"})
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert auth_module._data[1]["user_id"] == "new-user"
assert auth_module._data[1]["pin"] == "abcdefg"

View File

@@ -0,0 +1,401 @@
"""Test the HMAC-based One Time Password (MFA) auth module."""
import asyncio
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, models as auth_models
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.components.notify import NOTIFY_SERVICE_SCHEMA
from homeassistant.core import HomeAssistant
from tests.common import MockUser, async_mock_service
MOCK_CODE = "123456"
MOCK_CODE_2 = "654321"
async def test_validating_mfa(hass: HomeAssistant) -> None:
"""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"})
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: HomeAssistant) -> None:
"""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"})
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: HomeAssistant) -> None:
"""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"})
assert (
await notify_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_counter(hass: HomeAssistant) -> None:
"""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")
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")
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})
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
)
notify_setting = list(notify_auth_module._user_settings.values())[0]
assert after_generate_count == notify_setting.counter
async def test_setup_depose_user(hass: HomeAssistant) -> None:
"""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", {})
assert len(notify_auth_module._user_settings) == 1
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")
assert len(notify_auth_module._user_settings) == 0
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: HomeAssistant) -> None:
"""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"}],
)
user = MockUser(
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,
),
)
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"}
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is 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 MOCK_CODE in message
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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
# wait service call finished
await hass.async_block_till_done()
# would not send new code, allow user retry
assert len(notify_calls) == 1
# retry twice
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.FlowResultType.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.FlowResultType.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.FlowResultType.FORM
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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is 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 MOCK_CODE in message
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.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_setup_user_notify_service(hass: HomeAssistant) -> None:
"""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"})
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["test1", "test2"]
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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 MOCK_CODE in message
with patch("pyotp.HOTP.at", return_value=MOCK_CODE_2):
step = await flow.async_step_setup({"code": "invalid"})
assert step["type"] == data_entry_flow.FlowResultType.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 MOCK_CODE_2 in message
with patch("pyotp.HOTP.verify", return_value=True):
step = await flow.async_step_setup({"code": MOCK_CODE_2})
assert step["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
async def test_include_exclude_config(hass: HomeAssistant) -> None:
"""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)
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"]
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"]
# 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"],
},
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["include1"]
async def test_setup_user_no_notify_service(hass: HomeAssistant) -> None:
"""Test setup flow abort if there is no available 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"}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == []
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step["type"] == data_entry_flow.FlowResultType.ABORT
assert step["reason"] == "no_available_service"
async def test_not_raise_exception_when_service_not_exist(hass: HomeAssistant) -> None:
"""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"}],
)
user = MockUser(
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_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.FlowResultType.FORM
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.FlowResultType.ABORT
assert result["reason"] == "unknown_error"
# wait service call finished
await hass.async_block_till_done()
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the data loading."""
counter = 0
async def mock_load(_):
"""Mock homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
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"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
assert results[1] is False

View File

@@ -0,0 +1,152 @@
"""Test the Time-based One Time Password (MFA) auth module."""
import asyncio
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, models as auth_models
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.core import HomeAssistant
from tests.common import MockUser
MOCK_CODE = "123456"
async def test_validating_mfa(hass: HomeAssistant) -> None:
"""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", {})
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: HomeAssistant) -> None:
"""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", {})
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: HomeAssistant) -> None:
"""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", {})
assert (
await totp_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_setup_depose_user(hass: HomeAssistant) -> None:
"""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", {})
assert len(totp_auth_module._users) == 1
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")
assert len(totp_auth_module._users) == 0
result = await totp_auth_module.async_setup_user(
"test-user2", {"secret": "secret-code"}
)
assert result == "secret-code"
assert len(totp_auth_module._users) == 1
async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None:
"""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"}],
)
user = MockUser(
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_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.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is str
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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
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.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the data loading."""
counter = 0
async def mock_load(_):
"""Mock of homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
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"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
assert results[1] is False

View File

@@ -0,0 +1 @@
"""Tests for permissions."""

View File

@@ -0,0 +1,219 @@
"""Tests for entity permissions."""
import pytest
import voluptuous as vol
from homeassistant.auth.permissions.entities import (
ENTITY_POLICY_SCHEMA,
compile_entities,
)
from homeassistant.auth.permissions.models import PermissionLookup
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntry
from homeassistant.helpers.entity_registry import RegistryEntry
from tests.common import mock_device_registry, mock_registry
def test_entities_none() -> None:
"""Test entity ID policy."""
policy = None
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
def test_entities_empty() -> None:
"""Test entity ID policy."""
policy = {}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
def test_entities_false() -> None:
"""Test entity ID policy."""
policy = False
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_true() -> None:
"""Test entity ID policy."""
policy = True
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_domains_true() -> None:
"""Test entity ID policy."""
policy = {"domains": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_domains_domain_true() -> None:
"""Test entity ID policy."""
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
def test_entities_domains_domain_false() -> None:
"""Test entity ID policy."""
policy = {"domains": {"light": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_true() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_entity_ids_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": False}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_entity_id_true() -> None:
"""Test entity ID policy."""
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
def test_entities_entity_ids_entity_id_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": {"light.kitchen": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_control_only() -> None:
"""Test policy granting control only."""
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
def test_entities_read_control() -> None:
"""Test policy granting control only."""
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
def test_entities_all_allow() -> None:
"""Test policy allowing all entities."""
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
def test_entities_all_read() -> None:
"""Test policy applying read to all entities."""
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
def test_entities_all_control() -> None:
"""Test entity ID policy applying control to all."""
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
def test_entities_device_id_boolean(hass: HomeAssistant) -> None:
"""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",
),
},
)
device_registry = mock_device_registry(hass)
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
def test_entities_areas_true() -> None:
"""Test entity ID policy for areas."""
policy = {"area_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_areas_area_true(hass: HomeAssistant) -> None:
"""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")}
)
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

View File

@@ -0,0 +1,27 @@
"""Tests for permissions merging."""
from homeassistant.auth.permissions.merge import merge_policies
def test_merging_permissions_true_rules_dict() -> None:
"""Test merging policy with two entities."""
policy1 = {
"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},
}
def test_merging_permissions_multiple_subcategories() -> None:
"""Test merging policy with two entities."""
policy1 = {"entities": None}
policy2 = {"entities": {"entity_ids": True}}
policy3 = {"entities": True}
assert merge_policies([policy1, policy2]) == policy2
assert merge_policies([policy1, policy3]) == policy3
assert merge_policies([policy2, policy3]) == policy3

View File

@@ -0,0 +1,40 @@
"""Test system policies."""
from homeassistant.auth.permissions import (
POLICY_SCHEMA,
PolicyPermissions,
system_policies,
)
def test_admin_policy() -> None:
"""Test admin policy works."""
# Make sure it's valid
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")
def test_user_policy() -> None:
"""Test user policy works."""
# Make sure it's valid
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")
def test_read_only_policy() -> None:
"""Test read only policy works."""
# Make sure it's valid
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")

View File

@@ -0,0 +1,12 @@
"""Test the permission utils."""
from homeassistant.auth.permissions import util
def test_test_all() -> None:
"""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 (True, {"all": True}, {"all": {"read": True}}):
assert util.test_all(val, "read") is True

View File

@@ -0,0 +1 @@
"""Tests for the auth providers."""

View File

@@ -0,0 +1,164 @@
"""Tests for the command_line auth provider."""
import os
from unittest.mock import AsyncMock
import uuid
import pytest
from homeassistant import data_entry_flow
from homeassistant.auth import AuthManager, auth_store, models as auth_models
from homeassistant.auth.providers import command_line
from homeassistant.const import CONF_TYPE
from homeassistant.core import HomeAssistant
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> command_line.CommandLineAuthProvider:
"""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,
},
)
@pytest.fixture
def manager(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider: command_line.CommandLineAuthProvider,
) -> AuthManager:
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(
manager: AuthManager, provider: command_line.CommandLineAuthProvider
) -> None:
"""Test that we create a new credential."""
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)
assert user.is_active
assert len(user.groups) == 1
assert user.groups[0].id == "system-admin"
assert not user.local_only
async def test_match_existing_credentials(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""See if we match existing users."""
existing = auth_models.Credentials(
id=uuid.uuid4(),
auth_provider_type="command_line",
auth_provider_id=None,
data={"username": "good-user"},
is_new=False,
)
provider.async_credentials = AsyncMock(return_value=[existing])
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "irrelevant"}
)
assert credentials is existing
async def test_invalid_username(provider: command_line.CommandLineAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(command_line.InvalidAuthError):
await provider.async_validate_login("bad-user", "good-pass")
async def test_invalid_password(provider: command_line.CommandLineAuthProvider) -> None:
"""Test we raise if incorrect password specified."""
with pytest.raises(command_line.InvalidAuthError):
await provider.async_validate_login("good-user", "bad-pass")
async def test_good_auth(provider: command_line.CommandLineAuthProvider) -> None:
"""Test nothing is raised with good credentials."""
await provider.async_validate_login("good-user", "good-pass")
async def test_good_auth_with_meta(
manager: AuthManager, provider: command_line.CommandLineAuthProvider
) -> None:
"""Test metadata is added upon successful authentication."""
provider.config[command_line.CONF_ARGS] = ["--with-meta"]
provider.config[command_line.CONF_META] = True
await provider.async_validate_login("good-user", "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)
assert user.name == "Bob"
assert user.is_active
assert len(user.groups) == 1
assert user.groups[0].id == "system-users"
assert user.local_only
async def test_utf_8_username_password(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "ßßß", "password": "äöü"}
)
assert credentials.is_new is True
async def test_login_flow_validates(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""Test login flow."""
flow = await provider.async_login_flow({})
result = await flow.async_step_init()
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "bad-user", "password": "bad-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "good-user", "password": "good-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "good-user"
async def test_strip_username(provider: command_line.CommandLineAuthProvider) -> None:
"""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"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "good-user"

View File

@@ -0,0 +1,14 @@
#!/bin/sh
if [ "$username" = "good-user" ] && [ "$password" = "good-pass" ]; then
echo "Auth should succeed." >&2
if [ "$1" = "--with-meta" ]; then
echo "name=Bob"
echo "group=system-users"
echo "local_only=true"
fi
exit 0
fi
echo "Auth should fail." >&2
exit 1

View File

@@ -0,0 +1,481 @@
"""Test the Home Assistant local auth provider."""
import asyncio
from typing import Any
from unittest.mock import Mock, patch
import pytest
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,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
@pytest.fixture
def data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
return data
@pytest.fixture
def legacy_data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded legacy data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
data.is_legacy = True
return data
@pytest.fixture
async def load_auth_component(hass: HomeAssistant) -> None:
"""Load the auth component for translations."""
await async_setup_component(hass, "auth", {})
async def test_validating_password_invalid_user(data: hass_auth.Data) -> None:
"""Test validating an invalid user."""
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("non-existing", "pw")
async def test_not_allow_set_id() -> None:
"""Test we are not allowed to set an ID in config."""
hass = Mock()
hass.data = {}
with pytest.raises(vol.Invalid):
await auth_provider_from_config(
hass, None, {"type": "homeassistant", "id": "invalid"}
)
async def test_new_users_populate_values(
hass: HomeAssistant, data: hass_auth.Data
) -> None:
"""Test that we populate data for new users."""
data.add_auth("hello", "test-pass")
await data.async_save()
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
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.is_active
async def test_changing_password_raises_invalid_user(data: hass_auth.Data) -> None:
"""Test that changing password raises invalid user."""
with pytest.raises(hass_auth.InvalidUser):
data.change_password("non-existing", "pw")
# Modern mode
async def test_adding_user(data: hass_auth.Data) -> None:
"""Test adding a user."""
data.add_auth("test-user", "test-pass")
data.validate_login(" test-user ", "test-pass")
@pytest.mark.parametrize("username", ["test-user ", "TEST-USER"])
@pytest.mark.usefixtures("load_auth_component")
def test_adding_user_not_normalized(data: hass_auth.Data, username: str) -> None:
"""Test adding a user."""
with pytest.raises(
hass_auth.InvalidUsername, match=f'Username "{username}" is not normalized'
):
data.add_auth(username, "test-pass")
@pytest.mark.usefixtures("load_auth_component")
def test_adding_user_duplicate_username(data: hass_auth.Data) -> None:
"""Test adding a user with duplicate username."""
data.add_auth("test-user", "test-pass")
with pytest.raises(
hass_auth.InvalidUsername, match='Username "test-user" already exists'
):
data.add_auth("test-user", "other-pass")
async def test_validating_password_invalid_password(data: hass_auth.Data) -> None:
"""Test validating an invalid password."""
data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login(" test-user ", "invalid-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("test-user", "test-pass ")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("test-user", "Test-pass")
async def test_changing_password(data: hass_auth.Data) -> None:
"""Test adding a user."""
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", "new-pass")
async def test_login_flow_validates(data: hass_auth.Data, hass: HomeAssistant) -> None:
"""Test login flow."""
data.add_auth("test-user", "test-pass")
await data.async_save()
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.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "test-USER"
async def test_saving_loading(data: hass_auth.Data, hass: HomeAssistant) -> None:
"""Test saving and loading JSON."""
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")
async def test_get_or_create_credentials(
hass: HomeAssistant, data: hass_auth.Data
) -> None:
"""Test that we can get or create credentials."""
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=[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_auth.Data) -> None:
"""Test in legacy mode adding a user."""
legacy_data.add_auth("test-user", "test-pass")
legacy_data.validate_login("test-user", "test-pass")
async def test_legacy_validating_password_invalid_password(
legacy_data: hass_auth.Data,
) -> None:
"""Test in legacy mode validating an invalid password."""
legacy_data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login("test-user", "invalid-pass")
async def test_legacy_changing_password(legacy_data: hass_auth.Data) -> None:
"""Test in legacy mode adding a user."""
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, "new-pass")
async def test_legacy_changing_password_raises_invalid_user(
legacy_data: hass_auth.Data,
) -> None:
"""Test in legacy mode that we initialize an empty config."""
with pytest.raises(hass_auth.InvalidUser):
legacy_data.change_password("non-existing", "pw")
async def test_legacy_login_flow_validates(
legacy_data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test in legacy mode login flow."""
legacy_data.add_auth("test-user", "test-pass")
await legacy_data.async_save()
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.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "test-user"
async def test_legacy_saving_loading(
legacy_data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test in legacy mode saving and loading JSON."""
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")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login("test-user ", "test-pass")
async def test_legacy_get_or_create_credentials(
hass: HomeAssistant, legacy_data: hass_auth.Data
) -> None:
"""Test in legacy mode that we can get or create credentials."""
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"})
with patch.object(provider, "async_credentials", return_value=[credentials1]):
credentials2 = await provider.async_get_or_create_credentials(
{"username": "hello"}
)
assert credentials1 is credentials2
with patch.object(provider, "async_credentials", return_value=[credentials1]):
credentials3 = await provider.async_get_or_create_credentials(
{"username": "hello "}
)
assert credentials1 is not credentials3
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the hass_auth.Data loading.
Ref issue: https://github.com/home-assistant/core/issues/21569
"""
counter = 0
async def mock_load(_):
"""Mock of homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
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")
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert isinstance(results[0], hass_auth.InvalidAuth)
# results[1] will be a TypeError if race condition occurred
assert isinstance(results[1], hass_auth.InvalidAuth)
def test_change_username(data: hass_auth.Data) -> None:
"""Test changing username."""
data.add_auth("test-user", "test-pass")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
data.change_username("test-user", "new-user")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "new-user"
@pytest.mark.parametrize("username", ["test-user ", "TEST-USER"])
def test_change_username_legacy(legacy_data: hass_auth.Data, username: str) -> None:
"""Test changing username."""
# Cannot use add_auth as it normalizes username
legacy_data.users.append(
{
"username": username,
"password": legacy_data.hash_password("test-pass", True).decode(),
}
)
users = legacy_data.users
assert len(users) == 1
assert users[0]["username"] == username
legacy_data.change_username(username, "test-user")
users = legacy_data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
def test_change_username_invalid_user(data: hass_auth.Data) -> None:
"""Test changing username raises on invalid user."""
data.add_auth("test-user", "test-pass")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
with pytest.raises(hass_auth.InvalidUser):
data.change_username("non-existing", "new-user")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
@pytest.mark.usefixtures("load_auth_component")
async def test_change_username_not_normalized(
data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test changing username raises on not normalized username."""
data.add_auth("test-user", "test-pass")
with pytest.raises(
hass_auth.InvalidUsername, match='Username "TEST-user " is not normalized'
):
data.change_username("test-user", "TEST-user ")
@pytest.mark.parametrize(
("usernames_in_storage", "usernames_in_repair"),
[
(["Uppercase"], '- "Uppercase"'),
([" leading"], '- " leading"'),
(["trailing "], '- "trailing "'),
(["Test", "test", "Fritz "], '- "Fritz "\n- "Test"'),
],
)
async def test_create_repair_on_legacy_usernames(
hass: HomeAssistant,
hass_storage: dict[str, Any],
issue_registry: ir.IssueRegistry,
usernames_in_storage: list[str],
usernames_in_repair: str,
) -> None:
"""Test that we create a repair issue for legacy usernames."""
assert not issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
), "Repair issue already exists"
hass_storage[hass_auth.STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "auth_provider.homeassistant",
"data": {
"users": [
{
"username": username,
"password": "onlyherebecauseweneedapasswordstring",
}
for username in usernames_in_storage
]
},
}
data = hass_auth.Data(hass)
await data.async_load()
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue, "Repair issue not created"
assert issue.translation_placeholders == {"usernames": usernames_in_repair}
async def test_delete_repair_after_fixing_usernames(
hass: HomeAssistant,
hass_storage: dict[str, Any],
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that the repair is deleted after fixing the usernames."""
hass_storage[hass_auth.STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "auth_provider.homeassistant",
"data": {
"users": [
{
"username": "Test",
"password": "onlyherebecauseweneedapasswordstring",
},
{
"username": "bla ",
"password": "onlyherebecauseweneedapasswordstring",
},
]
},
}
data = hass_auth.Data(hass)
await data.async_load()
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue, "Repair issue not created"
assert issue.translation_placeholders == {"usernames": '- "Test"\n- "bla "'}
data.change_username("Test", "test")
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue
assert issue.translation_placeholders == {"usernames": '- "bla "'}
data.change_username("bla ", "bla")
assert not issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
), "Repair issue should be deleted"

View File

@@ -0,0 +1,104 @@
"""Tests for the insecure example auth provider."""
from unittest.mock import AsyncMock
import uuid
import pytest
from homeassistant.auth import AuthManager, auth_store, models as auth_models
from homeassistant.auth.providers import insecure_example
from homeassistant.core import HomeAssistant
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> insecure_example.ExampleAuthProvider:
"""Mock provider."""
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: HomeAssistant,
store: auth_store.AuthStore,
provider: insecure_example.ExampleAuthProvider,
) -> AuthManager:
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(
manager: AuthManager, provider: insecure_example.ExampleAuthProvider
) -> None:
"""Test that we create a new credential."""
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.is_active
async def test_match_existing_credentials(
provider: insecure_example.ExampleAuthProvider,
) -> None:
"""See if we match existing users."""
existing = auth_models.Credentials(
id=uuid.uuid4(),
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "user-test"},
is_new=False,
)
provider.async_credentials = AsyncMock(return_value=[existing])
credentials = await provider.async_get_or_create_credentials(
{"username": "user-test", "password": "password-test"}
)
assert credentials is existing
async def test_verify_username(provider: insecure_example.ExampleAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login("non-existing-user", "password-test")
async def test_verify_password(provider: insecure_example.ExampleAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login("user-test", "incorrect-password")
async def test_utf_8_username_password(
provider: insecure_example.ExampleAuthProvider,
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "🎉", "password": "😎"}
)
assert credentials.is_new is True

View File

@@ -0,0 +1,461 @@
"""Test the Trusted Networks auth provider."""
from ipaddress import ip_address, ip_network
from unittest.mock import Mock, patch
from hass_nabucasa import remote
import pytest
import voluptuous as vol
from homeassistant import auth
from homeassistant.auth import auth_store
from homeassistant.auth.providers import trusted_networks as tn_auth
from homeassistant.components.http import CONF_TRUSTED_PROXIES, CONF_USE_X_FORWARDED_FOR
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.setup import async_setup_component
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""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",
],
}
),
)
@pytest.fixture
def provider_with_user(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""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": [],
},
}
),
)
@pytest.fixture
def provider_bypass_login(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""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,
}
),
)
@pytest.fixture
def manager(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager."""
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
@pytest.fixture
def manager_with_user(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager with trusted user."""
return auth.AuthManager(
hass,
store,
{(provider_with_user.type, provider_with_user.id): provider_with_user},
{},
)
@pytest.fixture
def manager_bypass_login(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider_bypass_login: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager with allow bypass login."""
return auth.AuthManager(
hass,
store,
{(provider_bypass_login.type, provider_bypass_login.id): provider_bypass_login},
{},
)
async def test_config_schema() -> None:
"""Test CONFIG_SCHEMA."""
# Valid configuration
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": ["192.168.0.1"],
"trusted_users": {
"192.168.0.1": [
"a1ab982744b64757bf80515589258924",
{"group": "system-group"},
]
},
}
)
# Wrong user id format
with pytest.raises(vol.Invalid):
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": ["192.168.0.1"],
"trusted_users": {"192.168.0.1": ["abcde"]},
}
)
async def test_trusted_networks_credentials(
manager: auth.AuthManager, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""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})
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})
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"})
async def test_validate_access(provider: tn_auth.TrustedNetworksAuthProvider) -> None:
"""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"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.0.2"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("127.0.0.1"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("2001:db8::ff00:42:8329"))
async def test_validate_access_proxy(
hass: HomeAssistant, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test validate access from trusted networks are blocked from proxy."""
await async_setup_component(
hass,
"http",
{
"http": {
CONF_TRUSTED_PROXIES: ["192.168.128.0/31", "fd00::1"],
CONF_USE_X_FORWARDED_FOR: True,
}
},
)
provider.async_validate_access(ip_address("192.168.128.2"))
provider.async_validate_access(ip_address("fd00::2"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.0"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.1"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("fd00::1"))
async def test_validate_access_cloud(
hass: HomeAssistant, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test validate access from trusted networks are blocked from cloud."""
await async_setup_component(
hass,
"http",
{
"http": {
CONF_TRUSTED_PROXIES: ["192.168.128.0/31", "fd00::1"],
CONF_USE_X_FORWARDED_FOR: True,
}
},
)
hass.config.components.add("cloud")
provider.async_validate_access(ip_address("192.168.128.2"))
remote.is_cloud_request.set(True)
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.2"))
async def test_validate_refresh_token(
provider: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Verify re-validation of refresh token."""
with patch.object(provider, "async_validate_access") as mock:
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_refresh_token(Mock(), None)
provider.async_validate_refresh_token(Mock(), "127.0.0.1")
mock.assert_called_once_with(ip_address("127.0.0.1"))
async def test_login_flow(
manager: auth.AuthManager, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test login flow."""
owner = await manager.async_create_user("test-owner")
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")})
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users
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"
schema = step["data_schema"]
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": "invalid-user"})
# login with valid user
step = await flow.async_step_init({"user": user.id})
assert step["type"] == FlowResultType.CREATE_ENTRY
assert step["data"]["user"] == user.id
async def test_trusted_users_login(
manager_with_user: auth.AuthManager,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""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
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]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only owner listed
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
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")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only user listed
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
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")})
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
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")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# no user listed
with pytest.raises(vol.Invalid):
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": sys_user.id})
async def test_trusted_group_login(
manager_with_user: auth.AuthManager,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Test config trusted_user with group_id."""
owner = await manager_with_user.async_create_user("test-owner")
# 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]
)
# 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]},
]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only user listed
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
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")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})
async def test_bypass_login_flow(
manager_bypass_login: auth.AuthManager,
provider_bypass_login: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Test login flow can be bypass if only one user available."""
owner = await manager_bypass_login.async_create_user("test-owner")
# not from trusted network
flow = await provider_bypass_login.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# 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")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.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")}
)
step = await flow.async_step_init()
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})

View File

@@ -0,0 +1,381 @@
"""Tests for the auth store."""
import asyncio
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.auth import auth_store
from homeassistant.core import HomeAssistant
MOCK_STORAGE_DATA = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
{
"id": "system-id",
"is_active": True,
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id",
"version": "1.2.3",
},
{
"access_token_expiration": 1800.0,
"client_id": None,
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "system-token-id",
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "system-id",
},
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "hidden-because-no-jwt-id",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id",
},
],
},
}
async def test_loading_no_group_data_format(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load old data without any groups."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
read_group = groups[1]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
user_group = groups[2]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
users = await store.async_get_users()
assert len(users) == 2
owner, system = users
assert owner.system_generated is False
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.version == "1.2.3"
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.version is None
async def test_loading_all_access_group_data_format(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load old data with single group."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
read_group = groups[1]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
user_group = groups[2]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
users = await store.async_get_users()
assert len(users) == 2
owner, system = users
assert owner.system_generated is False
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.version == "1.2.3"
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.version is None
async def test_loading_empty_data(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load with no existing data."""
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
user_group = groups[1]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
read_group = groups[2]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
users = await store.async_get_users()
assert len(users) == 0
async def test_system_groups_store_id_and_name(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test that for system groups we store the ID and name.
Name is stored so that we remain backwards compat with < 0.82.
"""
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},
]
async def test_loading_only_once(hass: HomeAssistant) -> None:
"""Test only one storage load is allowed."""
store = auth_store.AuthStore(hass)
with (
patch("homeassistant.helpers.entity_registry.async_get") as mock_ent_registry,
patch("homeassistant.helpers.device_registry.async_get") as mock_dev_registry,
patch(
"homeassistant.helpers.storage.Store.async_load", return_value=None
) as mock_load,
):
await store.async_load()
with pytest.raises(RuntimeError, match="Auth storage is already loaded"):
await store.async_load()
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)
mock_load.assert_called_once_with()
assert results[0] == results[1]
async def test_dont_change_expire_at_on_load(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly don't modify expired_at store load."""
hass_storage[auth_store.STORAGE_KEY] = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
{
"id": "system-id",
"is_active": True,
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"token": "some-token",
"user_id": "user-id",
"version": "1.2.3",
},
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id2",
"jwt_key": "some-key2",
"token": "some-token",
"user_id": "user-id",
"expire_at": 1724133771.079745,
},
],
},
}
store = auth_store.AuthStore(hass)
await store.async_load()
users = await store.async_get_users()
assert len(users[0].refresh_tokens) == 2
token1, token2 = users[0].refresh_tokens.values()
assert not token1.expire_at
assert token2.expire_at == 1724133771.079745
async def test_loading_does_not_write_right_away(
hass: HomeAssistant, hass_storage: dict[str, Any], freezer: FrozenDateTimeFactory
) -> None:
"""Test after calling load we wait five minutes to write."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
# Wipe storage so we can verify if it was written
hass_storage[auth_store.STORAGE_KEY] = {}
freezer.tick(auth_store.DEFAULT_SAVE_DELAY)
await hass.async_block_till_done()
assert hass_storage[auth_store.STORAGE_KEY] == {}
freezer.tick(auth_store.INITIAL_LOAD_SAVE_DELAY)
# Once for scheduling the task
await hass.async_block_till_done()
# Once for the task
await hass.async_block_till_done()
assert hass_storage[auth_store.STORAGE_KEY] != {}
async def test_add_remove_user_affects_tokens(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test adding and removing a user removes the tokens."""
store = auth_store.AuthStore(hass)
await store.async_load()
user = await store.async_create_user("Test User")
assert user.name == "Test User"
refresh_token = await store.async_create_refresh_token(
user, "client_id", "access_token_expiration"
)
assert user.refresh_tokens == {refresh_token.id: refresh_token}
assert await store.async_get_user(user.id) == user
assert store.async_get_refresh_token(refresh_token.id) == refresh_token
assert store.async_get_refresh_token_by_token(refresh_token.token) == refresh_token
await store.async_remove_user(user)
assert store.async_get_refresh_token(refresh_token.id) is None
assert store.async_get_refresh_token_by_token(refresh_token.token) is None
assert user.refresh_tokens == {}
async def test_set_expiry_date(
hass: HomeAssistant, hass_storage: dict[str, Any], freezer: FrozenDateTimeFactory
) -> None:
"""Test set expiry date of a refresh token."""
hass_storage[auth_store.STORAGE_KEY] = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"token": "some-token",
"user_id": "user-id",
"expire_at": 1724133771.079745,
},
],
},
}
store = auth_store.AuthStore(hass)
await store.async_load()
users = await store.async_get_users()
assert len(users[0].refresh_tokens) == 1
(token,) = users[0].refresh_tokens.values()
assert token.expire_at == 1724133771.079745
store.async_set_expiry(token, enable_expiry=False)
assert token.expire_at is None
freezer.tick(auth_store.DEFAULT_SAVE_DELAY * 2)
# Once for scheduling the task
await hass.async_block_till_done()
# Once for the task
await hass.async_block_till_done()
# verify token is saved without expire_at
assert (
hass_storage[auth_store.STORAGE_KEY]["data"]["refresh_tokens"][0]["expire_at"]
is None
)
store.async_set_expiry(token, enable_expiry=True)
assert token.expire_at is not None

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
"""Tests for the Home Assistant auth jwt_wrapper module."""
import jwt
import pytest
from homeassistant.auth import jwt_wrapper
async def test_all_default_options_are_in_verify_options() -> None:
"""Test that all default options in _VERIFY_OPTIONS."""
for option in jwt_wrapper._PyJWTWithVerify._get_default_options():
assert option in jwt_wrapper._VERIFY_OPTIONS
async def test_reject_access_token_with_impossible_large_size() -> None:
"""Test rejecting access tokens with impossible sizes."""
with pytest.raises(jwt.DecodeError):
jwt_wrapper.unverified_hs256_token_decode("a" * 10000)

View File

@@ -0,0 +1,63 @@
"""Tests for the auth models."""
from homeassistant.auth import models, permissions
def test_owner_fetching_owner_permissions() -> None:
"""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
)
assert owner.permissions is permissions.OwnerPermissions
def test_permissions_merged() -> None:
"""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])
# 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
def test_cache_cleared_on_group_change() -> None:
"""Test we clear the cache when a group changes."""
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
admin_group = models.Group(
name="Admin group", id=models.GROUP_ID_ADMIN, policy={"entities": {}}
)
user = models.User(
name="Test User", perm_lookup=None, groups=[group], is_active=True
)
# Make sure we cache instance
assert user.permissions is user.permissions
# Make sure we cache is_admin
assert user.is_admin is user.is_admin
assert user.is_active is True
user.groups = []
assert user.groups == []
assert user.is_admin is False
user.is_owner = True
assert user.is_admin is True
user.is_owner = False
assert user.is_admin is False
user.groups = [admin_group]
assert user.is_admin is True
user.is_active = False
assert user.is_admin is False