Protect our user agent (#51486)

* Protect our user agent

* Fix expected error
pull/51494/head
Paulus Schoutsen 2021-06-04 09:14:18 -07:00 committed by GitHub
parent 5e067c2631
commit ede7932a57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -6,6 +6,7 @@ from collections.abc import Awaitable
from contextlib import suppress from contextlib import suppress
from ssl import SSLContext from ssl import SSLContext
import sys import sys
from types import MappingProxyType
from typing import Any, Callable, cast from typing import Any, Callable, cast
import aiohttp import aiohttp
@ -95,9 +96,14 @@ def _async_create_clientsession(
"""Create a new ClientSession with kwargs, i.e. for cookies.""" """Create a new ClientSession with kwargs, i.e. for cookies."""
clientsession = aiohttp.ClientSession( clientsession = aiohttp.ClientSession(
connector=_async_get_connector(hass, verify_ssl), connector=_async_get_connector(hass, verify_ssl),
headers={USER_AGENT: SERVER_SOFTWARE},
**kwargs, **kwargs,
) )
# Prevent packages accidentally overriding our default headers
# It's important that we identify as Home Assistant
# If a package requires a different user agent, override it by passing a headers
# dictionary to the request method.
# pylint: disable=protected-access
clientsession._default_headers = MappingProxyType({USER_AGENT: SERVER_SOFTWARE}) # type: ignore
clientsession.close = warn_use(clientsession.close, WARN_CLOSE_MSG) # type: ignore clientsession.close = warn_use(clientsession.close, WARN_CLOSE_MSG) # type: ignore

View File

@ -195,3 +195,14 @@ async def test_async_aiohttp_proxy_stream_client_err(aioclient_mock, camera_clie
resp = await camera_client.get("/api/camera_proxy_stream/camera.config_test") resp = await camera_client.get("/api/camera_proxy_stream/camera.config_test")
assert resp.status == 502 assert resp.status == 502
async def test_client_session_immutable_headers(hass):
"""Test we can't mutate headers."""
session = client.async_get_clientsession(hass)
with pytest.raises(TypeError):
session.headers["user-agent"] = "bla"
with pytest.raises(AttributeError):
session.headers.update({"user-agent": "bla"})