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,4 @@
"""Tests for the HTTP component."""
# Relic from the past. Kept here so we can run negative tests.
HTTP_HEADER_HA_AUTH = "X-HA-access"

View File

@@ -0,0 +1,17 @@
"""Test configuration for http."""
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

View File

@@ -0,0 +1,655 @@
"""The tests for the Home Assistant HTTP component."""
from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_network
import logging
from typing import Any
from unittest.mock import Mock, patch
from aiohttp import BasicAuth, web
from aiohttp.web_exceptions import HTTPUnauthorized
import jwt
import pytest
import yarl
from homeassistant.auth.const import GROUP_ID_READ_ONLY
from homeassistant.auth.models import User
from homeassistant.auth.providers import trusted_networks
from homeassistant.auth.providers.homeassistant import HassAuthProvider
from homeassistant.components import websocket_api
from homeassistant.components.http import KEY_HASS
from homeassistant.components.http.auth import (
CONTENT_USER_NAME,
DATA_SIGN_SECRET,
SIGN_QUERY_PARAM,
STORAGE_KEY,
async_setup_auth,
async_sign_path,
async_user_not_allowed_do_auth,
)
from homeassistant.components.http.const import KEY_AUTHENTICATED
from homeassistant.components.http.forwarded import async_setup_forwarded
from homeassistant.components.http.request_context import (
current_request,
setup_request_context,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.setup import async_setup_component
from . import HTTP_HEADER_HA_AUTH
from tests.common import MockUser
from tests.test_util import mock_real_ip
from tests.typing import ClientSessionGenerator, WebSocketGenerator
_LOGGER = logging.getLogger(__name__)
API_PASSWORD = "test-password"
# Don't add 127.0.0.1/::1 as trusted, as it may interfere with other test cases
TRUSTED_NETWORKS = [
ip_network("192.0.2.0/24"),
ip_network("2001:DB8:ABCD::/48"),
ip_network("100.64.0.1"),
ip_network("FD01:DB8::1"),
]
TRUSTED_ADDRESSES = ["100.64.0.1", "192.0.2.100", "FD01:DB8::1", "2001:DB8:ABCD::1"]
EXTERNAL_ADDRESSES = ["198.51.100.1", "2001:DB8:FA1::1"]
LOCALHOST_ADDRESSES = ["127.0.0.1", "::1"]
UNTRUSTED_ADDRESSES = [*EXTERNAL_ADDRESSES, *LOCALHOST_ADDRESSES]
PRIVATE_ADDRESSES = [
"192.168.10.10",
"172.16.4.20",
"10.100.50.5",
]
async def mock_handler(request: web.Request) -> web.Response:
"""Return if request was authenticated."""
if not request[KEY_AUTHENTICATED]:
raise HTTPUnauthorized
user = request.get("hass_user")
user_id = user.id if user else None
return web.json_response(data={"user_id": user_id})
@pytest.fixture
def app(hass: HomeAssistant) -> web.Application:
"""Fixture to set up a web.Application."""
app = web.Application()
app[KEY_HASS] = hass
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [])
return app
@pytest.fixture
def app2(hass: HomeAssistant) -> web.Application:
"""Fixture to set up a web.Application without real_ip middleware."""
app = web.Application()
app[KEY_HASS] = hass
app.router.add_get("/", mock_handler)
return app
@pytest.fixture
def trusted_networks_auth(
hass: HomeAssistant,
) -> trusted_networks.TrustedNetworksAuthProvider:
"""Load trusted networks auth provider."""
prv = trusted_networks.TrustedNetworksAuthProvider(
hass,
hass.auth._store,
{"type": "trusted_networks", "trusted_networks": TRUSTED_NETWORKS},
)
hass.auth._providers[(prv.type, prv.id)] = prv
return prv
async def test_auth_middleware_loaded_by_default(hass: HomeAssistant) -> None:
"""Test accessing to server from banned IP when feature is off."""
with patch("homeassistant.components.http.async_setup_auth") as mock_setup:
await async_setup_component(hass, "http", {"http": {}})
assert len(mock_setup.mock_calls) == 1
async def test_cant_access_with_password_in_header(
app: web.Application,
aiohttp_client: ClientSessionGenerator,
local_auth: HassAuthProvider,
hass: HomeAssistant,
) -> None:
"""Test access with password in header."""
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: "wrong-pass"})
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_cant_access_with_password_in_query(
app: web.Application,
aiohttp_client: ClientSessionGenerator,
local_auth: HassAuthProvider,
hass: HomeAssistant,
) -> None:
"""Test access with password in URL."""
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/")
assert resp.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/", params={"api_password": "wrong-password"})
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_basic_auth_does_not_work(
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass: HomeAssistant,
local_auth: HassAuthProvider,
) -> None:
"""Test access with basic authentication."""
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("wrong_username", API_PASSWORD))
assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("homeassistant", "wrong password"))
assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={"authorization": "NotBasic abcdefg"})
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_cannot_access_with_trusted_ip(
hass: HomeAssistant,
app2: web.Application,
trusted_networks_auth: trusted_networks.TrustedNetworksAuthProvider,
aiohttp_client: ClientSessionGenerator,
hass_owner_user: MockUser,
) -> None:
"""Test access with an untrusted ip address."""
await async_setup_auth(hass, app2)
set_mock_ip = mock_real_ip(app2)
client = await aiohttp_client(app2)
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
async def test_auth_active_access_with_access_token_in_header(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with access token in header."""
token = hass_access_token
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"AUTHORIZATION": f"Bearer {token}"})
assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"authorization": f"Bearer {token}"})
assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"Authorization": token})
assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={"Authorization": f"BEARER {token}"})
assert req.status == HTTPStatus.UNAUTHORIZED
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
refresh_token.user.is_active = False
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_active_access_with_trusted_ip(
hass: HomeAssistant,
app2: web.Application,
trusted_networks_auth: trusted_networks.TrustedNetworksAuthProvider,
aiohttp_client: ClientSessionGenerator,
hass_owner_user: MockUser,
) -> None:
"""Test access with an untrusted ip address."""
await async_setup_auth(hass, app2)
set_mock_ip = mock_real_ip(app2)
client = await aiohttp_client(app2)
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
async def test_auth_legacy_support_api_password_cannot_access(
app: web.Application,
aiohttp_client: ClientSessionGenerator,
local_auth: HassAuthProvider,
hass: HomeAssistant,
) -> None:
"""Test access using api_password if auth.support_legacy."""
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path_with_refresh_token(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with signed url."""
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass, "/", timedelta(seconds=5), refresh_token_id=refresh_token.id
)
req = await client.get(signed_path)
assert req.status == HTTPStatus.OK
data = await req.json()
assert data["user_id"] == refresh_token.user.id
# Use signature on other path
req = await client.get(f"/another_path?{signed_path.split('?')[1]}")
assert req.status == HTTPStatus.UNAUTHORIZED
# We only allow GET
req = await client.post(signed_path)
assert req.status == HTTPStatus.UNAUTHORIZED
# Never valid as expired in the past.
expired_signed_path = async_sign_path(
hass, "/", timedelta(seconds=-5), refresh_token_id=refresh_token.id
)
req = await client.get(expired_signed_path)
assert req.status == HTTPStatus.UNAUTHORIZED
# refresh token gone should also invalidate signature
hass.auth.async_remove_refresh_token(refresh_token)
req = await client.get(signed_path)
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path_with_query_param(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with signed url and query params."""
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass, "/?test=test", timedelta(seconds=5), refresh_token_id=refresh_token.id
)
req = await client.get(signed_path)
assert req.status == HTTPStatus.OK
data = await req.json()
assert data["user_id"] == refresh_token.user.id
# Without query params not allowed
url = yarl.URL(signed_path)
signed_path = f"{url.path}?{SIGN_QUERY_PARAM}={url.query.get(SIGN_QUERY_PARAM)}"
req = await client.get(signed_path)
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path_with_query_param_order(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with signed url and query params different order."""
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass,
"/?test=test&foo=bar",
timedelta(seconds=5),
refresh_token_id=refresh_token.id,
)
url = yarl.URL(signed_path)
# Change order
req = await client.get(
f"{url.path}?{SIGN_QUERY_PARAM}={url.query.get(SIGN_QUERY_PARAM)}&foo=bar&test=test"
)
assert req.status == HTTPStatus.UNAUTHORIZED
# Duplicate a param
req = await client.get(
f"{url.path}?{SIGN_QUERY_PARAM}={url.query.get(SIGN_QUERY_PARAM)}&test=test&foo=aaa&foo=bar"
)
assert req.status == HTTPStatus.UNAUTHORIZED
# Remove a param
req = await client.get(
f"{url.path}?{SIGN_QUERY_PARAM}={url.query.get(SIGN_QUERY_PARAM)}&test=test"
)
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path_with_query_param_safe_param(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with signed url and changing a safe param."""
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass,
"/?test=test&foo=bar",
timedelta(seconds=5),
refresh_token_id=refresh_token.id,
)
signed_path = f"{signed_path}&width=100"
req = await client.get(signed_path)
assert req.status == HTTPStatus.OK
data = await req.json()
assert data["user_id"] == refresh_token.user.id
@pytest.mark.parametrize(
("base_url", "test_url"),
[
("/?test=test", "/?test=test&foo=bar"),
("/", "/?test=test"),
("/?test=test&foo=bar", "/?test=test&foo=baz"),
("/?test=test&foo=bar", "/?test=test"),
],
)
async def test_auth_access_signed_path_with_query_param_tamper(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
base_url: str,
test_url: str,
) -> None:
"""Test access with signed url and query params that have been tampered with."""
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass, base_url, timedelta(seconds=5), refresh_token_id=refresh_token.id
)
url = yarl.URL(signed_path)
token = url.query.get(SIGN_QUERY_PARAM)
req = await client.get(f"{test_url}&{SIGN_QUERY_PARAM}={token}")
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path_via_websocket(
hass: HomeAssistant,
app: web.Application,
hass_ws_client: WebSocketGenerator,
hass_read_only_access_token: str,
) -> None:
"""Test signed url via websockets uses connection user."""
@websocket_api.websocket_command({"type": "diagnostics/list"})
@callback
def get_signed_path(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
connection.send_result(
msg["id"], {"path": async_sign_path(hass, "/", timedelta(seconds=5))}
)
websocket_api.async_register_command(hass, get_signed_path)
# We use hass_read_only_access_token to make sure the connection WS is used.
client = await hass_ws_client(access_token=hass_read_only_access_token)
await client.send_json({"id": 5, "type": "diagnostics/list"})
msg = await client.receive_json()
assert msg["id"] == 5
assert msg["success"]
refresh_token = hass.auth.async_validate_access_token(hass_read_only_access_token)
signature = yarl.URL(msg["result"]["path"]).query["authSig"]
claims = jwt.decode(
signature,
hass.data[DATA_SIGN_SECRET],
algorithms=["HS256"],
options={"verify_signature": False},
)
assert claims["iss"] == refresh_token.id
async def test_auth_access_signed_path_with_http(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test signed url via HTTP uses HTTP user."""
setup_request_context(app, current_request)
async def mock_handler(request):
"""Return signed path."""
return web.json_response(
data={"path": async_sign_path(hass, "/", timedelta(seconds=-5))}
)
app.router.add_get("/hello", mock_handler)
await async_setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
req = await client.get(
"/hello", headers={"Authorization": f"Bearer {hass_access_token}"}
)
assert req.status == HTTPStatus.OK
data = await req.json()
signature = yarl.URL(data["path"]).query["authSig"]
claims = jwt.decode(
signature,
hass.data[DATA_SIGN_SECRET],
algorithms=["HS256"],
options={"verify_signature": False},
)
assert claims["iss"] == refresh_token.id
async def test_auth_access_signed_path_with_content_user(
hass: HomeAssistant, app: web.Application, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test access signed url uses content user."""
await async_setup_auth(hass, app)
signed_path = async_sign_path(hass, "/", timedelta(seconds=5))
signature = yarl.URL(signed_path).query["authSig"]
claims = jwt.decode(
signature,
hass.data[DATA_SIGN_SECRET],
algorithms=["HS256"],
options={"verify_signature": False},
)
assert claims["iss"] == hass.data[STORAGE_KEY]
async def test_local_only_user_rejected(
hass: HomeAssistant,
app: web.Application,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test access with access token in header."""
token = hass_access_token
await async_setup_auth(hass, app)
set_mock_ip = mock_real_ip(app)
client = await aiohttp_client(app)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id}
refresh_token.user.local_only = True
for remote_addr in EXTERNAL_ADDRESSES:
set_mock_ip(remote_addr)
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == HTTPStatus.UNAUTHORIZED
async def test_async_user_not_allowed_do_auth(
hass: HomeAssistant, app: web.Application
) -> None:
"""Test for not allowing auth."""
user = await hass.auth.async_create_user("Hello")
user.is_active = False
# User not active
assert async_user_not_allowed_do_auth(hass, user) == "User is not active"
user.is_active = True
user.local_only = True
# No current request
assert (
async_user_not_allowed_do_auth(hass, user)
== "No request available to validate local access"
)
trusted_request = Mock(remote="192.168.1.123")
untrusted_request = Mock(remote=UNTRUSTED_ADDRESSES[0])
# Is Remote IP and local only (cloud not loaded)
assert async_user_not_allowed_do_auth(hass, user, trusted_request) is None
assert (
async_user_not_allowed_do_auth(hass, user, untrusted_request)
== "User cannot authenticate remotely"
)
# Mimic cloud loaded and validate local IP again
hass.config.components.add("cloud")
assert async_user_not_allowed_do_auth(hass, user, trusted_request) is None
assert (
async_user_not_allowed_do_auth(hass, user, untrusted_request)
== "User cannot authenticate remotely"
)
# Is Cloud request and local only, even a local IP will fail
with patch(
"hass_nabucasa.remote.is_cloud_request", Mock(get=Mock(return_value=True))
):
assert (
async_user_not_allowed_do_auth(hass, user, trusted_request)
== "User is local only"
)
async def test_create_user_once(hass: HomeAssistant) -> None:
"""Test that we reuse the user."""
cur_users = len(await hass.auth.async_get_users())
app = web.Application()
await async_setup_auth(hass, app)
users = await hass.auth.async_get_users()
assert len(users) == cur_users + 1
user: User = next((user for user in users if user.name == CONTENT_USER_NAME), None)
assert user is not None, users
assert len(user.groups) == 1
assert user.groups[0].id == GROUP_ID_READ_ONLY
assert len(user.refresh_tokens) == 1
assert user.system_generated
await async_setup_auth(hass, app)
# test it did not create a user
assert len(await hass.auth.async_get_users()) == cur_users + 1

View File

@@ -0,0 +1,412 @@
"""The tests for the Home Assistant HTTP component."""
from http import HTTPStatus
from ipaddress import ip_address
import os
from unittest.mock import AsyncMock, Mock, mock_open, patch
from aiohttp import web
from aiohttp.web_exceptions import HTTPUnauthorized
from aiohttp.web_middlewares import middleware
import pytest
from homeassistant.components import http
from homeassistant.components.http import KEY_AUTHENTICATED, KEY_HASS
from homeassistant.components.http.ban import (
IP_BANS_FILE,
KEY_BAN_MANAGER,
KEY_FAILED_LOGIN_ATTEMPTS,
process_success_login,
setup_bans,
)
from homeassistant.components.http.view import request_handler_factory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component
from tests.common import async_get_persistent_notifications
from tests.test_util import mock_real_ip
from tests.typing import ClientSessionGenerator
SUPERVISOR_IP = "1.2.3.4"
BANNED_IPS = ["200.201.202.203", "100.64.0.2"]
BANNED_IPS_WITH_SUPERVISOR = [*BANNED_IPS, SUPERVISOR_IP]
@pytest.fixture(name="hassio_env")
def hassio_env_fixture(supervisor_is_connected: AsyncMock):
"""Fixture to inject hassio env."""
with (
patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}),
patch.dict(os.environ, {"SUPERVISOR_TOKEN": "123456"}),
):
yield
@pytest.fixture(autouse=True)
def gethostbyaddr_mock():
"""Fixture to mock out I/O on getting host by address."""
with patch(
"homeassistant.components.http.ban.gethostbyaddr",
return_value=("example.com", ["0.0.0.0.in-addr.arpa"], ["0.0.0.0"]),
):
yield
async def test_access_from_banned_ip(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test accessing to server from banned IP. Both trusted and not."""
app = web.Application()
app[KEY_HASS] = hass
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
return_value={
banned_ip: {"banned_at": "2016-11-16T19:20:03"} for banned_ip in BANNED_IPS
},
):
client = await aiohttp_client(app)
for remote_addr in BANNED_IPS:
set_real_ip(remote_addr)
resp = await client.get("/")
assert resp.status == HTTPStatus.FORBIDDEN
async def test_access_from_banned_ip_with_partially_broken_yaml_file(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test accessing to server from banned IP. Both trusted and not.
We inject some garbage into the yaml file to make sure it can
still load the bans.
"""
app = web.Application()
app[KEY_HASS] = hass
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
data = {banned_ip: {"banned_at": "2016-11-16T19:20:03"} for banned_ip in BANNED_IPS}
data["5.3.3.3"] = {"banned_at": "garbage"}
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
return_value=data,
):
client = await aiohttp_client(app)
for remote_addr in BANNED_IPS:
set_real_ip(remote_addr)
resp = await client.get("/")
assert resp.status == HTTPStatus.FORBIDDEN
# Ensure garbage data is ignored
set_real_ip("5.3.3.3")
resp = await client.get("/")
assert resp.status == HTTPStatus.NOT_FOUND
assert "Failed to load IP ban" in caplog.text
async def test_no_ip_bans_file(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test no ip bans file."""
app = web.Application()
app[KEY_HASS] = hass
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
side_effect=FileNotFoundError,
):
client = await aiohttp_client(app)
set_real_ip("4.3.2.1")
resp = await client.get("/")
assert resp.status == HTTPStatus.NOT_FOUND
async def test_failure_loading_ip_bans_file(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test failure loading ip bans file."""
app = web.Application()
app[KEY_HASS] = hass
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
side_effect=HomeAssistantError,
):
client = await aiohttp_client(app)
set_real_ip("4.3.2.1")
resp = await client.get("/")
assert resp.status == HTTPStatus.NOT_FOUND
async def test_ip_ban_manager_never_started(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test we handle the ip ban manager not being started."""
app = web.Application()
app[KEY_HASS] = hass
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
side_effect=FileNotFoundError,
):
client = await aiohttp_client(app)
# Mock the manager never being started
del app[KEY_BAN_MANAGER]
set_real_ip("4.3.2.1")
resp = await client.get("/")
assert resp.status == HTTPStatus.NOT_FOUND
assert "IP Ban middleware loaded but banned IPs not loaded" in caplog.text
@pytest.mark.parametrize(
("remote_addr", "bans", "status"),
list(
zip(
BANNED_IPS_WITH_SUPERVISOR,
[1, 1, 0],
[HTTPStatus.FORBIDDEN, HTTPStatus.FORBIDDEN, HTTPStatus.UNAUTHORIZED],
strict=False,
)
),
)
async def test_access_from_supervisor_ip(
remote_addr,
bans,
status,
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
hassio_env,
resolution_info: AsyncMock,
) -> None:
"""Test accessing to server from supervisor IP."""
app = web.Application()
app[KEY_HASS] = hass
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
app.router.add_get("/", unauth_handler)
setup_bans(hass, app, 1)
mock_real_ip(app)(remote_addr)
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
return_value={},
):
client = await aiohttp_client(app)
manager = app[KEY_BAN_MANAGER]
assert await async_setup_component(hass, "hassio", {"hassio": {}})
m_open = mock_open()
with (
patch.dict(os.environ, {"SUPERVISOR": SUPERVISOR_IP}),
patch("homeassistant.components.http.ban.open", m_open, create=True),
):
resp = await client.get("/")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(manager.ip_bans_lookup) == bans
assert m_open.call_count == bans
# second request should be forbidden if banned
resp = await client.get("/")
assert resp.status == status
assert len(manager.ip_bans_lookup) == bans
async def test_ban_middleware_not_loaded_by_config(hass: HomeAssistant) -> None:
"""Test accessing to server from banned IP when feature is off."""
with patch("homeassistant.components.http.setup_bans") as mock_setup:
await async_setup_component(
hass, "http", {"http": {http.CONF_IP_BAN_ENABLED: False}}
)
assert len(mock_setup.mock_calls) == 0
async def test_ban_middleware_loaded_by_default(hass: HomeAssistant) -> None:
"""Test accessing to server from banned IP when feature is off."""
with patch("homeassistant.components.http.setup_bans") as mock_setup:
await async_setup_component(hass, "http", {"http": {}})
assert len(mock_setup.mock_calls) == 1
async def test_ip_bans_file_creation(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Testing if banned IP file created."""
app = web.Application()
app[KEY_HASS] = hass
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
app.router.add_get("/example", unauth_handler)
setup_bans(hass, app, 2)
mock_real_ip(app)("200.201.202.204")
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
return_value={
banned_ip: {"banned_at": "2016-11-16T19:20:03"} for banned_ip in BANNED_IPS
},
):
client = await aiohttp_client(app)
manager = app[KEY_BAN_MANAGER]
m_open = mock_open()
with patch("homeassistant.components.http.ban.open", m_open, create=True):
resp = await client.get("/example")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(manager.ip_bans_lookup) == len(BANNED_IPS)
assert m_open.call_count == 0
resp = await client.get("/example")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(manager.ip_bans_lookup) == len(BANNED_IPS) + 1
m_open.assert_called_once_with(
hass.config.path(IP_BANS_FILE), "a", encoding="utf8"
)
resp = await client.get("/example")
assert resp.status == HTTPStatus.FORBIDDEN
assert m_open.call_count == 1
notifications = async_get_persistent_notifications(hass)
assert len(notifications) == 2
assert (
notifications["http-login"]["message"]
== "Login attempt or request with invalid authentication from example.com (200.201.202.204). See the log for details."
)
assert (
"Login attempt or request with invalid authentication from example.com (200.201.202.204). Requested URL: '/example'."
in caplog.text
)
async def test_failed_login_attempts_counter(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None:
"""Testing if failed login attempts counter increased."""
app = web.Application()
app[KEY_HASS] = hass
async def auth_handler(request):
"""Return 200 status code."""
return None, 200
async def auth_true_handler(request):
"""Return 200 status code."""
process_success_login(request)
return None, 200
app.router.add_get(
"/auth_true",
request_handler_factory(hass, Mock(requires_auth=True), auth_true_handler),
)
app.router.add_get(
"/auth_false",
request_handler_factory(hass, Mock(requires_auth=True), auth_handler),
)
app.router.add_get(
"/", request_handler_factory(hass, Mock(requires_auth=False), auth_handler)
)
setup_bans(hass, app, 5)
remote_ip = ip_address("200.201.202.204")
mock_real_ip(app)("200.201.202.204")
@middleware
async def mock_auth(request, handler):
"""Mock auth middleware."""
if "auth_true" in request.path:
request[KEY_AUTHENTICATED] = True
else:
request[KEY_AUTHENTICATED] = False
return await handler(request)
app.middlewares.append(mock_auth)
client = await aiohttp_client(app)
resp = await client.get("/auth_false")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1
resp = await client.get("/auth_false")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
resp = await client.get("/")
assert resp.status == HTTPStatus.OK
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
# This used to check that with trusted networks we reset login attempts
# We no longer support trusted networks.
resp = await client.get("/auth_true")
assert resp.status == HTTPStatus.OK
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 0
resp = await client.get("/auth_false")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1
resp = await client.get("/auth_false")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
async def test_single_ban_file_entry(
hass: HomeAssistant,
) -> None:
"""Test that only one item is added to ban file."""
app = web.Application()
app[KEY_HASS] = hass
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
app.router.add_get("/example", unauth_handler)
setup_bans(hass, app, 2)
mock_real_ip(app)("200.201.202.204")
manager = app[KEY_BAN_MANAGER]
m_open = mock_open()
with patch("homeassistant.components.http.ban.open", m_open, create=True):
remote_ip = ip_address("200.201.202.204")
await manager.async_add_ban(remote_ip)
await manager.async_add_ban(remote_ip)
assert m_open.call_count == 1

View File

@@ -0,0 +1,175 @@
"""Test cors for the HTTP component."""
from asyncio import AbstractEventLoop
from http import HTTPStatus
from pathlib import Path
from unittest.mock import patch
from aiohttp import web
from aiohttp.hdrs import (
ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_REQUEST_HEADERS,
ACCESS_CONTROL_REQUEST_METHOD,
AUTHORIZATION,
ORIGIN,
)
from aiohttp.test_utils import TestClient
import pytest
from homeassistant.components.http.cors import setup_cors
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import HomeAssistant
from homeassistant.helpers.http import KEY_ALLOW_CONFIGURED_CORS
from homeassistant.setup import async_setup_component
from . import HTTP_HEADER_HA_AUTH
from tests.typing import ClientSessionGenerator
TRUSTED_ORIGIN = "https://home-assistant.io"
async def test_cors_middleware_loaded_by_default(hass: HomeAssistant) -> None:
"""Test accessing to server from banned IP when feature is off."""
with patch("homeassistant.components.http.setup_cors") as mock_setup:
await async_setup_component(hass, "http", {"http": {}})
assert len(mock_setup.mock_calls) == 1
async def test_cors_middleware_loaded_from_config(hass: HomeAssistant) -> None:
"""Test accessing to server from banned IP when feature is off."""
with patch("homeassistant.components.http.setup_cors") as mock_setup:
await async_setup_component(
hass,
"http",
{"http": {"cors_allowed_origins": ["http://home-assistant.io"]}},
)
assert len(mock_setup.mock_calls) == 1
async def mock_handler(request):
"""Return if request was authenticated."""
return web.Response()
@pytest.fixture
def client(
event_loop: AbstractEventLoop, aiohttp_client: ClientSessionGenerator
) -> TestClient:
"""Fixture to set up a web.Application."""
app = web.Application()
setup_cors(app, [TRUSTED_ORIGIN])
app[KEY_ALLOW_CONFIGURED_CORS](app.router.add_get("/", mock_handler))
return event_loop.run_until_complete(aiohttp_client(app))
async def test_cors_requests(client) -> None:
"""Test cross origin requests."""
req = await client.get("/", headers={ORIGIN: TRUSTED_ORIGIN})
assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in URL
req = await client.get(
"/", params={"api_password": "some-pass"}, headers={ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in headers
req = await client.get(
"/", headers={HTTP_HEADER_HA_AUTH: "some-pass", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With auth token in headers
req = await client.get(
"/", headers={AUTHORIZATION: "Bearer some-token", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
async def test_cors_preflight_allowed(client) -> None:
"""Test cross origin resource sharing preflight (OPTIONS) request."""
req = await client.options(
"/",
headers={
ORIGIN: TRUSTED_ORIGIN,
ACCESS_CONTROL_REQUEST_METHOD: "GET",
ACCESS_CONTROL_REQUEST_HEADERS: "x-requested-with",
},
)
assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
assert req.headers[ACCESS_CONTROL_ALLOW_HEADERS] == "X-REQUESTED-WITH"
async def test_cors_middleware_with_cors_allowed_view(hass: HomeAssistant) -> None:
"""Test that we can configure cors and have a cors_allowed view."""
class MyView(HomeAssistantView):
"""Test view that allows CORS."""
requires_auth = False
cors_allowed = True
def __init__(self, url, name) -> None:
"""Initialize test view."""
self.url = url
self.name = name
async def get(self, request):
"""Test response."""
return "test"
assert await async_setup_component(
hass, "http", {"http": {"cors_allowed_origins": ["http://home-assistant.io"]}}
)
hass.http.register_view(MyView("/api/test", "api:test"))
hass.http.register_view(MyView("/api/test", "api:test2"))
hass.http.register_view(MyView("/api/test2", "api:test"))
hass.http.app._on_startup.freeze()
await hass.http.app.startup()
async def test_cors_works_with_frontend(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test CORS works with the frontend."""
assert await async_setup_component(
hass,
"frontend",
{"http": {"cors_allowed_origins": ["http://home-assistant.io"]}},
)
client = await hass_client()
resp = await client.get("/")
assert resp.status == HTTPStatus.OK
async def test_cors_on_static_files(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test that we enable CORS for static files."""
assert await async_setup_component(
hass, "frontend", {"http": {"cors_allowed_origins": ["http://www.example.com"]}}
)
hass.http.register_static_path("/something", str(Path(__file__).parent))
client = await hass_client()
resp = await client.options(
"/something/__init__.py",
headers={
"origin": "http://www.example.com",
ACCESS_CONTROL_REQUEST_METHOD: "GET",
},
)
assert resp.status == HTTPStatus.OK
assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com"

View File

@@ -0,0 +1,75 @@
"""Test data validator decorator."""
from http import HTTPStatus
from unittest.mock import Mock
from aiohttp import web
import voluptuous as vol
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.helpers.http import KEY_ALLOW_CONFIGURED_CORS
from tests.typing import ClientSessionGenerator
async def get_client(aiohttp_client, validator):
"""Generate a client that hits a view decorated with validator."""
app = web.Application()
app[KEY_HASS] = Mock(is_stopping=False)
app[KEY_ALLOW_CONFIGURED_CORS] = lambda _: None
class TestView(HomeAssistantView):
url = "/"
name = "test"
requires_auth = False
@validator
async def post(self, request, data):
"""Test method."""
return b""
TestView().register(app[KEY_HASS], app, app.router)
return await aiohttp_client(app)
async def test_validator(aiohttp_client: ClientSessionGenerator) -> None:
"""Test the validator."""
client = await get_client(
aiohttp_client, RequestDataValidator(vol.Schema({vol.Required("test"): str}))
)
resp = await client.post("/", json={"test": "bla"})
assert resp.status == HTTPStatus.OK
resp = await client.post("/", json={"test": 100})
assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post("/")
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_validator_allow_empty(aiohttp_client: ClientSessionGenerator) -> None:
"""Test the validator with empty data."""
client = await get_client(
aiohttp_client,
RequestDataValidator(
vol.Schema(
{
# Although we allow empty, our schema should still be able
# to validate an empty dict.
vol.Optional("test"): str
}
),
allow_empty=True,
),
)
resp = await client.post("/", json={"test": "bla"})
assert resp.status == HTTPStatus.OK
resp = await client.post("/", json={"test": 100})
assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post("/")
assert resp.status == HTTPStatus.OK

View File

@@ -0,0 +1,504 @@
"""Test real forwarded middleware."""
from http import HTTPStatus
from ipaddress import ip_network
from unittest.mock import Mock, patch
from aiohttp import web
from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO
import pytest
from homeassistant.components.http.forwarded import async_setup_forwarded
from tests.typing import ClientSessionGenerator
async def mock_handler(request):
"""Return the real IP as text."""
return web.Response(text=request.remote)
async def test_x_forwarded_for_without_trusted_proxy(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we get the IP from the transport."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == HTTPStatus.BAD_REQUEST
assert (
"Received X-Forwarded-For header from an untrusted proxy 127.0.0.1"
in caplog.text
)
@pytest.mark.parametrize(
("trusted_proxies", "x_forwarded_for", "remote"),
[
(
["127.0.0.0/24", "1.1.1.1", "10.10.10.0/24"],
"10.10.10.10, 1.1.1.1",
"10.10.10.10",
),
(["127.0.0.0/24", "1.1.1.1"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "2.2.2.2"),
(["127.0.0.0/24", "1.1.1.1"], "123.123.123.123,2.2.2.2,1.1.1.1", "2.2.2.2"),
(["127.0.0.0/24"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "1.1.1.1"),
(["127.0.0.0/24"], "127.0.0.1", "127.0.0.1"),
(["127.0.0.1", "1.1.1.1"], "123.123.123.123, 1.1.1.1", "123.123.123.123"),
(["127.0.0.1", "1.1.1.1"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "2.2.2.2"),
(["127.0.0.1"], "255.255.255.255", "255.255.255.255"),
],
)
async def test_x_forwarded_for_with_trusted_proxy(
trusted_proxies, x_forwarded_for, remote, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test that we get the IP from the forwarded for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == remote
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(
app, True, [ip_network(trusted_proxy) for trusted_proxy in trusted_proxies]
)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_for_disabled_with_proxy(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we warn when processing is disabled, but proxy has been detected."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, False, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == HTTPStatus.BAD_REQUEST
assert (
"A request from a reverse proxy was received from 127.0.0.1, but your HTTP "
"integration is not set-up for reverse proxies" in caplog.text
)
async def test_x_forwarded_for_with_spoofed_header(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that we get the IP from the transport with a spoofed header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"}
)
assert resp.status == HTTPStatus.OK
@pytest.mark.parametrize(
"x_forwarded_for",
[
"This value is invalid",
"1.1.1.1, , 1.2.3.4",
"1.1.1.1,,1.2.3.4",
"1.1.1.1, batman, 1.2.3.4",
"192.168.0.0/24",
"192.168.0.0/24, 1.1.1.1",
",",
"",
],
)
async def test_x_forwarded_for_with_malformed_header(
x_forwarded_for,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that we get a HTTP 400 bad request with a malformed header."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Invalid IP address in X-Forwarded-For" in caplog.text
async def test_x_forwarded_for_with_multiple_headers(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_FOR, "123.123.123.123"),
],
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forwarded-For" in caplog.text
@pytest.mark.parametrize(
("x_forwarded_for", "remote", "x_forwarded_proto", "secure"),
[
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https, http, http", True),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https,http,http", True),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "http", False),
(
"10.10.10.10, 127.0.0.1, 127.0.0.2",
"10.10.10.10",
"http, https, https",
False,
),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https", True),
(
"255.255.255.255, 10.10.10.10, 127.0.0.1",
"10.10.10.10",
"http, https, http",
True,
),
(
"255.255.255.255, 10.10.10.10, 127.0.0.1",
"10.10.10.10",
"https, http, https",
False,
),
("255.255.255.255, 10.10.10.10, 127.0.0.1", "10.10.10.10", "https", True),
],
)
async def test_x_forwarded_proto_with_trusted_proxy(
x_forwarded_for,
remote,
x_forwarded_proto,
secure,
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that we get the proto header if proxy is trusted."""
async def handler(request):
assert request.remote == remote
assert request.scheme == ("https" if secure else "http")
assert request.secure == secure
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that we get the proto with 1 element in the proto, multiple in the for."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "https"
assert request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: "255.255.255.255, 127.0.0.1, 127.0.0.2",
X_FORWARDED_PROTO: "https",
},
)
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_not_processed_without_for(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that proto header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_PROTO: "https"})
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_with_multiple_headers(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_PROTO, "https"),
(X_FORWARDED_PROTO, "http"),
],
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forward-Proto" in caplog.text
@pytest.mark.parametrize(
"x_forwarded_proto",
["", ",", "https, , https", "https, https, "],
)
async def test_x_forwarded_proto_empty_element(
x_forwarded_proto,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that we get a HTTP 400 bad request with empty proto."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "1.1.1.1", X_FORWARDED_PROTO: x_forwarded_proto},
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Empty item received in X-Forward-Proto header" in caplog.text
@pytest.mark.parametrize(
("x_forwarded_for", "x_forwarded_proto", "expected", "got"),
[
("1.1.1.1, 2.2.2.2", "https, https, https", 2, 3),
("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4", "https, https, https", 4, 3),
],
)
async def test_x_forwarded_proto_incorrect_number_of_elements(
x_forwarded_for,
x_forwarded_proto,
expected,
got,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that we get a HTTP 400 bad request with incorrect number of elements."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert (
f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}"
in caplog.text
)
async def test_x_forwarded_host_with_trusted_proxy(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that we get the host header if proxy is trusted."""
async def handler(request):
assert request.host == "example.com"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
)
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_host_not_processed_without_for(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that host header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_HOST: "example.com"})
assert resp.status == HTTPStatus.OK
async def test_x_forwarded_host_with_multiple_headers(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_HOST, "example.com"),
(X_FORWARDED_HOST, "example.spoof"),
],
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forwarded-Host" in caplog.text
async def test_x_forwarded_host_with_empty_header(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that we get a HTTP 400 bad request with empty host value."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""}
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert "Empty value received in X-Forward-Host header" in caplog.text
async def test_x_forwarded_cloud(
aiohttp_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that cloud requests are not processed."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, True, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
with patch(
"hass_nabucasa.remote.is_cloud_request", Mock(get=Mock(return_value=True))
):
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""}
)
# This request would normally fail because it's invalid, now it works.
assert resp.status == HTTPStatus.OK

View File

@@ -0,0 +1,67 @@
"""Test headers middleware."""
from http import HTTPStatus
from aiohttp import web
from aiohttp.web_exceptions import HTTPUnauthorized
from homeassistant.components.http.headers import setup_headers
from tests.typing import ClientSessionGenerator
async def mock_handler(_: web.Request) -> web.Response:
"""Return OK."""
return web.Response(text="OK")
async def mock_handler_error(_: web.Request) -> web.Response:
"""Return Unauthorized."""
raise HTTPUnauthorized(text="Ah ah ah, you didn't say the magic word")
async def test_headers_added(aiohttp_client: ClientSessionGenerator) -> None:
"""Test that headers are being added on each request."""
app = web.Application()
app.router.add_get("/", mock_handler)
app.router.add_get("/error", mock_handler_error)
setup_headers(app, use_x_frame_options=True)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/")
assert resp.status == HTTPStatus.OK
assert resp.headers["Referrer-Policy"] == "no-referrer"
assert resp.headers["Server"] == ""
assert resp.headers["X-Content-Type-Options"] == "nosniff"
assert resp.headers["X-Frame-Options"] == "SAMEORIGIN"
resp = await mock_api_client.get("/error")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert resp.headers["Referrer-Policy"] == "no-referrer"
assert resp.headers["Server"] == ""
assert resp.headers["X-Content-Type-Options"] == "nosniff"
assert resp.headers["X-Frame-Options"] == "SAMEORIGIN"
async def test_allow_framing(aiohttp_client: ClientSessionGenerator) -> None:
"""Test that we allow framing when disabled."""
app = web.Application()
app.router.add_get("/", mock_handler)
app.router.add_get("/error", mock_handler_error)
setup_headers(app, use_x_frame_options=False)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/")
assert resp.status == HTTPStatus.OK
assert "X-Frame-Options" not in resp.headers
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/error")
assert resp.status == HTTPStatus.UNAUTHORIZED
assert "X-Frame-Options" not in resp.headers

View File

@@ -0,0 +1,696 @@
"""The tests for the Home Assistant HTTP component."""
import asyncio
from collections.abc import Callable
from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_network
import logging
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from homeassistant.auth.providers.homeassistant import HassAuthProvider
from homeassistant.components import cloud, http
from homeassistant.components.cloud import CloudNotAvailable
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.http import KEY_HASS
from homeassistant.helpers.network import NoURLAvailableError
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from homeassistant.util.ssl import server_context_intermediate, server_context_modern
from tests.common import async_fire_time_changed
from tests.typing import ClientSessionGenerator
def _setup_broken_ssl_pem_files(tmp_path: Path) -> tuple[Path, Path]:
test_dir = tmp_path / "test_broken_ssl"
test_dir.mkdir()
cert_path = test_dir / "cert.pem"
cert_path.write_text("garbage")
key_path = test_dir / "key.pem"
key_path.write_text("garbage")
return cert_path, key_path
def _setup_empty_ssl_pem_files(tmp_path: Path) -> tuple[Path, Path, Path]:
test_dir = tmp_path / "test_empty_ssl"
test_dir.mkdir()
cert_path = test_dir / "cert.pem"
cert_path.write_text("-")
peer_cert_path = test_dir / "peer_cert.pem"
peer_cert_path.write_text("-")
key_path = test_dir / "key.pem"
key_path.write_text("-")
return cert_path, key_path, peer_cert_path
@pytest.fixture
def mock_stack():
"""Mock extract stack."""
with patch(
"homeassistant.components.http.extract_stack",
return_value=[
Mock(
filename="/home/paulus/core/homeassistant/core.py",
lineno="23",
line="do_something()",
),
Mock(
filename="/home/paulus/core/homeassistant/components/hue/light.py",
lineno="23",
line="self.light.is_on",
),
Mock(
filename="/home/paulus/core/homeassistant/components/http/__init__.py",
lineno="157",
line="base_url",
),
],
):
yield
class TestView(http.HomeAssistantView):
"""Test the HTTP views."""
name = "test"
url = "/hello"
async def get(self, request):
"""Return a get request."""
return "hello"
async def test_registering_view_while_running(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
unused_tcp_port_factory: Callable[[], int],
) -> None:
"""Test that we can register a view while the server is running."""
await async_setup_component(
hass,
http.DOMAIN,
{http.DOMAIN: {http.CONF_SERVER_PORT: unused_tcp_port_factory()}},
)
await hass.async_start()
# This raises a RuntimeError if app is frozen
hass.http.register_view(TestView)
async def test_homeassistant_assigned_to_app(hass: HomeAssistant) -> None:
"""Test HomeAssistant instance is assigned to HomeAssistantApp."""
assert await async_setup_component(hass, "api", {"http": {}})
await hass.async_start()
assert hass.http.app[KEY_HASS] == hass
assert hass.http.app["hass"] == hass # For backwards compatibility
await hass.async_stop()
async def test_not_log_password(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
local_auth: HassAuthProvider,
) -> None:
"""Test access with password doesn't get logged."""
assert await async_setup_component(hass, "api", {"http": {}})
client = await hass_client_no_auth()
logging.getLogger("aiohttp.access").setLevel(logging.INFO)
resp = await client.get("/api/", params={"api_password": "test-password"})
assert resp.status == HTTPStatus.UNAUTHORIZED
logs = caplog.text
# Ensure we don't log API passwords
assert "/api/" in logs
assert "some-pass" not in logs
async def test_proxy_config(hass: HomeAssistant) -> None:
"""Test use_x_forwarded_for must config together with trusted_proxies."""
assert (
await async_setup_component(
hass,
"http",
{
"http": {
http.CONF_USE_X_FORWARDED_FOR: True,
http.CONF_TRUSTED_PROXIES: ["127.0.0.1"],
}
},
)
is True
)
async def test_proxy_config_only_use_xff(hass: HomeAssistant) -> None:
"""Test use_x_forwarded_for must config together with trusted_proxies."""
assert (
await async_setup_component(
hass, "http", {"http": {http.CONF_USE_X_FORWARDED_FOR: True}}
)
is not True
)
async def test_proxy_config_only_trust_proxies(hass: HomeAssistant) -> None:
"""Test use_x_forwarded_for must config together with trusted_proxies."""
assert (
await async_setup_component(
hass, "http", {"http": {http.CONF_TRUSTED_PROXIES: ["127.0.0.1"]}}
)
is not True
)
async def test_ssl_profile_defaults_modern(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test default ssl profile."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
) as mock_context,
):
assert (
await async_setup_component(
hass,
"http",
{"http": {"ssl_certificate": cert_path, "ssl_key": key_path}},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert len(mock_context.mock_calls) == 1
async def test_ssl_profile_change_intermediate(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test setting ssl profile to intermediate."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_intermediate",
side_effect=server_context_intermediate,
) as mock_context,
):
assert (
await async_setup_component(
hass,
"http",
{
"http": {
"ssl_profile": "intermediate",
"ssl_certificate": cert_path,
"ssl_key": key_path,
}
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert len(mock_context.mock_calls) == 1
async def test_ssl_profile_change_modern(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test setting ssl profile to modern."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
) as mock_context,
):
assert (
await async_setup_component(
hass,
"http",
{
"http": {
"ssl_profile": "modern",
"ssl_certificate": cert_path,
"ssl_key": key_path,
}
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert len(mock_context.mock_calls) == 1
async def test_peer_cert(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test required peer cert."""
cert_path, key_path, peer_cert_path = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch("ssl.SSLContext.load_verify_locations") as mock_load_verify_locations,
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
) as mock_context,
):
assert (
await async_setup_component(
hass,
"http",
{
"http": {
"ssl_peer_certificate": peer_cert_path,
"ssl_profile": "modern",
"ssl_certificate": cert_path,
"ssl_key": key_path,
}
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert len(mock_context.mock_calls) == 1
assert len(mock_load_verify_locations.mock_calls) == 1
async def test_emergency_ssl_certificate_when_invalid(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http can startup with an emergency self signed cert when the current one is broken."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.recovery_mode = True
assert (
await async_setup_component(
hass,
"http",
{
"http": {"ssl_certificate": cert_path, "ssl_key": key_path},
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert (
"Home Assistant is running in recovery mode with an emergency self signed ssl certificate because the configured SSL certificate was not usable"
in caplog.text
)
assert hass.http.site is not None
async def test_emergency_ssl_certificate_not_used_when_not_recovery_mode(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test an emergency cert is only used in recovery mode."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmp_path
)
assert (
await async_setup_component(
hass, "http", {"http": {"ssl_certificate": cert_path, "ssl_key": key_path}}
)
is False
)
async def test_emergency_ssl_certificate_when_invalid_get_url_fails(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken.
Ensure we can still start of we cannot determine the external url as well.
"""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.recovery_mode = True
with patch(
"homeassistant.components.http.get_url", side_effect=NoURLAvailableError
) as mock_get_url:
assert (
await async_setup_component(
hass,
"http",
{
"http": {"ssl_certificate": cert_path, "ssl_key": key_path},
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert len(mock_get_url.mock_calls) == 1
assert (
"Home Assistant is running in recovery mode with an emergency self signed ssl certificate because the configured SSL certificate was not usable"
in caplog.text
)
assert hass.http.site is not None
async def test_invalid_ssl_and_cannot_create_emergency_cert(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.recovery_mode = True
with patch(
"homeassistant.components.http.x509.CertificateBuilder", side_effect=OSError
) as mock_builder:
assert (
await async_setup_component(
hass,
"http",
{
"http": {"ssl_certificate": cert_path, "ssl_key": key_path},
},
)
is True
)
await hass.async_start()
await hass.async_block_till_done()
assert "Could not create an emergency self signed ssl certificate" in caplog.text
assert len(mock_builder.mock_calls) == 1
assert hass.http.site is not None
async def test_invalid_ssl_and_cannot_create_emergency_cert_with_ssl_peer_cert(
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken.
When there is a peer cert verification and we cannot create
an emergency cert (probably will never happen since this means
the system is very broken), we do not want to startup http
as it would allow connections that are not verified by the cert.
"""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.recovery_mode = True
with patch(
"homeassistant.components.http.x509.CertificateBuilder", side_effect=OSError
) as mock_builder:
assert (
await async_setup_component(
hass,
"http",
{
"http": {
"ssl_certificate": cert_path,
"ssl_key": key_path,
"ssl_peer_certificate": cert_path,
},
},
)
is False
)
await hass.async_start()
await hass.async_block_till_done()
assert "Could not create an emergency self signed ssl certificate" in caplog.text
assert len(mock_builder.mock_calls) == 1
async def test_cors_defaults(hass: HomeAssistant) -> None:
"""Test the CORS default settings."""
with patch("homeassistant.components.http.setup_cors") as mock_setup:
assert await async_setup_component(hass, "http", {})
assert len(mock_setup.mock_calls) == 1
assert mock_setup.mock_calls[0][1][1] == ["https://cast.home-assistant.io"]
async def test_storing_config(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
unused_tcp_port_factory: Callable[[], int],
) -> None:
"""Test that we store last working config."""
config = {
http.CONF_SERVER_PORT: unused_tcp_port_factory(),
"use_x_forwarded_for": True,
"trusted_proxies": ["192.168.1.100"],
}
assert await async_setup_component(hass, http.DOMAIN, {http.DOMAIN: config})
await hass.async_start()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=200))
await hass.async_block_till_done()
restored = await http.async_get_last_config(hass)
restored["trusted_proxies"][0] = ip_network(restored["trusted_proxies"][0])
assert restored == http.HTTP_SCHEMA(config)
async def test_logging(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Testing the access log works."""
await asyncio.gather(
*(
async_setup_component(hass, component, {})
for component in ("http", "logger", "api")
)
)
hass.states.async_set("logging.entity", "hello")
await hass.services.async_call(
"logger",
"set_level",
{"aiohttp.access": "info"},
blocking=True,
)
client = await hass_client()
response = await client.get("/api/states/logging.entity")
assert response.status == HTTPStatus.OK
assert "GET /api/states/logging.entity" in caplog.text
caplog.clear()
await hass.services.async_call(
"logger",
"set_level",
{"aiohttp.access": "warning"},
blocking=True,
)
response = await client.get("/api/states/logging.entity")
assert response.status == HTTPStatus.OK
assert "GET /api/states/logging.entity" not in caplog.text
async def test_register_static_paths(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test registering a static path with old api."""
assert await async_setup_component(hass, "frontend", {})
path = str(Path(__file__).parent)
hass.http.register_static_path("/something", path)
client = await hass_client()
resp = await client.get("/something/__init__.py")
assert resp.status == HTTPStatus.OK
assert (
"Detected code that calls hass.http.register_static_path "
"which is deprecated because it does blocking I/O in the "
"event loop, instead call "
"`await hass.http.async_register_static_paths"
) in caplog.text
async def test_ssl_issue_if_no_urls_configured(
hass: HomeAssistant,
tmp_path: Path,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test raising SSL issue if no external or internal URL is configured."""
assert hass.config.external_url is None
assert hass.config.internal_url is None
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
),
):
assert await async_setup_component(
hass,
"http",
{"http": {"ssl_certificate": cert_path, "ssl_key": key_path}},
)
await hass.async_start()
await hass.async_block_till_done()
assert ("http", "ssl_configured_without_configured_urls") in issue_registry.issues
async def test_ssl_issue_if_using_cloud(
hass: HomeAssistant,
tmp_path: Path,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test raising no SSL issue if not right configured but using cloud."""
assert hass.config.external_url is None
assert hass.config.internal_url is None
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch.object(cloud, "async_remote_ui_url", return_value="https://example.com"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
),
):
assert await async_setup_component(
hass,
"http",
{"http": {"ssl_certificate": cert_path, "ssl_key": key_path}},
)
await hass.async_start()
await hass.async_block_till_done()
assert (
"http",
"ssl_configured_without_configured_urls",
) not in issue_registry.issues
async def test_ssl_issue_if_not_connected_to_cloud(
hass: HomeAssistant,
tmp_path: Path,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test raising no SSL issue if not right configured and not connected to cloud."""
assert hass.config.external_url is None
assert hass.config.internal_url is None
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
),
patch(
"homeassistant.components.cloud.async_remote_ui_url",
side_effect=CloudNotAvailable,
),
):
assert await async_setup_component(
hass,
"http",
{"http": {"ssl_certificate": cert_path, "ssl_key": key_path}},
)
await hass.async_start()
await hass.async_block_till_done()
assert ("http", "ssl_configured_without_configured_urls") in issue_registry.issues
@pytest.mark.parametrize(
("external_url", "internal_url"),
[
("https://example.com", "https://example.local"),
(None, "http://example.local"),
("https://example.com", None),
],
)
async def test_ssl_issue_urls_configured(
hass: HomeAssistant,
tmp_path: Path,
issue_registry: ir.IssueRegistry,
external_url: str | None,
internal_url: str | None,
) -> None:
"""Test raising SSL issue if no external or internal URL is configured."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmp_path
)
hass.config.external_url = external_url
hass.config.internal_url = internal_url
with (
patch("ssl.SSLContext.load_cert_chain"),
patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
),
):
assert await async_setup_component(
hass,
"http",
{"http": {"ssl_certificate": cert_path, "ssl_key": key_path}},
)
await hass.async_start()
await hass.async_block_till_done()
assert (
"http",
"ssl_configured_without_configured_urls",
) not in issue_registry.issues

View File

@@ -0,0 +1,39 @@
"""Test request context middleware."""
from contextvars import ContextVar
from http import HTTPStatus
from aiohttp import web
from homeassistant.components.http.request_context import setup_request_context
from tests.typing import ClientSessionGenerator
async def test_request_context_middleware(
aiohttp_client: ClientSessionGenerator,
) -> None:
"""Test that request context is set from middleware."""
context = ContextVar("request", default=None)
app = web.Application()
async def mock_handler(request):
"""Return the real IP as text."""
request_context = context.get()
assert request_context
assert request_context == request
return web.Response(text="hi!")
app.router.add_get("/", mock_handler)
setup_request_context(app, context)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/")
assert resp.status == HTTPStatus.OK
text = await resp.text()
assert text == "hi!"
# We are outside of the context here, should be None
assert context.get() is None

View File

@@ -0,0 +1,160 @@
"""Test security filter middleware."""
import asyncio
from http import HTTPStatus
from aiohttp import web
import pytest
import urllib3
from homeassistant.components.http.security_filter import setup_security_filter
from tests.typing import ClientSessionGenerator
async def mock_handler(request):
"""Return OK."""
return web.Response(text="OK")
@pytest.mark.parametrize(
("request_path", "request_params"),
[
("/", {}),
("/lovelace/dashboard", {}),
("/frontend_latest/chunk.4c9e2d8dc10f77b885b0.js", {}),
("/static/translations/en-f96a262a5a6eede29234dc45dc63abf2.json", {}),
("/", {"test": "123"}),
],
)
async def test_ok_requests(
request_path, request_params, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test request paths that should not be filtered."""
app = web.Application()
app.router.add_get("/{all:.*}", mock_handler)
setup_security_filter(app)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(request_path, params=request_params)
assert resp.status == HTTPStatus.OK
assert await resp.text() == "OK"
@pytest.mark.parametrize(
("request_path", "request_params", "fail_on_query_string"),
[
("/proc/self/environ", {}, False),
("/", {"test": "/test/../../api"}, True),
("/", {"test": "test/../../api"}, True),
("/", {"test": "/test/%2E%2E%2f%2E%2E%2fapi"}, True),
("/", {"test": "test/%2E%2E%2f%2E%2E%2fapi"}, True),
("/", {"test": "test/%252E%252E/api"}, True),
("/", {"test": "test/%252E%252E%2fapi"}, True),
(
"/",
{"test": "test/%2525252E%2525252E%2525252f%2525252E%2525252E%2525252fapi"},
True,
),
("/test/.%252E/api", {}, False),
("/test/%252E%252E/api", {}, False),
("/test/%2E%2E%2f%2E%2E%2fapi", {}, False),
("/test/%2525252E%2525252E%2525252f%2525252E%2525252E/api", {}, False),
("/", {"sql": ";UNION SELECT (a, b"}, True),
("/", {"sql": "UNION%20SELECT%20%28a%2C%20b"}, True),
("/UNION%20SELECT%20%28a%2C%20b", {}, False),
("/", {"sql": "concat(..."}, True),
("/", {"xss": "<script >"}, True),
("/<script >", {"xss": ""}, False),
("/%3Cscript%3E", {}, False),
],
)
async def test_bad_requests(
request_path,
request_params,
fail_on_query_string,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test request paths that should be filtered."""
app = web.Application()
app.router.add_get("/{all:.*}", mock_handler)
setup_security_filter(app)
mock_api_client = await aiohttp_client(app)
# Manual params handling
if request_params:
raw_params = "&".join(f"{val}={key}" for val, key in request_params.items())
man_params = f"?{raw_params}"
else:
man_params = ""
http = urllib3.PoolManager()
resp = await asyncio.get_running_loop().run_in_executor(
None,
http.request,
"GET",
f"http://{mock_api_client.host}:{mock_api_client.port}{request_path}{man_params}",
request_params,
)
assert resp.status == HTTPStatus.BAD_REQUEST
message = "Filtered a potential harmful request to:"
if fail_on_query_string:
message = "Filtered a request with a potential harmful query string:"
assert message in caplog.text
@pytest.mark.parametrize(
("request_path", "request_params", "fail_on_query_string"),
[
("/some\thing", {}, False),
("/new\nline/cinema", {}, False),
("/return\r/to/sender", {}, False),
("/", {"some": "\thing"}, True),
("/", {"\newline": "cinema"}, True),
("/", {"return": "t\rue"}, True),
],
)
async def test_bad_requests_with_unsafe_bytes(
request_path,
request_params,
fail_on_query_string,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test request with unsafe bytes in their URLs."""
app = web.Application()
app.router.add_get("/{all:.*}", mock_handler)
setup_security_filter(app)
mock_api_client = await aiohttp_client(app)
# Manual params handling
if request_params:
raw_params = "&".join(f"{val}={key}" for val, key in request_params.items())
man_params = f"?{raw_params}"
else:
man_params = ""
http = urllib3.PoolManager()
resp = await asyncio.get_running_loop().run_in_executor(
None,
http.request,
"GET",
f"http://{mock_api_client.host}:{mock_api_client.port}{request_path}{man_params}",
request_params,
)
assert resp.status == HTTPStatus.BAD_REQUEST
message = "Filtered a request with an unsafe byte in path:"
if fail_on_query_string:
message = "Filtered a request with unsafe byte query string:"
assert message in caplog.text

View File

@@ -0,0 +1,65 @@
"""The tests for http static files."""
from http import HTTPStatus
from pathlib import Path
from aiohttp.test_utils import TestClient
import pytest
from homeassistant.components.http import StaticPathConfig
from homeassistant.components.http.static import CachingStaticResource
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.core import HomeAssistant
from homeassistant.helpers.http import KEY_ALLOW_CONFIGURED_CORS
from homeassistant.setup import async_setup_component
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
async def http(hass: HomeAssistant) -> None:
"""Ensure http is set up."""
assert await async_setup_component(hass, "http", {})
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
@pytest.fixture
async def mock_http_client(hass: HomeAssistant, aiohttp_client: ClientSessionGenerator):
"""Start the Home Assistant HTTP component."""
return await aiohttp_client(hass.http.app, server_kwargs={"skip_url_asserts": True})
async def test_static_resource_show_index(
hass: HomeAssistant, mock_http_client: TestClient, tmp_path: Path
) -> None:
"""Test static resource will return a directory index."""
app = hass.http.app
resource = CachingStaticResource("/", tmp_path, show_index=True)
app.router.register_resource(resource)
app[KEY_ALLOW_CONFIGURED_CORS](resource)
resp = await mock_http_client.get("/")
assert resp.status == 200
assert resp.content_type == "text/html"
async def test_async_register_static_paths(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test registering multiple static paths."""
assert await async_setup_component(hass, "frontend", {})
path = str(Path(__file__).parent)
await hass.http.async_register_static_paths(
[
StaticPathConfig("/something", path),
StaticPathConfig("/something_else", path),
]
)
client = await hass_client()
resp = await client.get("/something/__init__.py")
assert resp.status == HTTPStatus.OK
resp = await client.get("/something_else/__init__.py")
assert resp.status == HTTPStatus.OK

View File

@@ -0,0 +1,100 @@
"""Tests for Home Assistant View."""
from decimal import Decimal
from http import HTTPStatus
import json
from unittest.mock import AsyncMock, Mock
from aiohttp.web_exceptions import (
HTTPBadRequest,
HTTPInternalServerError,
HTTPUnauthorized,
)
import pytest
import voluptuous as vol
from homeassistant.components.http import KEY_HASS
from homeassistant.components.http.view import (
HomeAssistantView,
request_handler_factory,
)
from homeassistant.exceptions import ServiceNotFound, Unauthorized
@pytest.fixture
def mock_request() -> Mock:
"""Mock a request."""
return Mock(app={KEY_HASS: Mock(is_stopping=False)}, match_info={})
@pytest.fixture
def mock_request_with_stopping() -> Mock:
"""Mock a request."""
return Mock(app={KEY_HASS: Mock(is_stopping=True)}, match_info={})
async def test_invalid_json(caplog: pytest.LogCaptureFixture) -> None:
"""Test trying to return invalid JSON."""
with pytest.raises(HTTPInternalServerError):
HomeAssistantView.json({"hello": Decimal("2.0")})
assert (
"Unable to serialize to JSON. Bad data found at $.hello=2.0(<class 'decimal.Decimal'>"
in caplog.text
)
async def test_nan_serialized_to_null() -> None:
"""Test nan serialized to null JSON."""
response = HomeAssistantView.json(float("NaN"))
assert json.loads(response.body.decode("utf-8")) is None
async def test_handling_unauthorized(mock_request: Mock) -> None:
"""Test handling unauth exceptions."""
with pytest.raises(HTTPUnauthorized):
await request_handler_factory(
mock_request.app[KEY_HASS],
Mock(requires_auth=False),
AsyncMock(side_effect=Unauthorized),
)(mock_request)
async def test_handling_invalid_data(mock_request: Mock) -> None:
"""Test handling unauth exceptions."""
with pytest.raises(HTTPBadRequest):
await request_handler_factory(
mock_request.app[KEY_HASS],
Mock(requires_auth=False),
AsyncMock(side_effect=vol.Invalid("yo")),
)(mock_request)
async def test_handling_service_not_found(mock_request: Mock) -> None:
"""Test handling unauth exceptions."""
with pytest.raises(HTTPInternalServerError):
await request_handler_factory(
mock_request.app[KEY_HASS],
Mock(requires_auth=False),
AsyncMock(side_effect=ServiceNotFound("test", "test")),
)(mock_request)
async def test_not_running(mock_request_with_stopping: Mock) -> None:
"""Test we get a 503 when not running."""
response = await request_handler_factory(
mock_request_with_stopping.app[KEY_HASS],
Mock(requires_auth=False),
AsyncMock(side_effect=Unauthorized),
)(mock_request_with_stopping)
assert response.status == HTTPStatus.SERVICE_UNAVAILABLE
async def test_invalid_handler(mock_request: Mock) -> None:
"""Test an invalid handler."""
with pytest.raises(TypeError):
await request_handler_factory(
mock_request.app[KEY_HASS],
Mock(requires_auth=False),
AsyncMock(return_value=["not valid"]),
)(mock_request)