2018-02-15 21:06:14 +00:00
|
|
|
"""Test real IP middleware."""
|
|
|
|
from aiohttp import web
|
|
|
|
from aiohttp.hdrs import X_FORWARDED_FOR
|
2018-06-28 13:16:11 +00:00
|
|
|
from ipaddress import ip_network
|
2018-02-15 21:06:14 +00:00
|
|
|
|
|
|
|
from homeassistant.components.http.real_ip import setup_real_ip
|
|
|
|
from homeassistant.components.http.const import KEY_REAL_IP
|
|
|
|
|
|
|
|
|
2018-03-09 01:51:49 +00:00
|
|
|
async def mock_handler(request):
|
2018-02-15 21:06:14 +00:00
|
|
|
"""Handler that returns the real IP as text."""
|
|
|
|
return web.Response(text=str(request[KEY_REAL_IP]))
|
|
|
|
|
|
|
|
|
2018-03-15 20:49:49 +00:00
|
|
|
async def test_ignore_x_forwarded_for(aiohttp_client):
|
2018-02-15 21:06:14 +00:00
|
|
|
"""Test that we get the IP from the transport."""
|
|
|
|
app = web.Application()
|
|
|
|
app.router.add_get('/', mock_handler)
|
2018-06-28 13:16:11 +00:00
|
|
|
setup_real_ip(app, False, [])
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-03-15 20:49:49 +00:00
|
|
|
mock_api_client = await aiohttp_client(app)
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-03-09 01:51:49 +00:00
|
|
|
resp = await mock_api_client.get('/', headers={
|
2018-02-15 21:06:14 +00:00
|
|
|
X_FORWARDED_FOR: '255.255.255.255'
|
|
|
|
})
|
|
|
|
assert resp.status == 200
|
2018-03-09 01:51:49 +00:00
|
|
|
text = await resp.text()
|
2018-02-15 21:06:14 +00:00
|
|
|
assert text != '255.255.255.255'
|
|
|
|
|
|
|
|
|
2018-06-28 13:16:11 +00:00
|
|
|
async def test_use_x_forwarded_for_without_trusted_proxy(aiohttp_client):
|
2018-02-15 21:06:14 +00:00
|
|
|
"""Test that we get the IP from the transport."""
|
|
|
|
app = web.Application()
|
|
|
|
app.router.add_get('/', mock_handler)
|
2018-06-28 13:16:11 +00:00
|
|
|
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'
|
|
|
|
})
|
|
|
|
assert resp.status == 200
|
|
|
|
text = await resp.text()
|
|
|
|
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')])
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-03-15 20:49:49 +00:00
|
|
|
mock_api_client = await aiohttp_client(app)
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-03-09 01:51:49 +00:00
|
|
|
resp = await mock_api_client.get('/', headers={
|
2018-02-15 21:06:14 +00:00
|
|
|
X_FORWARDED_FOR: '255.255.255.255'
|
|
|
|
})
|
|
|
|
assert resp.status == 200
|
2018-03-09 01:51:49 +00:00
|
|
|
text = await resp.text()
|
2018-02-15 21:06:14 +00:00
|
|
|
assert text == '255.255.255.255'
|