init home-assistant
This commit is contained in:
47
home-assistant/tests/components/auth/__init__.py
Normal file
47
home-assistant/tests/components/auth/__init__.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Tests for the auth component."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant import auth
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.typing import UNDEFINED, UndefinedType
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import ensure_auth_manager_loaded
|
||||
from tests.test_util import mock_real_ip
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
BASE_CONFIG = [
|
||||
{
|
||||
"name": "Example",
|
||||
"type": "insecure_example",
|
||||
"users": [
|
||||
{"username": "test-user", "password": "test-pass", "name": "Test Name"}
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
EMPTY_CONFIG = []
|
||||
|
||||
|
||||
async def async_setup_auth(
|
||||
hass: HomeAssistant,
|
||||
aiohttp_client: ClientSessionGenerator,
|
||||
provider_configs: list[dict[str, Any]] | UndefinedType = UNDEFINED,
|
||||
module_configs: list[dict[str, Any]] | UndefinedType = UNDEFINED,
|
||||
setup_api: bool = False,
|
||||
custom_ip: str | None = None,
|
||||
):
|
||||
"""Set up authentication and create an HTTP client."""
|
||||
hass.auth = await auth.auth_manager_from_config(
|
||||
hass,
|
||||
BASE_CONFIG if provider_configs is UNDEFINED else provider_configs,
|
||||
EMPTY_CONFIG if module_configs is UNDEFINED else module_configs,
|
||||
)
|
||||
ensure_auth_manager_loaded(hass.auth)
|
||||
await async_setup_component(hass, "auth", {})
|
||||
if setup_api:
|
||||
await async_setup_component(hass, "api", {})
|
||||
if custom_ip:
|
||||
mock_real_ip(hass.http.app)(custom_ip)
|
||||
return await aiohttp_client(hass.http.app)
|
||||
17
home-assistant/tests/components/auth/conftest.py
Normal file
17
home-assistant/tests/components/auth/conftest.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""Test configuration for auth."""
|
||||
|
||||
from asyncio import AbstractEventLoop
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def aiohttp_client(
|
||||
event_loop: AbstractEventLoop,
|
||||
aiohttp_client: ClientSessionGenerator,
|
||||
socket_enabled: None,
|
||||
) -> ClientSessionGenerator:
|
||||
"""Return aiohttp_client and allow opening sockets."""
|
||||
return aiohttp_client
|
||||
210
home-assistant/tests/components/auth/test_indieauth.py
Normal file
210
home-assistant/tests/components/auth/test_indieauth.py
Normal file
@@ -0,0 +1,210 @@
|
||||
"""Tests for the client validator."""
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.auth import indieauth
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.test_util.aiohttp import AiohttpClientMocker
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_session():
|
||||
"""Mock aiohttp.ClientSession."""
|
||||
mocker = AiohttpClientMocker()
|
||||
|
||||
with patch(
|
||||
"aiohttp.ClientSession",
|
||||
side_effect=lambda *args, **kwargs: mocker.create_session(
|
||||
asyncio.get_event_loop()
|
||||
),
|
||||
):
|
||||
yield mocker
|
||||
|
||||
|
||||
def test_client_id_scheme() -> None:
|
||||
"""Test we enforce valid scheme."""
|
||||
assert indieauth._parse_client_id("http://ex.com/")
|
||||
assert indieauth._parse_client_id("https://ex.com/")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("ftp://ex.com")
|
||||
|
||||
|
||||
def test_client_id_path() -> None:
|
||||
"""Test we enforce valid path."""
|
||||
assert indieauth._parse_client_id("http://ex.com").path == "/"
|
||||
assert indieauth._parse_client_id("http://ex.com/hello").path == "/hello"
|
||||
assert (
|
||||
indieauth._parse_client_id("http://ex.com/hello/.world").path == "/hello/.world"
|
||||
)
|
||||
assert (
|
||||
indieauth._parse_client_id("http://ex.com/hello./.world").path
|
||||
== "/hello./.world"
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://ex.com/.")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://ex.com/hello/./yo")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://ex.com/hello/../yo")
|
||||
|
||||
|
||||
def test_client_id_fragment() -> None:
|
||||
"""Test we enforce valid fragment."""
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://ex.com/#yoo")
|
||||
|
||||
|
||||
def test_client_id_user_pass() -> None:
|
||||
"""Test we enforce valid username/password."""
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://user@ex.com/")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
indieauth._parse_client_id("http://user:pass@ex.com/")
|
||||
|
||||
|
||||
def test_client_id_hostname() -> None:
|
||||
"""Test we enforce valid hostname."""
|
||||
assert indieauth._parse_client_id("http://www.home-assistant.io/")
|
||||
assert indieauth._parse_client_id("http://[::1]")
|
||||
assert indieauth._parse_client_id("http://127.0.0.1")
|
||||
assert indieauth._parse_client_id("http://10.0.0.0")
|
||||
assert indieauth._parse_client_id("http://10.255.255.255")
|
||||
assert indieauth._parse_client_id("http://172.16.0.0")
|
||||
assert indieauth._parse_client_id("http://172.31.255.255")
|
||||
assert indieauth._parse_client_id("http://192.168.0.0")
|
||||
assert indieauth._parse_client_id("http://192.168.255.255")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
assert indieauth._parse_client_id("http://255.255.255.255/")
|
||||
with pytest.raises(ValueError):
|
||||
assert indieauth._parse_client_id("http://11.0.0.0/")
|
||||
with pytest.raises(ValueError):
|
||||
assert indieauth._parse_client_id("http://172.32.0.0/")
|
||||
with pytest.raises(ValueError):
|
||||
assert indieauth._parse_client_id("http://192.167.0.0/")
|
||||
|
||||
|
||||
def test_parse_url_lowercase_host() -> None:
|
||||
"""Test we update empty paths."""
|
||||
assert indieauth._parse_url("http://ex.com/hello").path == "/hello"
|
||||
assert indieauth._parse_url("http://EX.COM/hello").hostname == "ex.com"
|
||||
|
||||
parts = indieauth._parse_url("http://EX.COM:123/HELLO")
|
||||
assert parts.netloc == "ex.com:123"
|
||||
assert parts.path == "/HELLO"
|
||||
|
||||
|
||||
def test_parse_url_path() -> None:
|
||||
"""Test we update empty paths."""
|
||||
assert indieauth._parse_url("http://ex.com").path == "/"
|
||||
|
||||
|
||||
async def test_verify_redirect_uri() -> None:
|
||||
"""Test that we verify redirect uri correctly."""
|
||||
assert await indieauth.verify_redirect_uri(
|
||||
None, "http://ex.com", "http://ex.com/callback"
|
||||
)
|
||||
|
||||
with patch.object(indieauth, "fetch_redirect_uris", return_value=[]):
|
||||
# Different domain
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None, "http://ex.com", "http://different.com/callback"
|
||||
)
|
||||
|
||||
# Different scheme
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None, "http://ex.com", "https://ex.com/callback"
|
||||
)
|
||||
|
||||
# Different subdomain
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None, "https://sub1.ex.com", "https://sub2.ex.com/callback"
|
||||
)
|
||||
|
||||
|
||||
async def test_find_link_tag(hass: HomeAssistant, mock_session) -> None:
|
||||
"""Test finding link tag."""
|
||||
mock_session.get(
|
||||
"http://127.0.0.1:8000",
|
||||
text="""
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="redirect_uri" href="hass://oauth2_redirect">
|
||||
<link rel="other_value" href="hass://oauth2_redirect">
|
||||
<link rel="redirect_uri" href="/beer">
|
||||
</head>
|
||||
...
|
||||
</html>
|
||||
""",
|
||||
)
|
||||
redirect_uris = await indieauth.fetch_redirect_uris(hass, "http://127.0.0.1:8000")
|
||||
|
||||
assert redirect_uris == ["hass://oauth2_redirect", "http://127.0.0.1:8000/beer"]
|
||||
|
||||
|
||||
async def test_find_link_tag_max_size(hass: HomeAssistant, mock_session) -> None:
|
||||
"""Test finding link tag."""
|
||||
text = "".join(
|
||||
[
|
||||
'<link rel="redirect_uri" href="/wine">',
|
||||
("0" * 1024 * 10),
|
||||
'<link rel="redirect_uri" href="/beer">',
|
||||
]
|
||||
)
|
||||
mock_session.get("http://127.0.0.1:8000", text=text)
|
||||
redirect_uris = await indieauth.fetch_redirect_uris(hass, "http://127.0.0.1:8000")
|
||||
|
||||
assert redirect_uris == ["http://127.0.0.1:8000/wine"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"client_id",
|
||||
["https://home-assistant.io/android", "https://home-assistant.io/iOS"],
|
||||
)
|
||||
async def test_verify_redirect_uri_android_ios(client_id) -> None:
|
||||
"""Test that we verify redirect uri correctly for Android/iOS."""
|
||||
with patch.object(indieauth, "fetch_redirect_uris", return_value=[]):
|
||||
assert await indieauth.verify_redirect_uri(
|
||||
None, client_id, "homeassistant://auth-callback"
|
||||
)
|
||||
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None, client_id, "homeassistant://something-else"
|
||||
)
|
||||
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None, "https://incorrect.com", "homeassistant://auth-callback"
|
||||
)
|
||||
|
||||
if client_id == "https://home-assistant.io/android":
|
||||
assert await indieauth.verify_redirect_uri(
|
||||
None,
|
||||
client_id,
|
||||
"https://wear.googleapis.com/3p_auth/io.homeassistant.companion.android",
|
||||
)
|
||||
assert await indieauth.verify_redirect_uri(
|
||||
None,
|
||||
client_id,
|
||||
"https://wear.googleapis-cn.com/3p_auth/io.homeassistant.companion.android",
|
||||
)
|
||||
else:
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None,
|
||||
client_id,
|
||||
"https://wear.googleapis.com/3p_auth/io.homeassistant.companion.android",
|
||||
)
|
||||
assert not await indieauth.verify_redirect_uri(
|
||||
None,
|
||||
client_id,
|
||||
"https://wear.googleapis-cn.com/3p_auth/io.homeassistant.companion.android",
|
||||
)
|
||||
762
home-assistant/tests/components/auth/test_init.py
Normal file
762
home-assistant/tests/components/auth/test_init.py
Normal file
@@ -0,0 +1,762 @@
|
||||
"""Integration tests for the auth component."""
|
||||
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
|
||||
from homeassistant.auth import InvalidAuthError
|
||||
from homeassistant.auth.models import (
|
||||
TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN,
|
||||
TOKEN_TYPE_NORMAL,
|
||||
Credentials,
|
||||
RefreshToken,
|
||||
)
|
||||
from homeassistant.components import auth
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from . import async_setup_auth
|
||||
|
||||
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI, MockUser
|
||||
from tests.typing import ClientSessionGenerator, WebSocketGenerator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_credential():
|
||||
"""Return a mock credential."""
|
||||
return Credentials(
|
||||
id="mock-credential-id",
|
||||
auth_provider_type="insecure_example",
|
||||
auth_provider_id=None,
|
||||
data={"username": "test-user"},
|
||||
is_new=False,
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_user_refresh_token(hass: HomeAssistant) -> RefreshToken:
|
||||
"""Create a testing user with a connected credential."""
|
||||
user = await hass.auth.async_create_user("Test User")
|
||||
|
||||
credential = Credentials(
|
||||
id="mock-credential-id",
|
||||
auth_provider_type="insecure_example",
|
||||
auth_provider_id=None,
|
||||
data={"username": "test-user"},
|
||||
is_new=False,
|
||||
)
|
||||
user.credentials.append(credential)
|
||||
|
||||
return await hass.auth.async_create_refresh_token(
|
||||
user, CLIENT_ID, credential=credential
|
||||
)
|
||||
|
||||
|
||||
async def test_login_new_user_and_trying_refresh_token(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in with new user and refreshing tokens."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
code = step["result"]
|
||||
|
||||
# Exchange code for tokens
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={"client_id": CLIENT_ID, "grant_type": "authorization_code", "code": code},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
tokens = await resp.json()
|
||||
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None
|
||||
assert tokens["ha_auth_provider"] == "insecure_example"
|
||||
|
||||
# Use refresh token to get more tokens.
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": tokens["refresh_token"],
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
tokens = await resp.json()
|
||||
assert "refresh_token" not in tokens
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None
|
||||
|
||||
# Test using access token to hit API.
|
||||
resp = await client.get("/api/")
|
||||
assert resp.status == HTTPStatus.UNAUTHORIZED
|
||||
|
||||
resp = await client.get(
|
||||
"/api/", headers={"authorization": f"Bearer {tokens['access_token']}"}
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
|
||||
|
||||
async def test_auth_code_checks_local_only_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test local only user cannot exchange auth code for refresh tokens when external."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
code = step["result"]
|
||||
|
||||
# Exchange code for tokens
|
||||
with patch(
|
||||
"homeassistant.components.auth.async_user_not_allowed_do_auth",
|
||||
return_value="User is local only",
|
||||
):
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
error = await resp.json()
|
||||
assert error["error"] == "access_denied"
|
||||
|
||||
|
||||
def test_auth_code_store_expiration(
|
||||
mock_credential, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
"""Test that the auth code store will not return expired tokens."""
|
||||
store, retrieve = auth._create_auth_code_store()
|
||||
client_id = "bla"
|
||||
now = utcnow()
|
||||
|
||||
freezer.move_to(now)
|
||||
code = store(client_id, mock_credential)
|
||||
|
||||
freezer.move_to(now + timedelta(minutes=10))
|
||||
assert retrieve(client_id, code) is None
|
||||
|
||||
freezer.move_to(now)
|
||||
code = store(client_id, mock_credential)
|
||||
|
||||
freezer.move_to(now + timedelta(minutes=9, seconds=59))
|
||||
assert retrieve(client_id, code) == mock_credential
|
||||
|
||||
|
||||
def test_auth_code_store_requires_credentials(mock_credential) -> None:
|
||||
"""Test we require credentials."""
|
||||
store, _retrieve = auth._create_auth_code_store()
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
store(None, MockUser())
|
||||
|
||||
store(None, mock_credential)
|
||||
|
||||
|
||||
async def test_ws_current_user(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
|
||||
) -> None:
|
||||
"""Test the current user command with Home Assistant creds."""
|
||||
assert await async_setup_component(hass, "auth", {})
|
||||
|
||||
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
|
||||
user = refresh_token.user
|
||||
client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
await client.send_json({"id": 5, "type": "auth/current_user"})
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["success"], result
|
||||
|
||||
user_dict = result["result"]
|
||||
|
||||
assert user_dict["name"] == user.name
|
||||
assert user_dict["id"] == user.id
|
||||
assert user_dict["is_owner"] == user.is_owner
|
||||
assert len(user_dict["credentials"]) == 1
|
||||
|
||||
hass_cred = user_dict["credentials"][0]
|
||||
assert hass_cred["auth_provider_type"] == "homeassistant"
|
||||
assert hass_cred["auth_provider_id"] is None
|
||||
assert "data" not in hass_cred
|
||||
|
||||
|
||||
async def test_cors_on_token(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in with new user and refreshing tokens."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
|
||||
resp = await client.options(
|
||||
"/auth/token",
|
||||
headers={
|
||||
"origin": "http://example.com",
|
||||
"Access-Control-Request-Method": "POST",
|
||||
},
|
||||
)
|
||||
assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com"
|
||||
assert resp.headers["Access-Control-Allow-Methods"] == "POST"
|
||||
|
||||
resp = await client.post("/auth/token", headers={"origin": "http://example.com"})
|
||||
assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com"
|
||||
|
||||
|
||||
async def test_refresh_token_system_generated(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test that we can get access tokens for system generated user."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
user = await hass.auth.async_create_system_user("Test System")
|
||||
refresh_token = await hass.auth.async_create_refresh_token(user, None)
|
||||
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": "https://this-is-not-allowed-for-system-users.com/",
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
result = await resp.json()
|
||||
assert result["error"] == "invalid_request"
|
||||
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
tokens = await resp.json()
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None
|
||||
|
||||
|
||||
async def test_refresh_token_different_client_id(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test that we verify client ID."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
refresh_token = await async_setup_user_refresh_token(hass)
|
||||
|
||||
# No client ID
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
result = await resp.json()
|
||||
assert result["error"] == "invalid_request"
|
||||
|
||||
# Different client ID
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": "http://example-different.com",
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
result = await resp.json()
|
||||
assert result["error"] == "invalid_request"
|
||||
|
||||
# Correct
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
tokens = await resp.json()
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None
|
||||
|
||||
|
||||
async def test_refresh_token_checks_local_only_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test that we can't refresh token for a local only user when external."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
refresh_token = await async_setup_user_refresh_token(hass)
|
||||
refresh_token.user.local_only = True
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.auth.async_user_not_allowed_do_auth",
|
||||
return_value="User is local only",
|
||||
):
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
result = await resp.json()
|
||||
assert result["error"] == "access_denied"
|
||||
|
||||
|
||||
async def test_refresh_token_provider_rejected(
|
||||
hass: HomeAssistant,
|
||||
aiohttp_client: ClientSessionGenerator,
|
||||
hass_admin_user: MockUser,
|
||||
hass_admin_credential: Credentials,
|
||||
) -> None:
|
||||
"""Test that we verify client ID."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
refresh_token = await async_setup_user_refresh_token(hass)
|
||||
|
||||
# Rejected by provider
|
||||
with patch(
|
||||
"homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token",
|
||||
side_effect=InvalidAuthError("Invalid access"),
|
||||
):
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
result = await resp.json()
|
||||
assert result["error"] == "access_denied"
|
||||
assert result["error_description"] == "Invalid access"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "base_data"), [("/auth/token", {"action": "revoke"}), ("/auth/revoke", {})]
|
||||
)
|
||||
async def test_revoking_refresh_token(
|
||||
url, base_data, hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test that we can revoke refresh tokens."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
refresh_token = await async_setup_user_refresh_token(hass)
|
||||
|
||||
# Test that we can create an access token
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
tokens = await resp.json()
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None
|
||||
|
||||
# Revoke refresh token
|
||||
resp = await client.post(url, data={**base_data, "token": refresh_token.token})
|
||||
assert resp.status == HTTPStatus.OK
|
||||
|
||||
# Old access token should be no longer valid
|
||||
assert hass.auth.async_validate_access_token(tokens["access_token"]) is None
|
||||
|
||||
# Test that we no longer can create an access token
|
||||
resp = await client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"client_id": CLIENT_ID,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token.token,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
async def test_ws_long_lived_access_token(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
|
||||
) -> None:
|
||||
"""Test generate long-lived access token."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
# verify create long-lived access token
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "auth/long_lived_access_token",
|
||||
"client_name": "GPS Logger",
|
||||
"lifespan": 365,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
|
||||
long_lived_access_token = result["result"]
|
||||
assert long_lived_access_token is not None
|
||||
|
||||
refresh_token = hass.auth.async_validate_access_token(long_lived_access_token)
|
||||
assert refresh_token.client_id is None
|
||||
assert refresh_token.client_name == "GPS Logger"
|
||||
assert refresh_token.client_icon is None
|
||||
|
||||
|
||||
async def test_ws_refresh_tokens(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
|
||||
) -> None:
|
||||
"""Test fetching refresh token metadata."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
await ws_client.send_json({"id": 5, "type": "auth/refresh_tokens"})
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
assert len(result["result"]) == 1
|
||||
token = result["result"][0]
|
||||
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
|
||||
assert token["id"] == refresh_token.id
|
||||
assert token["type"] == refresh_token.token_type
|
||||
assert token["client_id"] == refresh_token.client_id
|
||||
assert token["client_name"] == refresh_token.client_name
|
||||
assert token["client_icon"] == refresh_token.client_icon
|
||||
assert token["created_at"] == refresh_token.created_at.isoformat()
|
||||
assert token["is_current"] is True
|
||||
assert token["last_used_at"] == refresh_token.last_used_at.isoformat()
|
||||
assert token["last_used_ip"] == refresh_token.last_used_ip
|
||||
assert token["auth_provider_type"] == "homeassistant"
|
||||
|
||||
|
||||
async def test_ws_delete_refresh_token(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
hass_admin_credential: Credentials,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_access_token: str,
|
||||
) -> None:
|
||||
"""Test deleting a refresh token."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
refresh_token = await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
|
||||
)
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
# verify create long-lived access token
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "auth/delete_refresh_token",
|
||||
"refresh_token_id": refresh_token.id,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
refresh_token = hass.auth.async_get_refresh_token(refresh_token.id)
|
||||
assert refresh_token is None
|
||||
|
||||
|
||||
async def test_ws_delete_all_refresh_tokens_error(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
hass_admin_credential: Credentials,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_access_token: str,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test deleting all refresh tokens, where a revoke callback raises an error."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
# one token already exists
|
||||
await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
|
||||
)
|
||||
token = await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, CLIENT_ID + "_1", credential=hass_admin_credential
|
||||
)
|
||||
|
||||
def cb():
|
||||
raise RuntimeError("I'm bad")
|
||||
|
||||
hass.auth.async_register_revoke_token_callback(token.id, cb)
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
# get all tokens
|
||||
await ws_client.send_json({"id": 5, "type": "auth/refresh_tokens"})
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
|
||||
tokens = result["result"]
|
||||
|
||||
with patch("homeassistant.components.auth.DELETE_CURRENT_TOKEN_DELAY", 0.001):
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 6,
|
||||
"type": "auth/delete_all_refresh_tokens",
|
||||
}
|
||||
)
|
||||
|
||||
caplog.clear()
|
||||
result = await ws_client.receive_json()
|
||||
assert result, result["success"] is False
|
||||
assert result["error"] == {
|
||||
"code": "token_removing_error",
|
||||
"message": "During removal, an error was raised.",
|
||||
}
|
||||
|
||||
records = [
|
||||
record
|
||||
for record in caplog.records
|
||||
if record.msg == "Error during refresh token removal"
|
||||
]
|
||||
assert len(records) == 1
|
||||
assert records[0].levelno == logging.ERROR
|
||||
assert records[0].exc_info and str(records[0].exc_info[1]) == "I'm bad"
|
||||
assert records[0].name == "homeassistant.components.auth"
|
||||
|
||||
await hass.async_block_till_done()
|
||||
for token in tokens:
|
||||
refresh_token = hass.auth.async_get_refresh_token(token["id"])
|
||||
assert refresh_token is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"delete_token_type",
|
||||
"delete_current_token",
|
||||
"expected_remaining_normal_tokens",
|
||||
"expected_remaining_long_lived_tokens",
|
||||
),
|
||||
[
|
||||
({}, {}, 0, 0),
|
||||
({"token_type": TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN}, {}, 3, 0),
|
||||
({"token_type": TOKEN_TYPE_NORMAL}, {}, 0, 1),
|
||||
({"token_type": TOKEN_TYPE_NORMAL}, {"delete_current_token": False}, 1, 1),
|
||||
],
|
||||
)
|
||||
async def test_ws_delete_all_refresh_tokens(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
hass_admin_credential: Credentials,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_access_token: str,
|
||||
delete_token_type: dict[str, str],
|
||||
delete_current_token: dict[str, bool],
|
||||
expected_remaining_normal_tokens: int,
|
||||
expected_remaining_long_lived_tokens: int,
|
||||
) -> None:
|
||||
"""Test deleting all or some refresh tokens."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
# one token already exists
|
||||
await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
|
||||
)
|
||||
|
||||
# create a long lived token
|
||||
await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user,
|
||||
f"{CLIENT_ID}_LL",
|
||||
client_name="client_ll",
|
||||
credential=hass_admin_credential,
|
||||
token_type=TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN,
|
||||
)
|
||||
|
||||
await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, f"{CLIENT_ID}_1", credential=hass_admin_credential
|
||||
)
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
# get all tokens
|
||||
await ws_client.send_json({"id": 5, "type": "auth/refresh_tokens"})
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
|
||||
with patch("homeassistant.components.auth.DELETE_CURRENT_TOKEN_DELAY", 0.001):
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 6,
|
||||
"type": "auth/delete_all_refresh_tokens",
|
||||
**delete_token_type,
|
||||
**delete_current_token,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result, result["success"]
|
||||
|
||||
await hass.async_block_till_done()
|
||||
# We need to enumerate the user since we may remove the token
|
||||
# that is used to authenticate the user which will prevent the websocket
|
||||
# connection from working
|
||||
remaining_tokens_by_type: dict[str, int] = {
|
||||
TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN: 0,
|
||||
TOKEN_TYPE_NORMAL: 0,
|
||||
}
|
||||
for refresh_token in hass_admin_user.refresh_tokens.values():
|
||||
remaining_tokens_by_type[refresh_token.token_type] += 1
|
||||
|
||||
assert (
|
||||
remaining_tokens_by_type[TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN]
|
||||
== expected_remaining_long_lived_tokens
|
||||
)
|
||||
assert (
|
||||
remaining_tokens_by_type[TOKEN_TYPE_NORMAL] == expected_remaining_normal_tokens
|
||||
)
|
||||
|
||||
|
||||
async def test_ws_sign_path(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
|
||||
) -> None:
|
||||
"""Test signing a path."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.auth.async_sign_path", return_value="hello_world"
|
||||
) as mock_sign:
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "auth/sign_path",
|
||||
"path": "/api/hello",
|
||||
"expires": 20,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
assert result["result"] == {"path": "hello_world"}
|
||||
assert len(mock_sign.mock_calls) == 1
|
||||
hass, path, expires = mock_sign.mock_calls[0][1]
|
||||
assert path == "/api/hello"
|
||||
assert expires.total_seconds() == 20
|
||||
|
||||
|
||||
async def test_ws_refresh_token_set_expiry(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
hass_admin_credential: Credentials,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_access_token: str,
|
||||
) -> None:
|
||||
"""Test setting expiry of a refresh token."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
refresh_token = await hass.auth.async_create_refresh_token(
|
||||
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
|
||||
)
|
||||
assert refresh_token.expire_at is not None
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
await ws_client.send_json_auto_id(
|
||||
{
|
||||
"type": "auth/refresh_token_set_expiry",
|
||||
"refresh_token_id": refresh_token.id,
|
||||
"enable_expiry": False,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
refresh_token = hass.auth.async_get_refresh_token(refresh_token.id)
|
||||
assert refresh_token.expire_at is None
|
||||
|
||||
await ws_client.send_json_auto_id(
|
||||
{
|
||||
"type": "auth/refresh_token_set_expiry",
|
||||
"refresh_token_id": refresh_token.id,
|
||||
"enable_expiry": True,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result["success"], result
|
||||
refresh_token = hass.auth.async_get_refresh_token(refresh_token.id)
|
||||
assert refresh_token.expire_at is not None
|
||||
|
||||
|
||||
async def test_ws_refresh_token_set_expiry_error(
|
||||
hass: HomeAssistant,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_access_token: str,
|
||||
) -> None:
|
||||
"""Test setting expiry of a invalid refresh token returns error."""
|
||||
assert await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
ws_client = await hass_ws_client(hass, hass_access_token)
|
||||
|
||||
await ws_client.send_json_auto_id(
|
||||
{
|
||||
"type": "auth/refresh_token_set_expiry",
|
||||
"refresh_token_id": "invalid",
|
||||
"enable_expiry": False,
|
||||
}
|
||||
)
|
||||
|
||||
result = await ws_client.receive_json()
|
||||
assert result, result["success"] is False
|
||||
assert result["error"] == {
|
||||
"code": "invalid_token_id",
|
||||
"message": "Received invalid token",
|
||||
}
|
||||
195
home-assistant/tests/components/auth/test_init_link_user.py
Normal file
195
home-assistant/tests/components/auth/test_init_link_user.py
Normal file
@@ -0,0 +1,195 @@
|
||||
"""Tests for the link user flow."""
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import async_setup_auth
|
||||
|
||||
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def async_get_code(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> dict[str, Any]:
|
||||
"""Return authorization code for link user tests."""
|
||||
config = [
|
||||
{
|
||||
"name": "Example",
|
||||
"type": "insecure_example",
|
||||
"users": [
|
||||
{"username": "test-user", "password": "test-pass", "name": "Test Name"}
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "Example",
|
||||
"id": "2nd auth",
|
||||
"type": "insecure_example",
|
||||
"users": [
|
||||
{"username": "2nd-user", "password": "2nd-pass", "name": "2nd Name"}
|
||||
],
|
||||
},
|
||||
]
|
||||
client = await async_setup_auth(hass, aiohttp_client, config)
|
||||
user = await hass.auth.async_create_user(name="Hello")
|
||||
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
|
||||
access_token = hass.auth.async_create_access_token(refresh_token)
|
||||
|
||||
# Now authenticate with the 2nd flow
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", "2nd auth"],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
"type": "link_user",
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "2nd-user",
|
||||
"password": "2nd-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"code": step["result"],
|
||||
"client": client,
|
||||
"access_token": access_token,
|
||||
}
|
||||
|
||||
|
||||
async def test_link_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to new credentials."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
code = info["code"]
|
||||
|
||||
# Link user
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": CLIENT_ID, "code": code},
|
||||
headers={"authorization": f"Bearer {info['access_token']}"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert len(info["user"].credentials) == 1
|
||||
|
||||
|
||||
async def test_link_user_invalid_client_id(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to new credentials."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
code = info["code"]
|
||||
|
||||
# Link user
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": "invalid", "code": code},
|
||||
headers={"authorization": f"Bearer {info['access_token']}"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
assert len(info["user"].credentials) == 0
|
||||
|
||||
|
||||
async def test_link_user_invalid_code(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to new credentials."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
|
||||
# Link user
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": CLIENT_ID, "code": "invalid"},
|
||||
headers={"authorization": f"Bearer {info['access_token']}"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
assert len(info["user"].credentials) == 0
|
||||
|
||||
|
||||
async def test_link_user_invalid_auth(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to new credentials."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
code = info["code"]
|
||||
|
||||
# Link user
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": CLIENT_ID, "code": code},
|
||||
headers={"authorization": "Bearer invalid"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.UNAUTHORIZED
|
||||
assert len(info["user"].credentials) == 0
|
||||
|
||||
|
||||
async def test_link_user_already_linked_same_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to a credential it's already linked to."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
code = info["code"]
|
||||
|
||||
# Link user
|
||||
with patch.object(
|
||||
hass.auth, "async_get_user_by_credentials", return_value=info["user"]
|
||||
):
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": CLIENT_ID, "code": code},
|
||||
headers={"authorization": f"Bearer {info['access_token']}"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
# The credential was not added because it saw that it was already linked
|
||||
assert len(info["user"].credentials) == 0
|
||||
|
||||
|
||||
async def test_link_user_already_linked_other_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test linking a user to a credential already linked to other user."""
|
||||
info = await async_get_code(hass, aiohttp_client)
|
||||
client = info["client"]
|
||||
code = info["code"]
|
||||
|
||||
another_user = await hass.auth.async_create_user(name="Another")
|
||||
|
||||
# Link user
|
||||
with patch.object(
|
||||
hass.auth, "async_get_user_by_credentials", return_value=another_user
|
||||
):
|
||||
resp = await client.post(
|
||||
"/auth/link_user",
|
||||
json={"client_id": CLIENT_ID, "code": code},
|
||||
headers={"authorization": f"Bearer {info['access_token']}"},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
# The credential was not added because it saw that it was already linked
|
||||
assert len(info["user"].credentials) == 0
|
||||
assert len(another_user.credentials) == 0
|
||||
389
home-assistant/tests/components/auth/test_login_flow.py
Normal file
389
home-assistant/tests/components/auth/test_login_flow.py
Normal file
@@ -0,0 +1,389 @@
|
||||
"""Tests for the login flow."""
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import BASE_CONFIG, async_setup_auth
|
||||
|
||||
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
_TRUSTED_NETWORKS_CONFIG = {
|
||||
"type": "trusted_networks",
|
||||
"trusted_networks": ["192.168.0.1"],
|
||||
"trusted_users": {
|
||||
"192.168.0.1": [
|
||||
"a1ab982744b64757bf80515589258924",
|
||||
{"group": "system-group"},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("ip", "preselect_remember_me"),
|
||||
[
|
||||
("192.168.1.10", True),
|
||||
("::ffff:192.168.0.10", True),
|
||||
("1.2.3.4", False),
|
||||
("2001:db8::1", False),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("provider_configs", "expected"),
|
||||
[
|
||||
(
|
||||
BASE_CONFIG,
|
||||
[{"name": "Example", "type": "insecure_example", "id": None}],
|
||||
),
|
||||
(
|
||||
[{"type": "homeassistant"}],
|
||||
[
|
||||
{
|
||||
"name": "Home Assistant Local",
|
||||
"type": "homeassistant",
|
||||
"id": None,
|
||||
}
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_fetch_auth_providers(
|
||||
hass: HomeAssistant,
|
||||
aiohttp_client: ClientSessionGenerator,
|
||||
provider_configs: list[dict[str, Any]],
|
||||
expected: list[dict[str, Any]],
|
||||
ip: str,
|
||||
preselect_remember_me: bool,
|
||||
) -> None:
|
||||
"""Test fetching auth providers."""
|
||||
client = await async_setup_auth(
|
||||
hass, aiohttp_client, provider_configs, custom_ip=ip
|
||||
)
|
||||
resp = await client.get("/auth/providers")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert await resp.json() == {
|
||||
"providers": expected,
|
||||
"preselect_remember_me": preselect_remember_me,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("ip", "expected"),
|
||||
[
|
||||
(
|
||||
"192.168.0.1",
|
||||
[{"name": "Trusted Networks", "type": "trusted_networks", "id": None}],
|
||||
),
|
||||
("::ffff:192.168.0.10", []),
|
||||
("1.2.3.4", []),
|
||||
("2001:db8::1", []),
|
||||
],
|
||||
)
|
||||
async def test_fetch_auth_providers_trusted_network(
|
||||
hass: HomeAssistant,
|
||||
aiohttp_client: ClientSessionGenerator,
|
||||
expected: list[dict[str, Any]],
|
||||
ip: str,
|
||||
) -> None:
|
||||
"""Test fetching auth providers."""
|
||||
client = await async_setup_auth(
|
||||
hass, aiohttp_client, [_TRUSTED_NETWORKS_CONFIG], custom_ip=ip
|
||||
)
|
||||
resp = await client.get("/auth/providers")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert (await resp.json())["providers"] == expected
|
||||
|
||||
|
||||
async def test_fetch_auth_providers_onboarding(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test fetching auth providers."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
with patch(
|
||||
"homeassistant.components.onboarding.async_is_user_onboarded",
|
||||
return_value=False,
|
||||
):
|
||||
resp = await client.get("/auth/providers")
|
||||
assert resp.status == HTTPStatus.BAD_REQUEST
|
||||
assert await resp.json() == {
|
||||
"message": "Onboarding not finished",
|
||||
"code": "onboarding_required",
|
||||
}
|
||||
|
||||
|
||||
async def test_cannot_get_flows_in_progress(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test we cannot get flows in progress."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, [])
|
||||
resp = await client.get("/auth/login_flow")
|
||||
assert resp.status == HTTPStatus.METHOD_NOT_ALLOWED
|
||||
|
||||
|
||||
async def test_invalid_username_password(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test we cannot get flows in progress."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
# Incorrect username
|
||||
with patch(
|
||||
"homeassistant.components.auth.login_flow.process_wrong_login"
|
||||
) as mock_process_wrong_login:
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "wrong-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
assert len(mock_process_wrong_login.mock_calls) == 1
|
||||
|
||||
assert step["step_id"] == "init"
|
||||
assert step["errors"]["base"] == "invalid_auth"
|
||||
|
||||
# Incorrect password
|
||||
with patch(
|
||||
"homeassistant.components.auth.login_flow.process_wrong_login"
|
||||
) as mock_process_wrong_login:
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "wrong-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
assert len(mock_process_wrong_login.mock_calls) == 1
|
||||
|
||||
assert step["step_id"] == "init"
|
||||
assert step["errors"]["base"] == "invalid_auth"
|
||||
|
||||
# Incorrect username and invalid redirect URI fails on wrong login
|
||||
with patch(
|
||||
"homeassistant.components.auth.login_flow.process_wrong_login"
|
||||
) as mock_process_wrong_login:
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "wrong-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
assert len(mock_process_wrong_login.mock_calls) == 1
|
||||
|
||||
assert step["step_id"] == "init"
|
||||
assert step["errors"]["base"] == "invalid_auth"
|
||||
|
||||
|
||||
async def test_invalid_redirect_uri(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test invalid redirect URI."""
|
||||
client = await async_setup_auth(hass, aiohttp_client)
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": "https://some-other-domain.com",
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.auth.indieauth.fetch_redirect_uris",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.http.ban.process_wrong_login"
|
||||
) as mock_process_wrong_login,
|
||||
):
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
data = await resp.json()
|
||||
assert len(mock_process_wrong_login.mock_calls) == 1
|
||||
|
||||
assert data["message"] == "Invalid redirect URI"
|
||||
|
||||
|
||||
async def test_login_exist_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in with exist user."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
|
||||
{"username": "test-user"}
|
||||
)
|
||||
await hass.auth.async_get_or_create_user(cred)
|
||||
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.auth.login_flow.process_success_login"
|
||||
) as mock_process_success_login:
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
assert step["type"] == "create_entry"
|
||||
assert len(step["result"]) > 1
|
||||
assert len(mock_process_success_login.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_login_local_only_user(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in with local only user."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
|
||||
{"username": "test-user"}
|
||||
)
|
||||
user = await hass.auth.async_get_or_create_user(cred)
|
||||
await hass.auth.async_update_user(user, local_only=True)
|
||||
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
step = await resp.json()
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.auth.login_flow.async_user_not_allowed_do_auth",
|
||||
return_value="User is local only",
|
||||
) as mock_not_allowed_do_auth:
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
assert len(mock_not_allowed_do_auth.mock_calls) == 1
|
||||
assert await resp.json() == {"message": "Login blocked: User is local only"}
|
||||
|
||||
|
||||
async def test_login_exist_user_ip_changes(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in and the ip address changes results in an rejection."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
|
||||
{"username": "test-user"}
|
||||
)
|
||||
await hass.auth.async_get_or_create_user(cred)
|
||||
|
||||
resp = await client.post(
|
||||
"/auth/login_flow",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"handler": ["insecure_example", None],
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
},
|
||||
)
|
||||
assert resp.status == 200
|
||||
step = await resp.json()
|
||||
|
||||
#
|
||||
# Here we modify the ip_address in the context to make sure
|
||||
# when ip address changes in the middle of the login flow we prevent logins.
|
||||
#
|
||||
# This method was chosen because it seemed less likely to break
|
||||
# vs patching aiohttp internals to fake the ip address
|
||||
#
|
||||
for flow_id, flow in hass.auth.login_flow._progress.items():
|
||||
assert flow_id == step["flow_id"]
|
||||
flow.context["ip_address"] = "10.2.3.1"
|
||||
|
||||
resp = await client.post(
|
||||
f"/auth/login_flow/{step['flow_id']}",
|
||||
json={
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": CLIENT_REDIRECT_URI,
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
response = await resp.json()
|
||||
assert response == {"message": "IP address changed"}
|
||||
|
||||
|
||||
async def test_well_known_auth_info(
|
||||
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test logging in and the ip address changes results in an rejection."""
|
||||
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
|
||||
resp = await client.get(
|
||||
"/.well-known/oauth-authorization-server",
|
||||
)
|
||||
assert resp.status == 200
|
||||
assert await resp.json() == {
|
||||
"authorization_endpoint": "/auth/authorize",
|
||||
"token_endpoint": "/auth/token",
|
||||
"revocation_endpoint": "/auth/revoke",
|
||||
"response_types_supported": ["code"],
|
||||
"service_documentation": "https://developers.home-assistant.io/docs/auth_api",
|
||||
}
|
||||
127
home-assistant/tests/components/auth/test_mfa_setup_flow.py
Normal file
127
home-assistant/tests/components/auth/test_mfa_setup_flow.py
Normal file
@@ -0,0 +1,127 @@
|
||||
"""Tests for the mfa setup flow."""
|
||||
|
||||
from homeassistant.auth import auth_manager_from_config
|
||||
from homeassistant.components.auth import mfa_setup_flow
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded
|
||||
from tests.typing import WebSocketGenerator
|
||||
|
||||
|
||||
async def test_ws_setup_depose_mfa(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
|
||||
) -> None:
|
||||
"""Test set up mfa module for current user."""
|
||||
hass.auth = await auth_manager_from_config(
|
||||
hass,
|
||||
provider_configs=[
|
||||
{
|
||||
"type": "insecure_example",
|
||||
"users": [
|
||||
{
|
||||
"username": "test-user",
|
||||
"password": "test-pass",
|
||||
"name": "Test Name",
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
module_configs=[
|
||||
{
|
||||
"type": "insecure_example",
|
||||
"id": "example_module",
|
||||
"data": [{"user_id": "mock-user", "pin": "123456"}],
|
||||
}
|
||||
],
|
||||
)
|
||||
ensure_auth_manager_loaded(hass.auth)
|
||||
await async_setup_component(hass, "auth", {"http": {}})
|
||||
|
||||
user = MockUser(id="mock-user").add_to_hass(hass)
|
||||
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
|
||||
{"username": "test-user"}
|
||||
)
|
||||
await hass.auth.async_link_user(user, cred)
|
||||
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
|
||||
access_token = hass.auth.async_create_access_token(refresh_token)
|
||||
|
||||
client = await hass_ws_client(hass, access_token)
|
||||
|
||||
await client.send_json(
|
||||
{
|
||||
"id": 10,
|
||||
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
|
||||
"mfa_module_id": "invalid_module",
|
||||
}
|
||||
)
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["id"] == 10
|
||||
assert result["success"] is False
|
||||
assert result["error"]["code"] == "no_module"
|
||||
|
||||
await client.send_json(
|
||||
{
|
||||
"id": 11,
|
||||
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
|
||||
"mfa_module_id": "example_module",
|
||||
}
|
||||
)
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["id"] == 11
|
||||
assert result["success"]
|
||||
|
||||
flow = result["result"]
|
||||
# Cannot use identity `is` check here as the value is parsed from JSON
|
||||
assert flow["type"] == FlowResultType.FORM.value
|
||||
assert flow["handler"] == "example_module"
|
||||
assert flow["step_id"] == "init"
|
||||
assert flow["data_schema"][0] == {"type": "string", "name": "pin", "required": True}
|
||||
|
||||
await client.send_json(
|
||||
{
|
||||
"id": 12,
|
||||
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
|
||||
"flow_id": flow["flow_id"],
|
||||
"user_input": {"pin": "654321"},
|
||||
}
|
||||
)
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["id"] == 12
|
||||
assert result["success"]
|
||||
|
||||
flow = result["result"]
|
||||
# Cannot use identity `is` check here as the value is parsed from JSON
|
||||
assert flow["type"] == FlowResultType.CREATE_ENTRY.value
|
||||
assert flow["handler"] == "example_module"
|
||||
assert flow["data"]["result"] is None
|
||||
|
||||
await client.send_json(
|
||||
{
|
||||
"id": 13,
|
||||
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
|
||||
"mfa_module_id": "invalid_id",
|
||||
}
|
||||
)
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["id"] == 13
|
||||
assert result["success"] is False
|
||||
assert result["error"]["code"] == "disable_failed"
|
||||
|
||||
await client.send_json(
|
||||
{
|
||||
"id": 14,
|
||||
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
|
||||
"mfa_module_id": "example_module",
|
||||
}
|
||||
)
|
||||
|
||||
result = await client.receive_json()
|
||||
assert result["id"] == 14
|
||||
assert result["success"]
|
||||
assert result["result"] == "done"
|
||||
Reference in New Issue
Block a user