Allow creating signed urls (#17759)

* Allow creating signed urls

* Fix parameter

* Lint
This commit is contained in:
Paulus Schoutsen authored and Pascal Vizeli committed 2018-10-25 16:44:57 +02:00
1 parent b5284aa445
commit 312d49caec
5 files changed
+174 -4

No files matched your search

+66
View File
@@ -6,16 +6,39 @@ import logging
from aiohttp import hdrs
from aiohttp.web import middleware
import jwt
from homeassistant.core import callback
from homeassistant.const import HTTP_HEADER_HA_AUTH
from homeassistant.auth.util import generate_secret
from homeassistant.util import dt as dt_util
from .const import KEY_AUTHENTICATED, KEY_REAL_IP
DATA_API_PASSWORD = 'api_password'
DATA_SIGN_SECRET = 'http.auth.sign_secret'
SIGN_QUERY_PARAM = 'authSig'
_LOGGER = logging.getLogger(__name__)
@callback
def async_sign_path(hass, refresh_token_id, path, expiration):
"""Sign a path for temporary access without auth header."""
secret = hass.data.get(DATA_SIGN_SECRET)
if secret is None:
secret = hass.data[DATA_SIGN_SECRET] = generate_secret()
now = dt_util.utcnow()
return "{}?{}={}".format(path, SIGN_QUERY_PARAM, jwt.encode({
'iss': refresh_token_id,
'path': path,
'iat': now,
'exp': now + expiration,
}, secret, algorithm='HS256').decode())
@callback
def setup_auth(app, trusted_networks, use_auth,
support_legacy=False, api_password=None):
@@ -43,6 +66,12 @@ def setup_auth(app, trusted_networks, use_auth,
# it included both use_auth and api_password Basic auth
authenticated = True
# We first start with a string check to avoid parsing query params
# for every request.
elif (request.method == "GET" and SIGN_QUERY_PARAM in request.query and
await async_validate_signed_request(request)):
authenticated = True
elif (legacy_auth and HTTP_HEADER_HA_AUTH in request.headers and
hmac.compare_digest(
api_password.encode('utf-8'),
@@ -131,3 +160,40 @@ async def async_validate_auth_header(request, api_password=None):
password.encode('utf-8'))
return False
async def async_validate_signed_request(request):
"""Validate a signed request."""
hass = request.app['hass']
secret = hass.data.get(DATA_SIGN_SECRET)
if secret is None:
return False
signature = request.query.get(SIGN_QUERY_PARAM)
if signature is None:
return False
try:
claims = jwt.decode(
signature,
secret,
algorithms=['HS256'],
options={'verify_iss': False}
)
except jwt.InvalidTokenError:
return False
if claims['path'] != request.path:
return False
refresh_token = await hass.auth.async_get_refresh_token(claims['iss'])
if refresh_token is None:
return False
request['hass_refresh_token'] = refresh_token
request['hass_user'] = refresh_token.user
return True