Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up signing paths #93127

Merged
merged 4 commits into from
May 17, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 9 additions & 7 deletions homeassistant/components/http/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
from aiohttp import hdrs
from aiohttp.web import Application, Request, StreamResponse, middleware
import jwt
from jwt import api_jws
from yarl import URL

from homeassistant.auth import jwt_wrapper
from homeassistant.auth.const import GROUP_ID_READ_ONLY
from homeassistant.auth.models import User
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.json import json_bytes
from homeassistant.helpers.storage import Store
from homeassistant.util import dt as dt_util
from homeassistant.util.network import is_local
Expand Down Expand Up @@ -61,19 +63,19 @@ def async_sign_path(

url = URL(path)
now = dt_util.utcnow()
now_timestamp = int(now.timestamp())
expiration_timestamp = now_timestamp + int(expiration.total_seconds())
Copy link
Member Author

@bdraco bdraco May 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JWT wants timestamps as int. Doing this here instead and passing to api_jws avoids all the expensive conversions and copies since our times are always in UTC

params = [itm for itm in url.query.items() if itm[0] not in SAFE_QUERY_PARAMS]
encoded = jwt.encode(
json_payload = json_bytes(
{
"iss": refresh_token_id,
"path": url.path,
"params": params,
"iat": now,
"exp": now + expiration,
},
secret,
algorithm="HS256",
"iat": now_timestamp,
"exp": expiration_timestamp,
}
)

encoded = api_jws.encode(json_payload, secret, "HS256")
params.append((SIGN_QUERY_PARAM, encoded))
url = url.with_query(params)
return f"{url.path}?{url.query_string}"
Expand Down