Skip to content

fix(auth): stop retrying a refresh token Wyze rejected (2002) - #407

Open
kylefritz wants to merge 2 commits into
SecKatie:mainfrom
kylefritz:fix/stop-retrying-rejected-refresh-token
Open

kylefritz wants to merge 2 commits into
SecKatie:mainfrom
kylefritz:fix/stop-retrying-rejected-refresh-token

Conversation

@kylefritz

Copy link
Copy Markdown

Fixes the retry loop in SecKatie/ha-wyzeapi#999.

The problem

When Wyze rejects the stored refresh token with code 2002 ("refresh token is error"), refresh() raises a generic UnknownApiError and keeps the token. Every device poll goes through refresh_if_should(), and UpdateManager logs and swallows the error, so each poll tries the same dead token again. That comes to about one request every 3 seconds across a normal device list.

On our Home Assistant install this ran for about three days before anyone noticed: 88,989 failed refreshes. Then Wyze rate-limited the home IP. Logins from that IP got HTTP 429 even with made-up credentials, so nobody could sign in again until the block lifted. #999 reports the same thing (about 17,500 attempts in 16 hours).

The fix

  • Add ResponseCodes.REFRESH_TOKEN_ERROR = "2002" and a new RefreshTokenError.
  • On 2002, refresh() remembers which refresh token Wyze rejected and raises RefreshTokenError.
  • While the current token still carries that refresh token, refresh_if_should() and refresh() raise RefreshTokenError straight away without calling Wyze. Polling keeps running but sends nothing to Wyze, so the IP doesn't get rate-limited.
  • A new login (get_token_with_username_password, get_token_with_2fa, or a caller setting a new Token) replaces the refresh token, which clears the state with no extra bookkeeping.
  • RefreshTokenError subclasses AccessTokenError. ha-wyzeapi's setup (except AccessTokenError → ConfigEntryAuthFailed) and its token_exception_handler already start a re-login on AccessTokenError, so they handle this with no changes. ha-wyzeapi pins wyzeapy>=0.8.1,<0.9.0, so a patch release reaches users without an integration release.

Not in this PR

  • UpdateManager still logs a traceback each time a device poll fails. Those are now local log lines only, with no network calls, but quieter logging there would be a reasonable follow-up.
  • Polling that only goes through UpdateManager doesn't raise into Home Assistant, so the re-login prompt shows up the next time something calls through a token_exception_handler path, or at the next restart (setup). Starting re-login straight from the poller would need a hook from wyzeapy to the integration. That's a larger change and I've left it out here.

Tests

Three new tests in tests/test_wyze_auth_lib.py:

  • a 2002 response raises RefreshTokenError, which is also an AccessTokenError;
  • after a rejection, more refresh_if_should() and refresh() calls raise without a second request to Wyze (the mocked post is called exactly once);
  • a new token clears the state, and refreshing works again.

pytest: 281 passed. ruff check and ruff format --check are clean.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
@kylefritz
kylefritz requested a review from SecKatie as a code owner November 30, 2026 04:52
@CLAassistant

CLAassistant commented Nov 30, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T04:55:17.350284Z 9c02de4 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9c02de44f1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/wyzeapy/wyze_auth_lib.py Outdated
)
response_json = await response.json()
if str(response_json.get("code")) == ResponseCodes.REFRESH_TOKEN_ERROR.value:
self._rejected_refresh_token = self.token.refresh_token

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cache the refresh token that was actually rejected

If overlapping refreshes produce a successful response followed by a delayed 2002 response, this assignment records the newly issued, valid refresh token as rejected instead of the token sent in the failed request. This overlap is possible through BaseService._monitoring_profile_state_status() (src/wyzeapy/services/base_service.py:730–731), which calls refresh() without taking refresh_lock. Every subsequent refresh_if_should() then fails locally despite the successful authentication, disabling device updates until reauthentication or restart. Associate the rejection with payload['refresh_token'] rather than reading mutable token state after the awaits, and cover this response ordering in a regression test.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, fixed in the latest commit: the rejection is now recorded from payload["refresh_token"] (the token this request actually sent), so a late 2002 can no longer mark a newer, valid token as rejected. Added test_late_rejection_does_not_poison_a_newer_token, which reproduces the overlap (a valid token lands while the 2002 is in flight). It fails on the old line and passes now; full suite 282 passed.

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 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Refresh token rejected (2002) causes a retry loop every ~3 s and gets the home IP rate-limited (429) at login

2 participants