From 9c02de44f12e0d0f42e10f38275f6a8db01d10d9 Mon Sep 17 00:00:00 2001 From: Kyle Fritz Date: Sun, 29 Nov 2026 23:52:07 -0500 Subject: [PATCH 1/2] fix(auth): stop retrying a refresh token Wyze rejected (2002) When Wyze rejects the stored refresh token with code 2002 ("refresh token is error"), refresh() raised a generic UnknownApiError and left the token as it was. Every device poll goes through refresh_if_should(), so each poll tried the same dead token again, about one request every 3 seconds across a typical device list. After a few hours Wyze rate-limits the IP, and logins from it get HTTP 429 too, so the user can't sign in again until the block lifts. refresh() now raises RefreshTokenError on 2002 and remembers the rejected refresh token. refresh_if_should() and refresh() raise RefreshTokenError straight away, without calling Wyze, for as long as the current token still carries it. A new login replaces the token and clears the state. RefreshTokenError subclasses AccessTokenError, so callers that already start a re-login on AccessTokenError (ha-wyzeapi's setup and token_exception_handler) handle it with no changes. Refs SecKatie/ha-wyzeapi#999 Co-Authored-By: Claude Opus 5.5 --- src/wyzeapy/exceptions.py | 9 +++++ src/wyzeapy/types.py | 1 + src/wyzeapy/wyze_auth_lib.py | 35 +++++++++++++++++- tests/test_wyze_auth_lib.py | 69 ++++++++++++++++++++++++++++++++++++ 4 files changed, 113 insertions(+), 1 deletion(-) diff --git a/src/wyzeapy/exceptions.py b/src/wyzeapy/exceptions.py index eb00f52f..68b2c45e 100644 --- a/src/wyzeapy/exceptions.py +++ b/src/wyzeapy/exceptions.py @@ -24,6 +24,15 @@ class AccessTokenError(Exception): """Raised when the access token is invalid or has expired.""" +class RefreshTokenError(AccessTokenError): + """Raised when Wyze rejects the refresh token (code 2002). + + Refreshing again cannot succeed; the caller has to log in again with the + account's credentials. Subclasses AccessTokenError so existing handlers + that start a re-login on AccessTokenError keep working. + """ + + class LoginError(Exception): """Raised during authentication or login failures.""" diff --git a/src/wyzeapy/types.py b/src/wyzeapy/types.py index 669b1c37..57dc446b 100644 --- a/src/wyzeapy/types.py +++ b/src/wyzeapy/types.py @@ -179,6 +179,7 @@ class ResponseCodes(Enum): SUCCESS = "1" PARAMETER_ERROR = "1001" ACCESS_TOKEN_ERROR = "2001" + REFRESH_TOKEN_ERROR = "2002" DEVICE_OFFLINE = "3019" diff --git a/src/wyzeapy/wyze_auth_lib.py b/src/wyzeapy/wyze_auth_lib.py index 9818f000..e9ad3c62 100644 --- a/src/wyzeapy/wyze_auth_lib.py +++ b/src/wyzeapy/wyze_auth_lib.py @@ -30,7 +30,9 @@ UnknownApiError, TwoFactorAuthenticationEnabled, AccessTokenError, + RefreshTokenError, ) +from .types import ResponseCodes from .utils import create_password, check_for_errors_standard _LOGGER = logging.getLogger(__name__) @@ -172,6 +174,10 @@ def __init__( self.two_factor_type = None self.refresh_lock = asyncio.Lock() self.token_callback = token_callback + # The refresh token Wyze last rejected with code 2002. While the current + # token still carries it, refreshing again cannot work, so we fail fast + # instead of calling Wyze. A new login replaces the token and clears this. + self._rejected_refresh_token: Optional[str] = None @classmethod async def create( @@ -350,20 +356,42 @@ def should_refresh(self) -> bool: return time.time() >= self.token.refresh_time async def refresh_if_should(self): - """Refresh the token proactively if expired or past refresh_time.""" + """Refresh the token proactively if expired or past refresh_time. + + Raises: + RefreshTokenError: Without calling Wyze, if Wyze already rejected + the current refresh token. Every device poll goes through here, + so retrying a dead token would hit Wyze every few seconds until + it rate-limits the caller's IP (HTTP 429 on login too). + """ + self._raise_if_refresh_token_rejected() if self.should_refresh or self.token.expired: async with self.refresh_lock: if self.should_refresh or self.token.expired: _LOGGER.debug("Should refresh. Refreshing...") await self.refresh() + def _raise_if_refresh_token_rejected(self) -> None: + if ( + self._rejected_refresh_token is not None + and self.token is not None + and self.token.refresh_token == self._rejected_refresh_token + ): + raise RefreshTokenError( + ResponseCodes.REFRESH_TOKEN_ERROR.value, + "Wyze rejected the refresh token; log in again", + ) + async def refresh(self) -> None: """Exchange the refresh token for a new access token and update internal Token. Raises: + RefreshTokenError: If Wyze rejects the refresh token (code 2002), or + already rejected it earlier; log in again to recover. AccessTokenError: If refresh fails due to invalid refresh token. UnknownApiError: For other errors during refresh. """ + self._raise_if_refresh_token_rejected() payload = { "phone_id": PHONE_ID, "app_name": APP_NAME, @@ -385,6 +413,11 @@ async def refresh(self) -> None: json=payload, ) response_json = await response.json() + if str(response_json.get("code")) == ResponseCodes.REFRESH_TOKEN_ERROR.value: + self._rejected_refresh_token = self.token.refresh_token + raise RefreshTokenError( + ResponseCodes.REFRESH_TOKEN_ERROR.value, response_json.get("msg") + ) check_for_errors_standard(self, response_json) self.token.access_token = response_json["data"]["access_token"] diff --git a/tests/test_wyze_auth_lib.py b/tests/test_wyze_auth_lib.py index 61707e50..fbb376f5 100644 --- a/tests/test_wyze_auth_lib.py +++ b/tests/test_wyze_auth_lib.py @@ -8,6 +8,7 @@ Token, TwoFactorAuthenticationEnabled, AccessTokenError, + RefreshTokenError, UnknownApiError, get_ssl_context, async_get_ssl_context, @@ -323,6 +324,74 @@ async def test_refresh_if_should_false(self): await auth_lib.refresh_if_should() auth_lib.refresh.assert_not_awaited() + def _mock_refresh_response(self, mock_session, body): + mock_response = AsyncMock() + mock_response.json.return_value = body + post = mock_session.return_value.__aenter__.return_value.post + post.return_value = mock_response + return post + + @patch("wyzeapy.wyze_auth_lib.ClientSession") + async def test_refresh_token_rejected_raises_refresh_token_error( + self, mock_session + ): + self._mock_refresh_response( + mock_session, {"code": "2002", "msg": "refresh token is error"} + ) + auth_lib = WyzeAuthLib( + token=Token("old_access", "dead_refresh", refresh_time=time.time() - 100) + ) + + with self.assertRaises(RefreshTokenError) as ctx: + await auth_lib.refresh() + # Existing callers that start a re-login on AccessTokenError still do. + self.assertIsInstance(ctx.exception, AccessTokenError) + + @patch("wyzeapy.wyze_auth_lib.ClientSession") + async def test_rejected_refresh_token_is_not_retried(self, mock_session): + post = self._mock_refresh_response( + mock_session, {"code": "2002", "msg": "refresh token is error"} + ) + auth_lib = WyzeAuthLib( + token=Token("old_access", "dead_refresh", refresh_time=time.time() - 100) + ) + + with self.assertRaises(RefreshTokenError): + await auth_lib.refresh_if_should() + # Every device poll calls refresh_if_should; none of them may reach Wyze. + for _ in range(5): + with self.assertRaises(RefreshTokenError): + await auth_lib.refresh_if_should() + with self.assertRaises(RefreshTokenError): + await auth_lib.refresh() + self.assertEqual(post.call_count, 1) + + @patch("wyzeapy.wyze_auth_lib.ClientSession") + async def test_new_login_clears_rejected_refresh_token(self, mock_session): + self._mock_refresh_response( + mock_session, {"code": "2002", "msg": "refresh token is error"} + ) + auth_lib = WyzeAuthLib( + token=Token("old_access", "dead_refresh", refresh_time=time.time() - 100) + ) + with self.assertRaises(RefreshTokenError): + await auth_lib.refresh() + + # A fresh login hands us a new token; refreshing works again. + auth_lib.token = Token( + "new_access", "new_refresh", refresh_time=time.time() - 100 + ) + auth_lib.token_callback = AsyncMock() + self._mock_refresh_response( + mock_session, + { + "code": "1", + "data": {"access_token": "newer_access", "refresh_token": "newer"}, + }, + ) + await auth_lib.refresh_if_should() + self.assertEqual(auth_lib.token.access_token, "newer_access") + def test_sanitize(self): auth_lib = WyzeAuthLib() data = { From 9f7310cf58a8a5ce630560d9ead42276ab500495 Mon Sep 17 00:00:00 2001 From: Kyle Fritz Date: Mon, 30 Nov 2026 00:10:01 -0500 Subject: [PATCH 2/2] fix(auth): record the refresh token the failed request sent An overlapping refresh (BaseService._monitoring_profile_state_status calls refresh() without refresh_lock) can replace self.token with a valid token while a 2002 response is still in flight. Recording self.token then marked the new, valid token as rejected and blocked every later refresh. Record payload["refresh_token"] instead, and cover that ordering in a test. Co-Authored-By: Claude Opus 5.5 --- src/wyzeapy/wyze_auth_lib.py | 4 +++- tests/test_wyze_auth_lib.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/wyzeapy/wyze_auth_lib.py b/src/wyzeapy/wyze_auth_lib.py index e9ad3c62..8d547854 100644 --- a/src/wyzeapy/wyze_auth_lib.py +++ b/src/wyzeapy/wyze_auth_lib.py @@ -414,7 +414,9 @@ async def refresh(self) -> None: ) response_json = await response.json() if str(response_json.get("code")) == ResponseCodes.REFRESH_TOKEN_ERROR.value: - self._rejected_refresh_token = self.token.refresh_token + # Record the token this request sent, not self.token: an overlapping + # refresh may already have replaced it with a valid one. + self._rejected_refresh_token = payload["refresh_token"] raise RefreshTokenError( ResponseCodes.REFRESH_TOKEN_ERROR.value, response_json.get("msg") ) diff --git a/tests/test_wyze_auth_lib.py b/tests/test_wyze_auth_lib.py index fbb376f5..75fd7980 100644 --- a/tests/test_wyze_auth_lib.py +++ b/tests/test_wyze_auth_lib.py @@ -392,6 +392,35 @@ async def test_new_login_clears_rejected_refresh_token(self, mock_session): await auth_lib.refresh_if_should() self.assertEqual(auth_lib.token.access_token, "newer_access") + @patch("wyzeapy.wyze_auth_lib.ClientSession") + async def test_late_rejection_does_not_poison_a_newer_token(self, mock_session): + auth_lib = WyzeAuthLib( + token=Token("old_access", "dead_refresh", refresh_time=time.time() - 100) + ) + + async def overlapping_refresh_wins_first(): + # Another refresh (e.g. BaseService._monitoring_profile_state_status, + # which does not take refresh_lock) succeeds while this request is in + # flight, then this request's 2002 arrives. + auth_lib.token.access_token = "valid_access" + auth_lib.token.refresh_token = "valid_refresh" + return {"code": "2002", "msg": "refresh token is error"} + + mock_response = AsyncMock() + mock_response.json.side_effect = overlapping_refresh_wins_first + mock_session.return_value.__aenter__.return_value.post.return_value = ( + mock_response + ) + + with self.assertRaises(RefreshTokenError): + await auth_lib.refresh() + + # The valid token from the overlapping refresh must still be usable. + auth_lib.refresh = AsyncMock() + auth_lib.token.expired = True + await auth_lib.refresh_if_should() + auth_lib.refresh.assert_awaited_once() + def test_sanitize(self): auth_lib = WyzeAuthLib() data = {