Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/wyzeapy/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
1 change: 1 addition & 0 deletions src/wyzeapy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ class ResponseCodes(Enum):
SUCCESS = "1"
PARAMETER_ERROR = "1001"
ACCESS_TOKEN_ERROR = "2001"
REFRESH_TOKEN_ERROR = "2002"
DEVICE_OFFLINE = "3019"


Expand Down
37 changes: 36 additions & 1 deletion src/wyzeapy/wyze_auth_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -385,6 +413,13 @@ async def refresh(self) -> None:
json=payload,
)
response_json = await response.json()
if str(response_json.get("code")) == ResponseCodes.REFRESH_TOKEN_ERROR.value:
# 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")
)
check_for_errors_standard(self, response_json)

self.token.access_token = response_json["data"]["access_token"]
Expand Down
98 changes: 98 additions & 0 deletions tests/test_wyze_auth_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Token,
TwoFactorAuthenticationEnabled,
AccessTokenError,
RefreshTokenError,
UnknownApiError,
get_ssl_context,
async_get_ssl_context,
Expand Down Expand Up @@ -323,6 +324,103 @@ 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")

@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 = {
Expand Down
Loading