From 2a2c03a153131aa0698fb078261c04de9c07ac1d Mon Sep 17 00:00:00 2001 From: proscar87 Date: Fri, 7 Aug 2026 13:34:05 -0600 Subject: [PATCH 1/2] Raise a typed error when Growatt refuses a login as rate limited Reworked after @johanzander pointed out the premise was wrong: Growatt does not signal 507 as an HTTP status. The request succeeds with HTTP 200 and the body carries `success: false` with `msg: "507"`, which is the only shape that can produce the `ConfigEntryError: Growatt login failed: 507` traceback in home-assistant/core#176831 and #174789. login() confirms this by design -- it goes straight to response.json()["back"] without ever reading response.status_code, so a transport-level check could not have fired. The previous transport-level handling and its Retry-After parsing are dropped entirely rather than kept "just in case": there is no evidence Growatt ever sends that shape, and speculative handling would just be untested code that looks like coverage. login() now raises GrowattRateLimitError(error_code="507") on that body, following the GrowattV1ApiError shape so consumers read the code off the exception instead of parsing a message. Every other failure keeps returning the dict unchanged. Three of the five tests fail against unmodified login(); all pass with it. Co-Authored-By: Claude Opus 5 (1M context) --- growattServer/__init__.py | 2 + growattServer/base_api.py | 9 ++++- growattServer/exceptions.py | 43 +++++++++++++++++++++ tests/test_login_rate_limit.py | 68 ++++++++++++++++++++++++++++++++++ 4 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 tests/test_login_rate_limit.py diff --git a/growattServer/__init__.py b/growattServer/__init__.py index e6914e8..c119dbd 100755 --- a/growattServer/__init__.py +++ b/growattServer/__init__.py @@ -7,6 +7,7 @@ from .exceptions import ( GrowattError, GrowattParameterError, + GrowattRateLimitError, GrowattV1ApiError, GrowattV1ApiErrorCode, ) @@ -20,6 +21,7 @@ "GrowattApi", "GrowattError", "GrowattParameterError", + "GrowattRateLimitError", "GrowattV1ApiError", "GrowattV1ApiErrorCode", "OpenApiV1", diff --git a/growattServer/base_api.py b/growattServer/base_api.py index 327d9f8..d171007 100644 --- a/growattServer/base_api.py +++ b/growattServer/base_api.py @@ -15,7 +15,7 @@ import requests -from .exceptions import GrowattError +from .exceptions import GrowattError, GrowattRateLimitError name = "growattServer" @@ -23,6 +23,11 @@ BATT_MODE_BATTERY_FIRST = 1 BATT_MODE_GRID_FIRST = 2 +# Growatt reports a rate-limited login in the response body, not as an HTTP +# status: HTTP 200 with `success: false` and `msg: "507"`. See +# GrowattRateLimitError for the reports behind this. +LOGIN_RATE_LIMITED_CODE = "507" + def hash_password(password: str) -> str: """ @@ -171,6 +176,8 @@ def login(self, username: str, password: str, is_password_hashed: bool = False) }) data = response.json()["back"] + if not data.get("success") and str(data.get("msg", "")) == LOGIN_RATE_LIMITED_CODE: + raise GrowattRateLimitError(error_code=LOGIN_RATE_LIMITED_CODE) if data["success"]: data.update({ "userId": data["user"]["id"], diff --git a/growattServer/exceptions.py b/growattServer/exceptions.py index 4b9520f..8532137 100644 --- a/growattServer/exceptions.py +++ b/growattServer/exceptions.py @@ -66,3 +66,46 @@ def __init__(self, message: str, error_code: int, error_msg: str) -> None: super().__init__(f"{message}: [{error_code}] {error_msg}") self.error_code = error_code self.error_msg = error_msg + + +class GrowattRateLimitError(GrowattError): + """ + Raised when Growatt refuses a login because the account is rate limited. + + Growatt signals this **in the response body**, not as an HTTP status: the + request succeeds with HTTP 200 and the payload carries ``success: false`` + with ``msg: "507"``. That is the shape behind the + ``ConfigEntryError: Growatt login failed: 507`` tracebacks in + home-assistant/core#176831 and home-assistant/core#174789. + + A 507 has been observed to precede an approximately 24 hour lockout rather + than a short cooldown, so this library never retries on its own: retrying + immediately is what deepens the lockout. Callers get a distinct exception + type so they can back off for hours instead of treating it like bad + credentials or a malformed response. + + Follows the :class:`GrowattV1ApiError` shape so consumers can read the code + off the exception rather than parsing a message. + """ + + def __init__(self, error_code: str, error_msg: str | None = None) -> None: + """ + Initialize the GrowattRateLimitError. + + Args: + error_code: The application-level code from the response body, + e.g. ``"507"``. + error_msg: Optional human-readable detail, when the body carries one. + + """ + message = f"Growatt refused the login as rate limited: [{error_code}]" + if error_msg: + message += f" {error_msg}" + message += ( + ". A 507 has been observed to precede an approximately 24 hour " + "account lockout rather than a short cooldown -- do not retry " + "immediately." + ) + super().__init__(message) + self.error_code = error_code + self.error_msg = error_msg diff --git a/tests/test_login_rate_limit.py b/tests/test_login_rate_limit.py new file mode 100644 index 0000000..bb5a3c0 --- /dev/null +++ b/tests/test_login_rate_limit.py @@ -0,0 +1,68 @@ +"""Growatt reports a rate-limited login in the body, not as an HTTP status.""" +from unittest.mock import MagicMock, patch + +import pytest + +from growattServer import GrowattApi, GrowattRateLimitError + + +def _api_with_login_body(body): + """Build an API whose login POST returns the given `back` payload.""" + api = GrowattApi() + response = MagicMock() + response.json.return_value = {"back": body} + response.status_code = 200 # the real lockout answers 200, not 507 + api.session = MagicMock() + api.session.post.return_value = response + return api + + +def test_login_raises_on_507_in_the_body(): + """`success: false` + `msg: "507"` is the real lockout signal.""" + api = _api_with_login_body({"success": False, "msg": "507"}) + + with pytest.raises(GrowattRateLimitError) as exc: + api.login("user", "pass") + + assert exc.value.error_code == "507" + + +def test_507_error_mentions_not_retrying(): + """Callers must not be nudged into an immediate retry.""" + api = _api_with_login_body({"success": False, "msg": "507"}) + + with pytest.raises(GrowattRateLimitError) as exc: + api.login("user", "pass") + + assert "do not retry immediately" in str(exc.value) + + +def test_other_failures_are_left_alone(): + """A wrong password must keep returning the dict, not raise.""" + api = _api_with_login_body({"success": False, "msg": "501"}) + + result = api.login("user", "pass") + + assert result["success"] is False + assert result["msg"] == "501" + + +def test_numeric_msg_is_still_recognised(): + """Defensive: the code is compared as a string.""" + api = _api_with_login_body({"success": False, "msg": 507}) + + with pytest.raises(GrowattRateLimitError): + api.login("user", "pass") + + +def test_successful_login_is_unaffected(): + """The happy path keeps its existing shape.""" + api = _api_with_login_body({ + "success": True, + "user": {"id": "u1", "rightlevel": 1}, + }) + + result = api.login("user", "pass") + + assert result["userId"] == "u1" + assert result["userLevel"] == 1 From 1bd046d4d632028b4317a93c33f5198cc2d285b8 Mon Sep 17 00:00:00 2001 From: proscar87 Date: Sat, 8 Aug 2026 23:26:13 -0600 Subject: [PATCH 2/2] Detect the 507 in the session hook so data calls are covered too Growatt rate limits each endpoint separately, so guarding login() alone misses refusals on data calls. The response hook already sees every response for the session, which makes it one place to extend instead of ~40 endpoint methods that each parse their own shape. The hook runs on everything, so it falls through untouched on shapes it does not recognise: plant_list receives `back` as a list, and non-JSON bodies are possible. Only the exact `success: false` + `msg: "507"` combination raises. Also drops the observed-lockout prose from the exception message, since that is behaviour that can change and it ended up in every log line. It lives in the docstring now, and the test asserts on error_code rather than message wording. Co-Authored-By: Claude Opus 5 --- growattServer/base_api.py | 42 ++++++++++++-- growattServer/exceptions.py | 13 ++--- tests/test_login_rate_limit.py | 100 +++++++++++++++++++++++++++++---- 3 files changed, 130 insertions(+), 25 deletions(-) diff --git a/growattServer/base_api.py b/growattServer/base_api.py index d171007..7b5e75e 100644 --- a/growattServer/base_api.py +++ b/growattServer/base_api.py @@ -23,10 +23,41 @@ BATT_MODE_BATTERY_FIRST = 1 BATT_MODE_GRID_FIRST = 2 -# Growatt reports a rate-limited login in the response body, not as an HTTP -# status: HTTP 200 with `success: false` and `msg: "507"`. See -# GrowattRateLimitError for the reports behind this. -LOGIN_RATE_LIMITED_CODE = "507" +# Growatt reports rate limiting in the response body, not as an HTTP status: +# HTTP 200 with `success: false` and `msg: "507"`. See GrowattRateLimitError +# for the reports behind this. +RATE_LIMITED_CODE = "507" + + +def _raise_if_rate_limited(response: requests.Response) -> None: + """ + Raise GrowattRateLimitError when a response body carries Growatt's 507 code. + + Growatt answers HTTP 200 and puts the refusal in the payload, so the body + of every response has to be read. Growatt rate limits each endpoint + separately, so this lives in the session hook rather than in `login()`: + the reports we have are all logins, but a data call can be refused the + same way. + + Body shapes vary -- most endpoints wrap their payload in `back`, but + `plant_list` returns `back` as a list, and some responses are not JSON at + all. Since this runs on every response, anything unexpected falls through + untouched instead of raising. + """ + try: + data = response.json() + except ValueError: + return + + if not isinstance(data, dict): + return + + back = data.get("back") + if isinstance(back, dict): + data = back + + if not data.get("success", True) and str(data.get("msg", "")) == RATE_LIMITED_CODE: + raise GrowattRateLimitError(error_code=RATE_LIMITED_CODE) def hash_password(password: str) -> str: @@ -79,6 +110,7 @@ def __init__(self, add_random_user_id: bool = False, agent_identifier: str | Non def _raise_for_status(response, *args: object, **kwargs: object) -> None: _ = args _ = kwargs + _raise_if_rate_limited(response) response.raise_for_status() self.session.hooks = {"response": [_raise_for_status]} @@ -176,8 +208,6 @@ def login(self, username: str, password: str, is_password_hashed: bool = False) }) data = response.json()["back"] - if not data.get("success") and str(data.get("msg", "")) == LOGIN_RATE_LIMITED_CODE: - raise GrowattRateLimitError(error_code=LOGIN_RATE_LIMITED_CODE) if data["success"]: data.update({ "userId": data["user"]["id"], diff --git a/growattServer/exceptions.py b/growattServer/exceptions.py index 8532137..a42a4f9 100644 --- a/growattServer/exceptions.py +++ b/growattServer/exceptions.py @@ -70,7 +70,7 @@ def __init__(self, message: str, error_code: int, error_msg: str) -> None: class GrowattRateLimitError(GrowattError): """ - Raised when Growatt refuses a login because the account is rate limited. + Raised when Growatt refuses a request because the account is rate limited. Growatt signals this **in the response body**, not as an HTTP status: the request succeeds with HTTP 200 and the payload carries ``success: false`` @@ -78,6 +78,10 @@ class GrowattRateLimitError(GrowattError): ``ConfigEntryError: Growatt login failed: 507`` tracebacks in home-assistant/core#176831 and home-assistant/core#174789. + Every reported case so far is a login, but Growatt rate limits each + endpoint separately, so detection sits in the session response hook and + any call can raise this. + A 507 has been observed to precede an approximately 24 hour lockout rather than a short cooldown, so this library never retries on its own: retrying immediately is what deepens the lockout. Callers get a distinct exception @@ -98,14 +102,9 @@ def __init__(self, error_code: str, error_msg: str | None = None) -> None: error_msg: Optional human-readable detail, when the body carries one. """ - message = f"Growatt refused the login as rate limited: [{error_code}]" + message = f"Growatt rate limit reached: [{error_code}]" if error_msg: message += f" {error_msg}" - message += ( - ". A 507 has been observed to precede an approximately 24 hour " - "account lockout rather than a short cooldown -- do not retry " - "immediately." - ) super().__init__(message) self.error_code = error_code self.error_msg = error_msg diff --git a/tests/test_login_rate_limit.py b/tests/test_login_rate_limit.py index bb5a3c0..44d22cd 100644 --- a/tests/test_login_rate_limit.py +++ b/tests/test_login_rate_limit.py @@ -1,22 +1,56 @@ -"""Growatt reports a rate-limited login in the body, not as an HTTP status.""" -from unittest.mock import MagicMock, patch +"""Growatt reports rate limiting in the body, not as an HTTP status.""" +import json import pytest +import requests from growattServer import GrowattApi, GrowattRateLimitError -def _api_with_login_body(body): - """Build an API whose login POST returns the given `back` payload.""" +def _response(payload=None, *, body=None, status=200): + """Build a real Response -- the check parses the body itself.""" + response = requests.Response() + response.status_code = status + if body is None: + body = json.dumps(payload) + response._content = body.encode() + response.headers["Content-Type"] = "application/json" + return response + + +class _HookedSession: + """A session stand-in that runs the response hooks, as requests does. + + The 507 check lives in the hook now, so a plain MagicMock session would + skip it and every test here would pass for the wrong reason. + """ + + def __init__(self, hooks, response): + self.hooks = hooks + self.headers = {} + self._response = response + + def _dispatch(self, *args, **kwargs): + for hook in self.hooks["response"]: + hook(self._response) + return self._response + + get = _dispatch + post = _dispatch + + +def _api_returning(response): + """An API whose every call answers with `response`, hooks included.""" api = GrowattApi() - response = MagicMock() - response.json.return_value = {"back": body} - response.status_code = 200 # the real lockout answers 200, not 507 - api.session = MagicMock() - api.session.post.return_value = response + api.session = _HookedSession(api.session.hooks, response) return api +def _api_with_login_body(body): + """An API whose login answers with the given `back` payload.""" + return _api_returning(_response({"back": body})) + + def test_login_raises_on_507_in_the_body(): """`success: false` + `msg: "507"` is the real lockout signal.""" api = _api_with_login_body({"success": False, "msg": "507"}) @@ -27,14 +61,23 @@ def test_login_raises_on_507_in_the_body(): assert exc.value.error_code == "507" -def test_507_error_mentions_not_retrying(): - """Callers must not be nudged into an immediate retry.""" +def test_the_code_is_readable_off_the_exception(): + """Callers branch on `error_code`, never on the message wording.""" api = _api_with_login_body({"success": False, "msg": "507"}) with pytest.raises(GrowattRateLimitError) as exc: api.login("user", "pass") - assert "do not retry immediately" in str(exc.value) + assert exc.value.error_code == "507" + assert str(exc.value) == "Growatt rate limit reached: [507]" + + +def test_a_data_call_is_covered_too(): + """Growatt rate limits per endpoint, so this cannot be login-only.""" + api = _api_returning(_response({"back": {"success": False, "msg": "507"}})) + + with pytest.raises(GrowattRateLimitError): + api.plant_list("user_1") def test_other_failures_are_left_alone(): @@ -66,3 +109,36 @@ def test_successful_login_is_unaffected(): assert result["userId"] == "u1" assert result["userLevel"] == 1 + + +def test_a_list_back_does_not_raise(): + """`plant_list` answers with `back` as a list -- the guard must hold.""" + api = _api_returning(_response({"back": [{"success": False, "msg": "507"}]})) + + assert api.plant_list("user_1") == [{"success": False, "msg": "507"}] + + +def test_a_non_json_body_does_not_raise(): + """The hook sees every response, including ones that are not JSON.""" + response = _response(body="maintenance") + response.headers["Content-Type"] = "text/html" + api = _api_returning(response) + + for hook in api.session.hooks["response"]: + hook(response) + + +def test_a_bare_body_without_the_back_wrapper_is_checked(): + """Not every endpoint wraps its payload, so read the top level too.""" + api = _api_returning(_response({"success": False, "msg": "507"})) + + with pytest.raises(GrowattRateLimitError): + api.plant_list("user_1") + + +def test_http_errors_still_raise(): + """The rate-limit check must not shadow raise_for_status.""" + api = _api_returning(_response({"back": {"success": True}}, status=500)) + + with pytest.raises(requests.exceptions.HTTPError): + api.plant_list("user_1")