diff --git a/custom_components/dataplicity/__init__.py b/custom_components/dataplicity/__init__.py index 3c76f15..fc7b94f 100644 --- a/custom_components/dataplicity/__init__.py +++ b/custom_components/dataplicity/__init__.py @@ -6,6 +6,8 @@ from homeassistant.requirements import async_process_requirements from homeassistant.util import package +from . import utils + DOMAIN = 'dataplicity' @@ -48,6 +50,8 @@ async def hass_stop(event): hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, hass_stop) + await utils.fix_middleware(hass) + return True diff --git a/custom_components/dataplicity/utils.py b/custom_components/dataplicity/utils.py index b32f57d..678ce81 100644 --- a/custom_components/dataplicity/utils.py +++ b/custom_components/dataplicity/utils.py @@ -1,6 +1,8 @@ import logging +from ipaddress import IPv4Network from aiohttp import ClientSession +from homeassistant.helpers.typing import HomeAssistantType _LOGGER = logging.getLogger(__name__) @@ -17,3 +19,29 @@ async def register_device(session: ClientSession, token: str): except: _LOGGER.exception("Can't register dataplicity device") return None + + +async def fix_middleware(hass: HomeAssistantType): + """Dirty hack for HTTP integration. Plug and play for usual users... + + [v2021.7] Home Assistant will now block HTTP requests when a misconfigured + reverse proxy, or misconfigured Home Assistant instance when using a + reverse proxy, has been detected. + + http: + use_x_forwarded_for: true + trusted_proxies: + - 127.0.0.1 + """ + for f in hass.http.app.middlewares: + if f.__name__ != 'forwarded_middleware': + continue + # https://til.hashrocket.com/posts/ykhyhplxjh-examining-the-closure + for i, var in enumerate(f.__code__.co_freevars): + cell = f.__closure__[i] + if var == 'use_x_forwarded_for': + if not cell.cell_contents: + cell.cell_contents = True + elif var == 'trusted_proxies': + if not cell.cell_contents: + cell.cell_contents = [IPv4Network('127.0.0.1/32')]