This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ def mock_real_ip(app):
request[KEY_REAL_IP] = ip_address(ip_to_mock)
return (await handler(request))
return await handler(request)
async def real_ip_startup(app):
"""Startup of real ip."""
+78 -145
View File
@@ -16,18 +16,17 @@ from homeassistant.setup import async_setup_component
from . import mock_real_ip
API_PASSWORD = 'test-password'
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'),
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']
UNTRUSTED_ADDRESSES = ['198.51.100.1', '2001:DB8:FA1::1', '127.0.0.1', '::1']
TRUSTED_ADDRESSES = ["100.64.0.1", "192.0.2.100", "FD01:DB8::1", "2001:DB8:ABCD::1"]
UNTRUSTED_ADDRESSES = ["198.51.100.1", "2001:DB8:FA1::1", "127.0.0.1", "::1"]
async def mock_handler(request):
@@ -35,17 +34,15 @@ async def mock_handler(request):
if not request[KEY_AUTHENTICATED]:
raise HTTPUnauthorized
user = request.get('hass_user')
user = request.get("hass_user")
user_id = user.id if user else None
return web.json_response(status=200, data={
'user_id': user_id,
})
return web.json_response(status=200, data={"user_id": user_id})
async def get_legacy_user(auth):
"""Get the user in legacy_api_password auth provider."""
provider = auth.get_auth_provider('legacy_api_password', None)
provider = auth.get_auth_provider("legacy_api_password", None)
return await auth.async_get_or_create_user(
await provider.async_get_or_create_credentials({})
)
@@ -55,8 +52,8 @@ async def get_legacy_user(auth):
def app(hass):
"""Fixture to set up a web.Application."""
app = web.Application()
app['hass'] = hass
app.router.add_get('/', mock_handler)
app["hass"] = hass
app.router.add_get("/", mock_handler)
setup_real_ip(app, False, [])
return app
@@ -65,8 +62,8 @@ def app(hass):
def app2(hass):
"""Fixture to set up a web.Application without real_ip middleware."""
app = web.Application()
app['hass'] = hass
app.router.add_get('/', mock_handler)
app["hass"] = hass
app.router.add_get("/", mock_handler)
return app
@@ -74,10 +71,9 @@ def app2(hass):
def trusted_networks_auth(hass):
"""Load trusted networks auth provider."""
prv = trusted_networks.TrustedNetworksAuthProvider(
hass, hass.auth._store, {
'type': 'trusted_networks',
'trusted_networks': TRUSTED_NETWORKS,
}
hass,
hass.auth._store,
{"type": "trusted_networks", "trusted_networks": TRUSTED_NETWORKS},
)
hass.auth._providers[(prv.type, prv.id)] = prv
return prv
@@ -85,54 +81,40 @@ def trusted_networks_auth(hass):
async def test_auth_middleware_loaded_by_default(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_auth') as mock_setup:
await async_setup_component(hass, 'http', {
'http': {}
})
with patch("homeassistant.components.http.setup_auth") as mock_setup:
await async_setup_component(hass, "http", {"http": {}})
assert len(mock_setup.mock_calls) == 1
async def test_access_with_password_in_header(app, aiohttp_client,
legacy_auth, hass):
async def test_access_with_password_in_header(app, aiohttp_client, legacy_auth, hass):
"""Test access with password in header."""
setup_auth(hass, app)
client = await aiohttp_client(app)
user = await get_legacy_user(hass.auth)
req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == 200
assert await req.json() == {
'user_id': user.id,
}
assert await req.json() == {"user_id": user.id}
req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: 'wrong-pass'})
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: "wrong-pass"})
assert req.status == 401
async def test_access_with_password_in_query(app, aiohttp_client, legacy_auth,
hass):
async def test_access_with_password_in_query(app, aiohttp_client, legacy_auth, hass):
"""Test access with password in URL."""
setup_auth(hass, app)
client = await aiohttp_client(app)
user = await get_legacy_user(hass.auth)
resp = await client.get('/', params={
'api_password': API_PASSWORD
})
resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == 200
assert await resp.json() == {
'user_id': user.id,
}
assert await resp.json() == {"user_id": user.id}
resp = await client.get('/')
resp = await client.get("/")
assert resp.status == 401
resp = await client.get('/', params={
'api_password': 'wrong-password'
})
resp = await client.get("/", params={"api_password": "wrong-password"})
assert resp.status == 401
@@ -142,35 +124,23 @@ async def test_basic_auth_works(app, aiohttp_client, hass, legacy_auth):
client = await aiohttp_client(app)
user = await get_legacy_user(hass.auth)
req = await client.get(
'/',
auth=BasicAuth('homeassistant', API_PASSWORD))
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == 200
assert await req.json() == {
'user_id': user.id,
}
assert await req.json() == {"user_id": user.id}
req = await client.get(
'/',
auth=BasicAuth('wrong_username', API_PASSWORD))
req = await client.get("/", auth=BasicAuth("wrong_username", API_PASSWORD))
assert req.status == 401
req = await client.get(
'/',
auth=BasicAuth('homeassistant', 'wrong password'))
req = await client.get("/", auth=BasicAuth("homeassistant", "wrong password"))
assert req.status == 401
req = await client.get(
'/',
headers={
'authorization': 'NotBasic abcdefg'
})
req = await client.get("/", headers={"authorization": "NotBasic abcdefg"})
assert req.status == 401
async def test_access_with_trusted_ip(hass, app2, trusted_networks_auth,
aiohttp_client,
hass_owner_user):
async def test_access_with_trusted_ip(
hass, app2, trusted_networks_auth, aiohttp_client, hass_owner_user
):
"""Test access with an untrusted ip address."""
setup_auth(hass, app2)
@@ -179,70 +149,52 @@ async def test_access_with_trusted_ip(hass, app2, trusted_networks_auth,
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get('/')
assert resp.status == 401, \
"{} shouldn't be trusted".format(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get('/')
assert resp.status == 200, \
"{} should be trusted".format(remote_addr)
assert await resp.json() == {
'user_id': hass_owner_user.id,
}
resp = await client.get("/")
assert resp.status == 200, "{} should be trusted".format(remote_addr)
assert await resp.json() == {"user_id": hass_owner_user.id}
async def test_auth_active_access_with_access_token_in_header(
hass, app, aiohttp_client, hass_access_token):
hass, app, aiohttp_client, hass_access_token
):
"""Test access with access token in header."""
token = hass_access_token
setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
req = await client.get(
'/', headers={'Authorization': 'Bearer {}'.format(token)})
req = await client.get("/", headers={"Authorization": "Bearer {}".format(token)})
assert req.status == 200
assert await req.json() == {
'user_id': refresh_token.user.id,
}
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get(
'/', headers={'AUTHORIZATION': 'Bearer {}'.format(token)})
req = await client.get("/", headers={"AUTHORIZATION": "Bearer {}".format(token)})
assert req.status == 200
assert await req.json() == {
'user_id': refresh_token.user.id,
}
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get(
'/', headers={'authorization': 'Bearer {}'.format(token)})
req = await client.get("/", headers={"authorization": "Bearer {}".format(token)})
assert req.status == 200
assert await req.json() == {
'user_id': refresh_token.user.id,
}
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get(
'/', headers={'Authorization': token})
req = await client.get("/", headers={"Authorization": token})
assert req.status == 401
req = await client.get(
'/', headers={'Authorization': 'BEARER {}'.format(token)})
req = await client.get("/", headers={"Authorization": "BEARER {}".format(token)})
assert req.status == 401
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
refresh_token.user.is_active = False
req = await client.get(
'/', headers={'Authorization': 'Bearer {}'.format(token)})
req = await client.get("/", headers={"Authorization": "Bearer {}".format(token)})
assert req.status == 401
async def test_auth_active_access_with_trusted_ip(hass, app2,
trusted_networks_auth,
aiohttp_client,
hass_owner_user):
async def test_auth_active_access_with_trusted_ip(
hass, app2, trusted_networks_auth, aiohttp_client, hass_owner_user
):
"""Test access with an untrusted ip address."""
setup_auth(hass, app2)
@@ -251,74 +203,55 @@ async def test_auth_active_access_with_trusted_ip(hass, app2,
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get('/')
assert resp.status == 401, \
"{} shouldn't be trusted".format(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get('/')
assert resp.status == 200, \
"{} should be trusted".format(remote_addr)
assert await resp.json() == {
'user_id': hass_owner_user.id,
}
resp = await client.get("/")
assert resp.status == 200, "{} should be trusted".format(remote_addr)
assert await resp.json() == {"user_id": hass_owner_user.id}
async def test_auth_legacy_support_api_password_access(
app, aiohttp_client, legacy_auth, hass):
app, aiohttp_client, legacy_auth, hass
):
"""Test access using api_password if auth.support_legacy."""
setup_auth(hass, app)
client = await aiohttp_client(app)
user = await get_legacy_user(hass.auth)
req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == 200
assert await req.json() == {
'user_id': user.id,
}
assert await req.json() == {"user_id": user.id}
resp = await client.get('/', params={
'api_password': API_PASSWORD
})
resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == 200
assert await resp.json() == {
'user_id': user.id,
}
assert await resp.json() == {"user_id": user.id}
req = await client.get(
'/',
auth=BasicAuth('homeassistant', API_PASSWORD))
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == 200
assert await req.json() == {
'user_id': user.id,
}
assert await req.json() == {"user_id": user.id}
async def test_auth_access_signed_path(
hass, app, aiohttp_client, hass_access_token):
async def test_auth_access_signed_path(hass, app, aiohttp_client, hass_access_token):
"""Test access with signed url."""
app.router.add_post('/', mock_handler)
app.router.add_get('/another_path', mock_handler)
app.router.add_post("/", mock_handler)
app.router.add_get("/another_path", mock_handler)
setup_auth(hass, app)
client = await aiohttp_client(app)
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
signed_path = async_sign_path(
hass, refresh_token.id, '/', timedelta(seconds=5)
)
signed_path = async_sign_path(hass, refresh_token.id, "/", timedelta(seconds=5))
req = await client.get(signed_path)
assert req.status == 200
data = await req.json()
assert data['user_id'] == refresh_token.user.id
assert data["user_id"] == refresh_token.user.id
# Use signature on other path
req = await client.get(
'/another_path?{}'.format(signed_path.split('?')[1]))
req = await client.get("/another_path?{}".format(signed_path.split("?")[1]))
assert req.status == 401
# We only allow GET
@@ -327,7 +260,7 @@ async def test_auth_access_signed_path(
# Never valid as expired in the past.
expired_signed_path = async_sign_path(
hass, refresh_token.id, '/', timedelta(seconds=-5)
hass, refresh_token.id, "/", timedelta(seconds=-5)
)
req = await client.get(expired_signed_path)
+44 -38
View File
@@ -12,14 +12,19 @@ from homeassistant.components.http.view import request_handler_factory
from homeassistant.setup import async_setup_component
import homeassistant.components.http as http
from homeassistant.components.http.ban import (
IpBan, IP_BANS_FILE, setup_bans, KEY_BANNED_IPS, KEY_FAILED_LOGIN_ATTEMPTS)
IpBan,
IP_BANS_FILE,
setup_bans,
KEY_BANNED_IPS,
KEY_FAILED_LOGIN_ATTEMPTS,
)
from . import mock_real_ip
from tests.common import mock_coro
BANNED_IPS = ['200.201.202.203', '100.64.0.2']
BANNED_IPS = ["200.201.202.203", "100.64.0.2"]
async def test_access_from_banned_ip(hass, aiohttp_client):
@@ -28,35 +33,32 @@ async def test_access_from_banned_ip(hass, aiohttp_client):
setup_bans(hass, app, 5)
set_real_ip = mock_real_ip(app)
with patch('homeassistant.components.http.ban.async_load_ip_bans_config',
return_value=mock_coro([IpBan(banned_ip) for banned_ip
in BANNED_IPS])):
with patch(
"homeassistant.components.http.ban.async_load_ip_bans_config",
return_value=mock_coro([IpBan(banned_ip) 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('/')
resp = await client.get("/")
assert resp.status == 403
async def test_ban_middleware_not_loaded_by_config(hass):
"""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,
}
})
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):
"""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': {}
})
with patch("homeassistant.components.http.setup_bans") as mock_setup:
await async_setup_component(hass, "http", {"http": {}})
assert len(mock_setup.mock_calls) == 1
@@ -64,35 +66,36 @@ async def test_ban_middleware_loaded_by_default(hass):
async def test_ip_bans_file_creation(hass, aiohttp_client):
"""Testing if banned IP file created."""
app = web.Application()
app['hass'] = hass
app["hass"] = hass
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
app.router.add_get('/', unauth_handler)
app.router.add_get("/", unauth_handler)
setup_bans(hass, app, 2)
mock_real_ip(app)("200.201.202.204")
with patch('homeassistant.components.http.ban.async_load_ip_bans_config',
return_value=mock_coro([IpBan(banned_ip) for banned_ip
in BANNED_IPS])):
with patch(
"homeassistant.components.http.ban.async_load_ip_bans_config",
return_value=mock_coro([IpBan(banned_ip) for banned_ip in BANNED_IPS]),
):
client = await aiohttp_client(app)
m = mock_open()
with patch('homeassistant.components.http.ban.open', m, create=True):
resp = await client.get('/')
with patch("homeassistant.components.http.ban.open", m, create=True):
resp = await client.get("/")
assert resp.status == 401
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS)
assert m.call_count == 0
resp = await client.get('/')
resp = await client.get("/")
assert resp.status == 401
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) + 1
m.assert_called_once_with(hass.config.path(IP_BANS_FILE), 'a')
m.assert_called_once_with(hass.config.path(IP_BANS_FILE), "a")
resp = await client.get('/')
resp = await client.get("/")
assert resp.status == 403
assert m.call_count == 1
@@ -100,18 +103,21 @@ async def test_ip_bans_file_creation(hass, aiohttp_client):
async def test_failed_login_attempts_counter(hass, aiohttp_client):
"""Testing if failed login attempts counter increased."""
app = web.Application()
app['hass'] = hass
app["hass"] = hass
async def auth_handler(request):
"""Return 200 status code."""
return None, 200
app.router.add_get('/auth_true', request_handler_factory(
Mock(requires_auth=True), auth_handler))
app.router.add_get('/auth_false', request_handler_factory(
Mock(requires_auth=True), auth_handler))
app.router.add_get('/', request_handler_factory(
Mock(requires_auth=False), auth_handler))
app.router.add_get(
"/auth_true", request_handler_factory(Mock(requires_auth=True), auth_handler)
)
app.router.add_get(
"/auth_false", request_handler_factory(Mock(requires_auth=True), auth_handler)
)
app.router.add_get(
"/", request_handler_factory(Mock(requires_auth=False), auth_handler)
)
setup_bans(hass, app, 5)
remote_ip = ip_address("200.201.202.204")
@@ -120,7 +126,7 @@ async def test_failed_login_attempts_counter(hass, aiohttp_client):
@middleware
async def mock_auth(request, handler):
"""Mock auth middleware."""
if 'auth_true' in request.path:
if "auth_true" in request.path:
request[KEY_AUTHENTICATED] = True
else:
request[KEY_AUTHENTICATED] = False
@@ -130,18 +136,18 @@ async def test_failed_login_attempts_counter(hass, aiohttp_client):
client = await aiohttp_client(app)
resp = await client.get('/auth_false')
resp = await client.get("/auth_false")
assert resp.status == 401
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1
resp = await client.get('/auth_false')
resp = await client.get("/auth_false")
assert resp.status == 401
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
resp = await client.get('/')
resp = await client.get("/")
assert resp.status == 200
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
resp = await client.get('/auth_true')
resp = await client.get("/auth_true")
assert resp.status == 200
assert remote_ip not in app[KEY_FAILED_LOGIN_ATTEMPTS]
+60 -73
View File
@@ -9,39 +9,35 @@ from aiohttp.hdrs import (
ACCESS_CONTROL_REQUEST_HEADERS,
ACCESS_CONTROL_REQUEST_METHOD,
AUTHORIZATION,
ORIGIN
ORIGIN,
)
import pytest
from homeassistant.const import (
HTTP_HEADER_HA_AUTH
)
from homeassistant.const import HTTP_HEADER_HA_AUTH
from homeassistant.setup import async_setup_component
from homeassistant.components.http.cors import setup_cors
from homeassistant.components.http.view import HomeAssistantView
TRUSTED_ORIGIN = 'https://home-assistant.io'
TRUSTED_ORIGIN = "https://home-assistant.io"
async def test_cors_middleware_loaded_by_default(hass):
"""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': {}
})
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):
"""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']
}
})
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
@@ -55,65 +51,58 @@ async def mock_handler(request):
def client(loop, aiohttp_client):
"""Fixture to set up a web.Application."""
app = web.Application()
app.router.add_get('/', mock_handler)
app.router.add_get("/", mock_handler)
setup_cors(app, [TRUSTED_ORIGIN])
return loop.run_until_complete(aiohttp_client(app))
async def test_cors_requests(client):
"""Test cross origin requests."""
req = await client.get('/', headers={
ORIGIN: TRUSTED_ORIGIN
})
req = await client.get("/", headers={ORIGIN: TRUSTED_ORIGIN})
assert req.status == 200
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == \
TRUSTED_ORIGIN
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
})
req = await client.get(
"/", params={"api_password": "some-pass"}, headers={ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == 200
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == \
TRUSTED_ORIGIN
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
})
req = await client.get(
"/", headers={HTTP_HEADER_HA_AUTH: "some-pass", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == 200
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == \
TRUSTED_ORIGIN
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
})
req = await client.get(
"/", headers={AUTHORIZATION: "Bearer some-token", ORIGIN: TRUSTED_ORIGIN}
)
assert req.status == 200
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == \
TRUSTED_ORIGIN
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
async def test_cors_preflight_allowed(client):
"""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-ha-access'
})
req = await client.options(
"/",
headers={
ORIGIN: TRUSTED_ORIGIN,
ACCESS_CONTROL_REQUEST_METHOD: "GET",
ACCESS_CONTROL_REQUEST_HEADERS: "x-ha-access",
},
)
assert req.status == 200
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
assert req.headers[ACCESS_CONTROL_ALLOW_HEADERS] == \
HTTP_HEADER_HA_AUTH.upper()
assert req.headers[ACCESS_CONTROL_ALLOW_HEADERS] == HTTP_HEADER_HA_AUTH.upper()
async def test_cors_middleware_with_cors_allowed_view(hass):
"""Test that we can configure cors and have a cors_allowed view."""
class MyView(HomeAssistantView):
"""Test view that allows CORS."""
@@ -129,15 +118,13 @@ async def test_cors_middleware_with_cors_allowed_view(hass):
"""Test response."""
return "test"
assert await async_setup_component(hass, 'http', {
'http': {
'cors_allowed_origins': ['http://home-assistant.io']
}
})
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.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()
@@ -145,30 +132,30 @@ async def test_cors_middleware_with_cors_allowed_view(hass):
async def test_cors_works_with_frontend(hass, hass_client):
"""Test CORS works with the frontend."""
assert await async_setup_component(hass, 'frontend', {
'http': {
'cors_allowed_origins': ['http://home-assistant.io']
}
})
assert await async_setup_component(
hass,
"frontend",
{"http": {"cors_allowed_origins": ["http://home-assistant.io"]}},
)
client = await hass_client()
resp = await client.get('/')
resp = await client.get("/")
assert resp.status == 200
async def test_cors_on_static_files(hass, hass_client):
"""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))
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',
})
resp = await client.options(
"/something/__init__.py",
headers={
"origin": "http://www.example.com",
ACCESS_CONTROL_REQUEST_METHOD: "GET",
},
)
assert resp.status == 200
assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == \
'http://www.example.com'
assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com"
+24 -26
View File
@@ -11,17 +11,17 @@ from homeassistant.components.http.data_validator import RequestDataValidator
async def get_client(aiohttp_client, validator):
"""Generate a client that hits a view decorated with validator."""
app = web.Application()
app['hass'] = Mock(is_running=True)
app["hass"] = Mock(is_running=True)
class TestView(HomeAssistantView):
url = '/'
name = 'test'
url = "/"
name = "test"
requires_auth = False
@validator
async def post(self, request, data):
"""Test method."""
return b''
return b""
TestView().register(app, app.router)
client = await aiohttp_client(app)
@@ -31,42 +31,40 @@ async def get_client(aiohttp_client, validator):
async def test_validator(aiohttp_client):
"""Test the validator."""
client = await get_client(
aiohttp_client, RequestDataValidator(vol.Schema({
vol.Required('test'): str
})))
aiohttp_client, RequestDataValidator(vol.Schema({vol.Required("test"): str}))
)
resp = await client.post('/', json={
'test': 'bla'
})
resp = await client.post("/", json={"test": "bla"})
assert resp.status == 200
resp = await client.post('/', json={
'test': 100
})
resp = await client.post("/", json={"test": 100})
assert resp.status == 400
resp = await client.post('/')
resp = await client.post("/")
assert resp.status == 400
async def test_validator_allow_empty(aiohttp_client):
"""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))
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'
})
resp = await client.post("/", json={"test": "bla"})
assert resp.status == 200
resp = await client.post('/', json={
'test': 100
})
resp = await client.post("/", json={"test": 100})
assert resp.status == 400
resp = await client.post('/')
resp = await client.post("/")
assert resp.status == 200
+100 -107
View File
@@ -6,30 +6,26 @@ from unittest.mock import patch
from homeassistant.setup import async_setup_component
import homeassistant.components.http as http
from homeassistant.util.ssl import (
server_context_modern, server_context_intermediate)
from homeassistant.util.ssl import server_context_modern, server_context_intermediate
class TestView(http.HomeAssistantView):
"""Test the HTTP views."""
name = 'test'
url = '/hello'
name = "test"
url = "/hello"
async def get(self, request):
"""Return a get request."""
return 'hello'
return "hello"
async def test_registering_view_while_running(hass, aiohttp_client,
aiohttp_unused_port):
async def test_registering_view_while_running(
hass, aiohttp_client, aiohttp_unused_port
):
"""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: aiohttp_unused_port(),
}
}
hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: aiohttp_unused_port()}}
)
await hass.async_start()
@@ -42,161 +38,156 @@ class TestApiConfig(unittest.TestCase):
def test_api_base_url_with_domain(hass):
"""Test setting API URL with domain."""
api_config = http.ApiConfig('example.com')
assert api_config.base_url == 'http://example.com:8123'
api_config = http.ApiConfig("example.com")
assert api_config.base_url == "http://example.com:8123"
def test_api_base_url_with_ip(hass):
"""Test setting API URL with IP."""
api_config = http.ApiConfig('1.1.1.1')
assert api_config.base_url == 'http://1.1.1.1:8123'
api_config = http.ApiConfig("1.1.1.1")
assert api_config.base_url == "http://1.1.1.1:8123"
def test_api_base_url_with_ip_and_port(hass):
"""Test setting API URL with IP and port."""
api_config = http.ApiConfig('1.1.1.1', 8124)
assert api_config.base_url == 'http://1.1.1.1:8124'
api_config = http.ApiConfig("1.1.1.1", 8124)
assert api_config.base_url == "http://1.1.1.1:8124"
def test_api_base_url_with_protocol(hass):
"""Test setting API URL with protocol."""
api_config = http.ApiConfig('https://example.com')
assert api_config.base_url == 'https://example.com:8123'
api_config = http.ApiConfig("https://example.com")
assert api_config.base_url == "https://example.com:8123"
def test_api_base_url_with_protocol_and_port(hass):
"""Test setting API URL with protocol and port."""
api_config = http.ApiConfig('https://example.com', 433)
assert api_config.base_url == 'https://example.com:433'
api_config = http.ApiConfig("https://example.com", 433)
assert api_config.base_url == "https://example.com:433"
def test_api_base_url_with_ssl_enable(hass):
"""Test setting API URL with use_ssl enabled."""
api_config = http.ApiConfig('example.com', use_ssl=True)
assert api_config.base_url == 'https://example.com:8123'
api_config = http.ApiConfig("example.com", use_ssl=True)
assert api_config.base_url == "https://example.com:8123"
def test_api_base_url_with_ssl_enable_and_port(hass):
"""Test setting API URL with use_ssl enabled and port."""
api_config = http.ApiConfig('1.1.1.1', use_ssl=True, port=8888)
assert api_config.base_url == 'https://1.1.1.1:8888'
api_config = http.ApiConfig("1.1.1.1", use_ssl=True, port=8888)
assert api_config.base_url == "https://1.1.1.1:8888"
def test_api_base_url_with_protocol_and_ssl_enable(hass):
"""Test setting API URL with specific protocol and use_ssl enabled."""
api_config = http.ApiConfig('http://example.com', use_ssl=True)
assert api_config.base_url == 'http://example.com:8123'
api_config = http.ApiConfig("http://example.com", use_ssl=True)
assert api_config.base_url == "http://example.com:8123"
def test_api_base_url_removes_trailing_slash(hass):
"""Test a trialing slash is removed when setting the API URL."""
api_config = http.ApiConfig('http://example.com/')
assert api_config.base_url == 'http://example.com:8123'
api_config = http.ApiConfig("http://example.com/")
assert api_config.base_url == "http://example.com:8123"
async def test_api_base_url_with_domain(hass):
"""Test setting API URL."""
result = await async_setup_component(hass, 'http', {
'http': {
'base_url': 'example.com'
}
})
result = await async_setup_component(
hass, "http", {"http": {"base_url": "example.com"}}
)
assert result
assert hass.config.api.base_url == 'http://example.com'
assert hass.config.api.base_url == "http://example.com"
async def test_api_base_url_with_ip(hass):
"""Test setting api url."""
result = await async_setup_component(hass, 'http', {
'http': {
'server_host': '1.1.1.1'
}
})
result = await async_setup_component(
hass, "http", {"http": {"server_host": "1.1.1.1"}}
)
assert result
assert hass.config.api.base_url == 'http://1.1.1.1:8123'
assert hass.config.api.base_url == "http://1.1.1.1:8123"
async def test_api_base_url_with_ip_port(hass):
"""Test setting api url."""
result = await async_setup_component(hass, 'http', {
'http': {
'base_url': '1.1.1.1:8124'
}
})
result = await async_setup_component(
hass, "http", {"http": {"base_url": "1.1.1.1:8124"}}
)
assert result
assert hass.config.api.base_url == 'http://1.1.1.1:8124'
assert hass.config.api.base_url == "http://1.1.1.1:8124"
async def test_api_no_base_url(hass):
"""Test setting api url."""
result = await async_setup_component(hass, 'http', {
'http': {
}
})
result = await async_setup_component(hass, "http", {"http": {}})
assert result
assert hass.config.api.base_url == 'http://127.0.0.1:8123'
assert hass.config.api.base_url == "http://127.0.0.1:8123"
async def test_api_base_url_removes_trailing_slash(hass):
"""Test setting api url."""
result = await async_setup_component(hass, 'http', {
'http': {
'base_url': 'https://example.com/'
}
})
result = await async_setup_component(
hass, "http", {"http": {"base_url": "https://example.com/"}}
)
assert result
assert hass.config.api.base_url == 'https://example.com'
assert hass.config.api.base_url == "https://example.com"
async def test_not_log_password(hass, aiohttp_client, caplog, legacy_auth):
"""Test access with password doesn't get logged."""
assert await async_setup_component(hass, 'api', {
'http': {}
})
assert await async_setup_component(hass, "api", {"http": {}})
client = await aiohttp_client(hass.http.app)
logging.getLogger('aiohttp.access').setLevel(logging.INFO)
logging.getLogger("aiohttp.access").setLevel(logging.INFO)
resp = await client.get('/api/', params={
'api_password': 'test-password'
})
resp = await client.get("/api/", params={"api_password": "test-password"})
assert resp.status == 200
logs = caplog.text
# Ensure we don't log API passwords
assert '/api/' in logs
assert 'some-pass' not in logs
assert "/api/" in logs
assert "some-pass" not in logs
async def test_proxy_config(hass):
"""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
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):
"""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
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):
"""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
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):
"""Test default ssl profile."""
assert await async_setup_component(hass, 'http', {}) is True
assert await async_setup_component(hass, "http", {}) is True
hass.http.ssl_certificate = 'bla'
hass.http.ssl_certificate = "bla"
with patch('ssl.SSLContext.load_cert_chain'), \
patch('homeassistant.util.ssl.server_context_modern',
side_effect=server_context_modern) as mock_context:
with patch("ssl.SSLContext.load_cert_chain"), patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
) as mock_context:
await hass.async_start()
await hass.async_block_till_done()
@@ -205,17 +196,19 @@ async def test_ssl_profile_defaults_modern(hass):
async def test_ssl_profile_change_intermediate(hass):
"""Test setting ssl profile to intermediate."""
assert await async_setup_component(hass, 'http', {
'http': {
'ssl_profile': 'intermediate'
}
}) is True
assert (
await async_setup_component(
hass, "http", {"http": {"ssl_profile": "intermediate"}}
)
is True
)
hass.http.ssl_certificate = 'bla'
hass.http.ssl_certificate = "bla"
with patch('ssl.SSLContext.load_cert_chain'), \
patch('homeassistant.util.ssl.server_context_intermediate',
side_effect=server_context_intermediate) as mock_context:
with patch("ssl.SSLContext.load_cert_chain"), patch(
"homeassistant.util.ssl.server_context_intermediate",
side_effect=server_context_intermediate,
) as mock_context:
await hass.async_start()
await hass.async_block_till_done()
@@ -224,17 +217,17 @@ async def test_ssl_profile_change_intermediate(hass):
async def test_ssl_profile_change_modern(hass):
"""Test setting ssl profile to modern."""
assert await async_setup_component(hass, 'http', {
'http': {
'ssl_profile': 'modern'
}
}) is True
assert (
await async_setup_component(hass, "http", {"http": {"ssl_profile": "modern"}})
is True
)
hass.http.ssl_certificate = 'bla'
hass.http.ssl_certificate = "bla"
with patch('ssl.SSLContext.load_cert_chain'), \
patch('homeassistant.util.ssl.server_context_modern',
side_effect=server_context_modern) as mock_context:
with patch("ssl.SSLContext.load_cert_chain"), patch(
"homeassistant.util.ssl.server_context_modern",
side_effect=server_context_modern,
) as mock_context:
await hass.async_start()
await hass.async_block_till_done()
+26 -34
View File
@@ -15,94 +15,86 @@ async def mock_handler(request):
async def test_ignore_x_forwarded_for(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
app.router.add_get("/", mock_handler)
setup_real_ip(app, False, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255'
})
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
text = await resp.text()
assert text != '255.255.255.255'
assert text != "255.255.255.255"
async def test_use_x_forwarded_for_without_trusted_proxy(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
app.router.add_get("/", mock_handler)
setup_real_ip(app, True, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255'
})
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
text = await resp.text()
assert text != '255.255.255.255'
assert text != "255.255.255.255"
async def test_use_x_forwarded_for_with_trusted_proxy(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, True, [ip_network('127.0.0.1')])
app.router.add_get("/", mock_handler)
setup_real_ip(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'
})
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
text = await resp.text()
assert text == '255.255.255.255'
assert text == "255.255.255.255"
async def test_use_x_forwarded_for_with_untrusted_proxy(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, True, [ip_network('1.1.1.1')])
app.router.add_get("/", mock_handler)
setup_real_ip(app, True, [ip_network("1.1.1.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255'
})
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
text = await resp.text()
assert text != '255.255.255.255'
assert text != "255.255.255.255"
async def test_use_x_forwarded_for_with_spoofed_header(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, True, [ip_network('127.0.0.1')])
app.router.add_get("/", mock_handler)
setup_real_ip(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'
})
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"}
)
assert resp.status == 200
text = await resp.text()
assert text == '255.255.255.255'
assert text == "255.255.255.255"
async def test_use_x_forwarded_for_with_nonsense_header(aiohttp_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, True, [ip_network('127.0.0.1')])
app.router.add_get("/", mock_handler)
setup_real_ip(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: 'This value is invalid'
})
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "This value is invalid"}
)
assert resp.status == 200
text = await resp.text()
assert text == '127.0.0.1'
assert text == "127.0.0.1"
+11 -11
View File
@@ -2,12 +2,17 @@
from unittest.mock import Mock
from aiohttp.web_exceptions import (
HTTPInternalServerError, HTTPBadRequest, HTTPUnauthorized)
HTTPInternalServerError,
HTTPBadRequest,
HTTPUnauthorized,
)
import pytest
import voluptuous as vol
from homeassistant.components.http.view import (
HomeAssistantView, request_handler_factory)
HomeAssistantView,
request_handler_factory,
)
from homeassistant.exceptions import ServiceNotFound, Unauthorized
from tests.common import mock_coro_func
@@ -16,10 +21,7 @@ from tests.common import mock_coro_func
@pytest.fixture
def mock_request():
"""Mock a request."""
return Mock(
app={'hass': Mock(is_running=True)},
match_info={},
)
return Mock(app={"hass": Mock(is_running=True)}, match_info={})
async def test_invalid_json(caplog):
@@ -36,8 +38,7 @@ async def test_handling_unauthorized(mock_request):
"""Test handling unauth exceptions."""
with pytest.raises(HTTPUnauthorized):
await request_handler_factory(
Mock(requires_auth=False),
mock_coro_func(exception=Unauthorized)
Mock(requires_auth=False), mock_coro_func(exception=Unauthorized)
)(mock_request)
@@ -45,8 +46,7 @@ async def test_handling_invalid_data(mock_request):
"""Test handling unauth exceptions."""
with pytest.raises(HTTPBadRequest):
await request_handler_factory(
Mock(requires_auth=False),
mock_coro_func(exception=vol.Invalid('yo'))
Mock(requires_auth=False), mock_coro_func(exception=vol.Invalid("yo"))
)(mock_request)
@@ -55,5 +55,5 @@ async def test_handling_service_not_found(mock_request):
with pytest.raises(HTTPInternalServerError):
await request_handler_factory(
Mock(requires_auth=False),
mock_coro_func(exception=ServiceNotFound('test', 'test'))
mock_coro_func(exception=ServiceNotFound("test", "test")),
)(mock_request)