diff --git a/homeassistant/helpers/config_entry_oauth2_flow.py b/homeassistant/helpers/config_entry_oauth2_flow.py index 0a6356d310d8..552fa29eb864 100644 --- a/homeassistant/helpers/config_entry_oauth2_flow.py +++ b/homeassistant/helpers/config_entry_oauth2_flow.py @@ -13,7 +13,7 @@ from collections.abc import Awaitable, Callable import logging import secrets import time -from typing import Any, cast +from typing import Any, Optional, cast from aiohttp import client, web import async_timeout @@ -437,7 +437,10 @@ class OAuth2AuthorizeCallbackView(http.HomeAssistantView): state = _decode_jwt(hass, request.query["state"]) if state is None: - return web.Response(text="Invalid state") + return web.Response( + text="Invalid state. Is My Home Assistant configured to go to the right instance?", + status=400, + ) user_input: dict[str, Any] = {"state": state} @@ -538,7 +541,10 @@ def _encode_jwt(hass: HomeAssistant, data: dict) -> str: @callback def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict | None: """JWT encode data.""" - secret = cast(str, hass.data.get(DATA_JWT_SECRET)) + secret = cast(Optional[str], hass.data.get(DATA_JWT_SECRET)) + + if secret is None: + return None try: return jwt.decode(encoded, secret, algorithms=["HS256"]) diff --git a/tests/helpers/test_config_entry_oauth2_flow.py b/tests/helpers/test_config_entry_oauth2_flow.py index f64525ecdd33..3b94f3d80c1e 100644 --- a/tests/helpers/test_config_entry_oauth2_flow.py +++ b/tests/helpers/test_config_entry_oauth2_flow.py @@ -726,3 +726,10 @@ async def test_oauth_session_refresh_failure( session = config_entry_oauth2_flow.OAuth2Session(hass, config_entry, local_impl) with pytest.raises(aiohttp.client_exceptions.ClientResponseError): await session.async_request("post", "https://example.com") + + +async def test_oauth2_without_secret_init(local_impl, hass_client_no_auth): + """Check authorize callback without secret initalizated.""" + client = await hass_client_no_auth() + resp = await client.get("/auth/external/callback?code=abcd&state=qwer") + assert resp.status == 400