core/tests/components/http/test_cors.py

170 lines
5.4 KiB
Python
Raw Normal View History

"""Test cors for the HTTP component."""
from http import HTTPStatus
2019-07-25 11:52:27 +00:00
from pathlib import Path
2021-01-01 21:31:56 +00:00
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,
2019-07-31 19:25:30 +00:00
ORIGIN,
)
import pytest
from homeassistant.components.http.cors import setup_cors
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import HTTP_HEADER_HA_AUTH
from tests.typing import ClientSessionGenerator
2019-07-31 19:25:30 +00:00
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."""
2019-07-31 19:25:30 +00:00
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."""
2019-07-31 19:25:30 +00:00
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
Upgrade pytest-aiohttp (#82475) * Upgrade pytest-aiohttp * Make sure executors, tasks and timers are closed Some test will trigger warnings on garbage collect, these warnings spills over into next test. Some test trigger tasks that raise errors on shutdown, these spill over into next test. This is to mimic older pytest-aiohttp and it's behaviour on test cleanup. Discussions on similar changes for pytest-aiohttp are here: https://github.com/pytest-dev/pytest-asyncio/pull/309 * Replace loop with event_loop * Make sure time is frozen for tests * Make sure the ConditionType is not async /home-assistant/homeassistant/helpers/template.py:2082: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited def wrapper(*args, **kwargs): Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. * Increase litejet press tests with a factor 10 The times are simulated anyway, and we can't stop the normal event from occuring. * Use async handlers for aiohttp tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template /Users/joakim/src/hass/home-assistant/venv/lib/python3.9/site-packages/aiohttp/web_urldispatcher.py:189: DeprecationWarning: Bare functions are deprecated, use async ones warnings.warn( * Switch to freezegun in modbus tests The tests allowed clock to tick in between steps * Make sure skybell object are fully mocked Old tests would trigger attempts to post to could services: ``` DEBUG:aioskybell:HTTP post https://cloud.myskybell.com/api/v3/login/ Request with headers: {'content-type': 'application/json', 'accept': '*/*', 'x-skybell-app-id': 'd2b542c7-a7e4-4e1e-b77d-2b76911c7c46', 'x-skybell-client-id': '1f36a3c0-6dee-4997-a6db-4e1c67338e57'} ``` * Fix sorting that broke after rebase
2022-11-29 21:36:36 +00:00
def client(event_loop, aiohttp_client):
2018-08-19 20:29:08 +00:00
"""Fixture to set up a web.Application."""
app = web.Application()
setup_cors(app, [TRUSTED_ORIGIN])
app["allow_configured_cors"](app.router.add_get("/", mock_handler))
Upgrade pytest-aiohttp (#82475) * Upgrade pytest-aiohttp * Make sure executors, tasks and timers are closed Some test will trigger warnings on garbage collect, these warnings spills over into next test. Some test trigger tasks that raise errors on shutdown, these spill over into next test. This is to mimic older pytest-aiohttp and it's behaviour on test cleanup. Discussions on similar changes for pytest-aiohttp are here: https://github.com/pytest-dev/pytest-asyncio/pull/309 * Replace loop with event_loop * Make sure time is frozen for tests * Make sure the ConditionType is not async /home-assistant/homeassistant/helpers/template.py:2082: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited def wrapper(*args, **kwargs): Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. * Increase litejet press tests with a factor 10 The times are simulated anyway, and we can't stop the normal event from occuring. * Use async handlers for aiohttp tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template /Users/joakim/src/hass/home-assistant/venv/lib/python3.9/site-packages/aiohttp/web_urldispatcher.py:189: DeprecationWarning: Bare functions are deprecated, use async ones warnings.warn( * Switch to freezegun in modbus tests The tests allowed clock to tick in between steps * Make sure skybell object are fully mocked Old tests would trigger attempts to post to could services: ``` DEBUG:aioskybell:HTTP post https://cloud.myskybell.com/api/v3/login/ Request with headers: {'content-type': 'application/json', 'accept': '*/*', 'x-skybell-app-id': 'd2b542c7-a7e4-4e1e-b77d-2b76911c7c46', 'x-skybell-client-id': '1f36a3c0-6dee-4997-a6db-4e1c67338e57'} ``` * Fix sorting that broke after rebase
2022-11-29 21:36:36 +00:00
return event_loop.run_until_complete(aiohttp_client(app))
async def test_cors_requests(client) -> None:
"""Test cross origin requests."""
2019-07-31 19:25:30 +00:00
req = await client.get("/", headers={ORIGIN: TRUSTED_ORIGIN})
assert req.status == HTTPStatus.OK
2019-07-31 19:25:30 +00:00
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in URL
2019-07-31 19:25:30 +00:00
req = await client.get(
"/", params={"api_password": "some-pass"}, headers={ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
2019-07-31 19:25:30 +00:00
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in headers
2019-07-31 19:25:30 +00:00
req = await client.get(
"/", headers={HTTP_HEADER_HA_AUTH: "some-pass", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
2019-07-31 19:25:30 +00:00
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With auth token in headers
2019-07-31 19:25:30 +00:00
req = await client.get(
"/", headers={AUTHORIZATION: "Bearer some-token", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == HTTPStatus.OK
2019-07-31 19:25:30 +00:00
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."""
2019-07-31 19:25:30 +00:00
req = await client.options(
"/",
headers={
ORIGIN: TRUSTED_ORIGIN,
ACCESS_CONTROL_REQUEST_METHOD: "GET",
ACCESS_CONTROL_REQUEST_HEADERS: "x-requested-with",
2019-07-31 19:25:30 +00:00
},
)
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."""
2019-07-31 19:25:30 +00:00
class MyView(HomeAssistantView):
"""Test view that allows CORS."""
requires_auth = False
cors_allowed = True
def __init__(self, url, name):
"""Initialize test view."""
self.url = url
self.name = name
async def get(self, request):
"""Test response."""
return "test"
2019-07-31 19:25:30 +00:00
assert await async_setup_component(
hass, "http", {"http": {"cors_allowed_origins": ["http://home-assistant.io"]}}
)
2019-07-31 19:25:30 +00:00
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()
2019-06-03 18:43:13 +00:00
async def test_cors_works_with_frontend(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
2019-06-03 18:43:13 +00:00
"""Test CORS works with the frontend."""
2019-07-31 19:25:30 +00:00
assert await async_setup_component(
hass,
"frontend",
{"http": {"cors_allowed_origins": ["http://home-assistant.io"]}},
)
2019-06-03 18:43:13 +00:00
client = await hass_client()
2019-07-31 19:25:30 +00:00
resp = await client.get("/")
assert resp.status == HTTPStatus.OK
2019-07-25 11:52:27 +00:00
async def test_cors_on_static_files(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
2019-07-25 11:52:27 +00:00
"""Test that we enable CORS for static files."""
2019-07-31 19:25:30 +00:00
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))
2019-07-25 11:52:27 +00:00
client = await hass_client()
2019-07-31 19:25:30 +00:00
resp = await client.options(
"/something/__init__.py",
headers={
"origin": "http://www.example.com",
ACCESS_CONTROL_REQUEST_METHOD: "GET",
},
)
assert resp.status == HTTPStatus.OK
2019-07-31 19:25:30 +00:00
assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com"