Merge agent/fix-cognito-signin: sign in via Cognito directly, readable auth errors

This commit is contained in:
2026-11-07 12:23:49 +01:00
11 changed files with 536 additions and 41 deletions
+6 -4
View File
@@ -45,16 +45,18 @@ The integration needs a one-time verification token from PerfectDraft's website.
1. Open [perfectdraft.com/en-gb/customer/account/login](https://www.perfectdraft.com/en-gb/customer/account/login) in your browser (Chrome, Firefox, Edge, etc.) — you do **not** need to log in on this page, just open it
2. Press **F12** to open Developer Tools, then click the **Console** tab
3. Paste this command and press **Enter**:
3. Paste this command at the console prompt and press **Enter** — once, not as a "Live expression", which re-runs it over and over:
```javascript
grecaptcha.enterprise.execute('6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV', {action: 'Magento/login'}).then(t => console.log(t))
grecaptcha.enterprise.execute('6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV', {action: 'Magento/login'}).then(t => { console.log(t); const b = document.body.appendChild(document.createElement('button')); b.textContent = 'Click THIS BLACK BOX to copy your PerfectDraft token'; b.style = 'position:fixed;top:40%;left:50%;transform:translateX(-50%);z-index:2147483647;padding:20px 40px;font-size:22px;background:#000;color:#fff;border-radius:8px;cursor:pointer'; b.onclick = () => navigator.clipboard.writeText(t).then(() => b.textContent = 'Copied! Paste it into Home Assistant', e => b.textContent = 'Copy failed: ' + e.message) })
```
4. A long string of text will appear in the console — that's your token
5. Select it, copy it, and paste it into the Home Assistant setup dialog
4. A black box saying **Click THIS BLACK BOX to copy your PerfectDraft token** appears in the middle of the page — click it, and it changes to **Copied!**
5. Paste the token into the Home Assistant setup dialog
6. Click **Submit** within 2 minutes (the token expires)
If the button says **Copy failed**, the same token is printed in the console: right-click it there and copy it.
That's it! The integration will authenticate and start polling your PerfectDraft Pro. Token refresh is automatic — you should not need to repeat this step. If the session does eventually expire, Home Assistant will prompt you to re-authenticate. (This is a new integration, so the exact session lifespan is still being determined — it's at least 30 days and may well be indefinite.)
### Step 3: Configure polling
+67 -16
View File
@@ -7,7 +7,14 @@ from typing import Any
import aiohttp
from .const import API_BASE_URL, API_KEY, COGNITO_CLIENT_ID, COGNITO_REGION
from .const import (
API_BASE_URL,
API_KEY,
COGNITO_CLIENT_ID,
COGNITO_REGION,
RECAPTCHA_ACTION,
RECAPTCHA_DOMAIN,
)
from .exceptions import (
AuthenticationError,
PerfectDraftApiError,
@@ -16,8 +23,33 @@ from .exceptions import (
_LOGGER = logging.getLogger(__name__)
RECAPTCHA_ACTION_SIGN_IN = "Magento/login"
COGNITO_IDP_URL = f"https://cognito-idp.{COGNITO_REGION}.amazonaws.com/"
COGNITO_HEADERS = {
"Content-Type": "application/x-amz-json-1.1",
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
}
def _parse_cognito_error(body: str) -> tuple[str | None, str | None]:
"""Return (error type, message) from a Cognito error body.
Cognito answers ``{"__type": "...", "message": "..."}``, sometimes with a
namespaced type (``com.amazonaws...#NotAuthorizedException``). A body that
is not JSON, such as an HTML error page, becomes the message, truncated.
"""
try:
data = json.loads(body)
except ValueError:
return None, body.strip()[:200] or None
if not isinstance(data, dict):
return None, None
code = data.get("__type")
reason = data.get("message")
if isinstance(code, str):
code = code.rsplit("#", 1)[-1]
else:
code = None
return code, reason if isinstance(reason, str) else None
class PerfectDraftApiClient:
@@ -59,42 +91,61 @@ class PerfectDraftApiClient:
async def authenticate(
self, email: str, password: str, recaptcha_token: str
) -> dict[str, str]:
"""Sign in via /authentication/sign-in with a reCAPTCHA token.
"""Sign in directly against Cognito with a reCAPTCHA token.
The token must be generated from a real browser on perfectdraft.com
using the web reCAPTCHA Enterprise key with action Magento/login.
PerfectDraft's PreAuthentication Lambda also requires the shop's
origin as ``domain``; the api.perfectdraft.com sign-in gateway does
not forward it, so sign-in cannot go through the gateway.
"""
url = f"{self._base}/authentication/sign-in"
payload = {
"email": email,
"password": password,
"recaptchaToken": recaptcha_token,
"recaptchaAction": RECAPTCHA_ACTION_SIGN_IN,
"AuthFlow": "USER_PASSWORD_AUTH",
"ClientId": COGNITO_CLIENT_ID,
"AuthParameters": {"USERNAME": email, "PASSWORD": password},
"ClientMetadata": {
"recaptchaToken": recaptcha_token,
"recaptchaAction": RECAPTCHA_ACTION,
"domain": RECAPTCHA_DOMAIN,
},
}
headers = {"x-api-key": API_KEY}
try:
async with self._session.post(
url, json=payload, headers=headers
COGNITO_IDP_URL, json=payload, headers=COGNITO_HEADERS
) as resp:
if resp.status in (400, 401, 403):
body = await resp.text()
code, reason = _parse_cognito_error(body)
raise AuthenticationError(
f"Sign-in rejected ({resp.status}): {body}"
f"Sign-in rejected ({resp.status}): {body}",
code=code,
reason=reason,
)
if resp.status != 200:
body = await resp.text()
raise PerfectDraftApiError(resp.status, body)
data = await resp.json()
data = await resp.json(content_type=None)
except aiohttp.ClientError as exc:
raise PerfectDraftConnectionError(str(exc)) from exc
self._access_token = data["AccessToken"]
self._id_token = data["IdToken"]
self._refresh_token = data["RefreshToken"]
result = data.get("AuthenticationResult") if isinstance(data, dict) else None
if not isinstance(result, dict) or not all(
result.get(key) for key in ("AccessToken", "IdToken", "RefreshToken")
):
challenge = data.get("ChallengeName") if isinstance(data, dict) else None
raise AuthenticationError(
f"Sign-in returned no tokens (challenge: {challenge})",
code=challenge,
reason=f"Sign-in requires {challenge}" if challenge else None,
)
self._access_token = result["AccessToken"]
self._id_token = result["IdToken"]
self._refresh_token = result["RefreshToken"]
_LOGGER.debug("Authenticated successfully")
return data
return result
async def refresh_access_token(self) -> dict[str, Any]:
"""Refresh tokens directly via AWS Cognito (bypasses API gateway + reCAPTCHA)."""
+30 -5
View File
@@ -31,6 +31,12 @@ _LOGGER = logging.getLogger(__name__)
CONF_RECAPTCHA_TOKEN = "recaptcha_token"
_AUTH_ERRORS = {
"credentials": "invalid_credentials",
"token": "token_rejected",
"other": "invalid_auth",
}
class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for PerfectDraft."""
@@ -40,18 +46,23 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
def __init__(self) -> None:
self._email: str | None = None
self._password: str | None = None
# Fills {reason} in the error strings; every form must pass it.
self._auth_reason = ""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Step 1: collect email and password."""
errors: dict[str, str] = {}
if user_input is not None:
self._email = user_input[CONF_EMAIL]
self._password = user_input[CONF_PASSWORD]
return await self.async_step_token()
return self._show_user_form({})
def _show_user_form(
self, errors: dict[str, str]
) -> config_entries.ConfigFlowResult:
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
@@ -61,6 +72,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
}
),
errors=errors,
description_placeholders={"reason": self._auth_reason},
)
async def async_step_token(
@@ -81,7 +93,15 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
)
except AuthenticationError as err:
_LOGGER.error("Authentication failed: %s", err)
errors["base"] = "invalid_auth"
self._auth_reason = err.display_reason
error = _AUTH_ERRORS[err.kind]
if error == "invalid_credentials":
# A fresh token cannot fix a wrong password, so ask for
# the credentials again instead of looping on this step.
if self.source == config_entries.SOURCE_REAUTH:
return self._show_reauth_confirm_form({"base": error})
return self._show_user_form({"base": error})
errors["base"] = error
except PerfectDraftConnectionError as err:
_LOGGER.error("Connection failed: %s", err)
errors["base"] = "cannot_connect"
@@ -120,6 +140,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
}
),
errors=errors,
description_placeholders={"reason": self._auth_reason},
)
async def _async_persist(
@@ -168,13 +189,16 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Ask user to re-enter credentials for reauth."""
errors: dict[str, str] = {}
if user_input is not None:
self._email = user_input[CONF_EMAIL]
self._password = user_input[CONF_PASSWORD]
return await self.async_step_token()
return self._show_reauth_confirm_form({})
def _show_reauth_confirm_form(
self, errors: dict[str, str]
) -> config_entries.ConfigFlowResult:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema(
@@ -184,6 +208,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
}
),
errors=errors,
description_placeholders={"reason": self._auth_reason},
)
@staticmethod
+2
View File
@@ -5,6 +5,8 @@ API_KEY = "cAyzERqthCJXYVExjNAhr9CzE8ncLN2cQK3WGK10"
RECAPTCHA_SITE_KEY = "6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV"
RECAPTCHA_ACTION = "Magento/login"
# PerfectDraft's Cognito PreAuthentication Lambda rejects sign-in without it.
RECAPTCHA_DOMAIN = "https://www.perfectdraft.com"
COGNITO_REGION = "eu-west-1"
COGNITO_CLIENT_ID = "57ddq2ppqg2jcpup06r2g1deur"
+32 -1
View File
@@ -5,8 +5,39 @@ class PerfectDraftError(Exception):
"""Base exception for PerfectDraft."""
_CREDENTIAL_ERROR_CODES = frozenset({"NotAuthorizedException", "UserNotFoundException"})
_TOKEN_ERROR_CODES = frozenset({"UserLambdaValidationException"})
_MAX_REASON_LENGTH = 200
class AuthenticationError(PerfectDraftError):
"""Raised when authentication fails (bad credentials, expired refresh token, reCAPTCHA rejection)."""
"""Raised when authentication fails (bad credentials, expired refresh token, reCAPTCHA rejection).
``code`` is the Cognito error type (e.g. ``NotAuthorizedException``) and
``reason`` its human-readable message, when the server supplied them.
"""
def __init__(
self, message: str, code: str | None = None, reason: str | None = None
) -> None:
super().__init__(message)
self.code = code
self.reason = reason
@property
def kind(self) -> str:
"""Which input was rejected: ``credentials``, ``token`` or ``other``."""
if self.code in _CREDENTIAL_ERROR_CODES:
return "credentials"
if self.code in _TOKEN_ERROR_CODES:
return "token"
return "other"
@property
def display_reason(self) -> str:
"""Server-supplied reason for the config flow, never empty."""
text = (self.reason or self.code or "").strip().rstrip(".")
return text[:_MAX_REASON_LENGTH] or "no reason given"
class PerfectDraftApiError(PerfectDraftError):
+1 -1
View File
@@ -1,7 +1,7 @@
{
"domain": "perfectdraft",
"name": "PerfectDraft",
"version": "0.3.4",
"version": "0.4.4",
"documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro",
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues",
"codeowners": ["@Falkvinge"],
+3 -1
View File
@@ -26,7 +26,9 @@
}
},
"error": {
"invalid_auth": "Authentication failed. Token may have expired (2 min limit) or credentials are wrong. Try again with a fresh token.",
"invalid_auth": "Authentication failed: {reason}. Try again with a fresh token.",
"invalid_credentials": "PerfectDraft rejected the email or password: {reason}.",
"token_rejected": "PerfectDraft rejected the verification token: {reason}. Generate a fresh token and paste it within 2 minutes.",
"cannot_connect": "Cannot connect to PerfectDraft service.",
"unknown": "An unexpected error occurred."
},
@@ -26,7 +26,9 @@
}
},
"error": {
"invalid_auth": "Authentication failed. Token may have expired (2 min limit) or credentials are wrong. Try again with a fresh token.",
"invalid_auth": "Authentication failed: {reason}. Try again with a fresh token.",
"invalid_credentials": "PerfectDraft rejected the email or password: {reason}.",
"token_rejected": "PerfectDraft rejected the verification token: {reason}. Generate a fresh token and paste it within 2 minutes.",
"cannot_connect": "Cannot connect to PerfectDraft service.",
"unknown": "An unexpected error occurred."
},
+4 -9
View File
@@ -3,16 +3,11 @@
# config-flow behaviour cannot be exercised without a real Home Assistant.
#
# pytest-homeassistant-custom-component releases track core one-to-one.
# 0.13.205 is the newest release that still supports Python 3.12 and it
# pins core 2025.1.4 — above the 2024.11 floor the reauth helpers need.
# 0.13.375 pins core 2026.10.4 and requires Python 3.14, the interpreter on
# the dev host. Older pins (0.13.205 / core 2025.1.4) need Python 3.12:
# their numpy has no 3.14 wheel and will not build without a C compiler.
#
# python3 -m venv .venv-test
# .venv-test/bin/pip install -r requirements-test.txt
# .venv-test/bin/pytest tests/
pytest-homeassistant-custom-component==0.13.205
# Core pins aiodns==3.2.0 but leaves pycares floating. pycares 4.6+ starts a
# daemon shutdown thread that the harness's verify_cleanup fixture flags as a
# leak, failing every test at teardown. 4.5.0 is contemporaneous with core
# 2025.1.4 and has no such thread.
pycares==4.5.0
pytest-homeassistant-custom-component==0.13.375
+229
View File
@@ -0,0 +1,229 @@
"""Tests for PerfectDraftApiClient.authenticate() against Cognito.
Stdlib only, like ``test_keg_detection.py``: ``api.py`` is loaded as part of
a stub ``perfectdraft`` package so the integration's ``__init__.py`` (which
needs Home Assistant) never runs, and a fake session replays canned
responses instead of touching the network.
"""
import asyncio
import importlib
import json
import sys
import types
import unittest
from pathlib import Path
PKG_DIR = Path(__file__).resolve().parent.parent / "custom_components" / "perfectdraft"
try:
import aiohttp
except ImportError: # the client only needs aiohttp.ClientError at runtime
aiohttp = types.ModuleType("aiohttp")
aiohttp.ClientError = type("ClientError", (Exception,), {})
aiohttp.ClientSession = object
sys.modules["aiohttp"] = aiohttp
_pkg = types.ModuleType("_perfectdraft_stub")
_pkg.__path__ = [str(PKG_DIR)]
sys.modules["_perfectdraft_stub"] = _pkg
api = importlib.import_module("_perfectdraft_stub.api")
exceptions = importlib.import_module("_perfectdraft_stub.exceptions")
EMAIL = "drinker@example.com"
PASSWORD = "hunter2"
TOKEN = "recaptcha-token"
TOKENS = {"AccessToken": "access-jwt-1", "IdToken": "id-jwt-1", "RefreshToken": "refresh-jwt-1"}
class FakeResponse:
def __init__(self, status, body):
self.status = status
self._body = body if isinstance(body, str) else json.dumps(body)
async def text(self):
return self._body
async def json(self, content_type="application/json"):
if content_type is not None:
raise AssertionError("Cognito replies x-amz-json; parse with content_type=None")
return json.loads(self._body)
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
class FakeSession:
def __init__(self, status=200, body=None, raises=None):
self._response = FakeResponse(status, body if body is not None else {})
self._raises = raises
self.calls = []
def post(self, url, **kwargs):
self.calls.append((url, kwargs))
if self._raises:
raise self._raises
return self._response
def sign_in(session):
client = api.PerfectDraftApiClient(session)
result = asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
return client, result
def rejection(session):
client = api.PerfectDraftApiClient(session)
client.set_tokens("old-access", "old-id", "old-refresh")
with unittest.TestCase().assertRaises(exceptions.AuthenticationError) as ctx:
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
return client, ctx.exception
class SuccessfulSignIn(unittest.TestCase):
def setUp(self):
self.session = FakeSession(200, {"AuthenticationResult": {**TOKENS, "ExpiresIn": 3600}})
self.client, self.result = sign_in(self.session)
self.url, self.kwargs = self.session.calls[0]
def test_posts_to_cognito_not_the_gateway(self):
self.assertEqual(self.url, "https://cognito-idp.eu-west-1.amazonaws.com/")
self.assertEqual(
self.kwargs["headers"],
{
"Content-Type": "application/x-amz-json-1.1",
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
},
)
def test_payload_carries_credentials_and_recaptcha_metadata(self):
self.assertEqual(
self.kwargs["json"],
{
"AuthFlow": "USER_PASSWORD_AUTH",
"ClientId": "57ddq2ppqg2jcpup06r2g1deur",
"AuthParameters": {"USERNAME": EMAIL, "PASSWORD": PASSWORD},
"ClientMetadata": {
"recaptchaToken": TOKEN,
"recaptchaAction": "Magento/login",
"domain": "https://www.perfectdraft.com",
},
},
)
def test_stores_tokens_from_authentication_result(self):
self.assertEqual(self.client.access_token, "access-jwt-1")
self.assertEqual(self.client.id_token, "id-jwt-1")
self.assertEqual(self.client.refresh_token, "refresh-jwt-1")
self.assertEqual(self.result["AccessToken"], "access-jwt-1")
class Challenge(unittest.TestCase):
def test_challenge_raises_and_keeps_tokens(self):
client, err = rejection(FakeSession(200, {"ChallengeName": "NEW_PASSWORD_REQUIRED", "Session": "s"}))
self.assertEqual(err.code, "NEW_PASSWORD_REQUIRED")
self.assertEqual(err.kind, "other")
self.assertIn("NEW_PASSWORD_REQUIRED", err.display_reason)
self.assertEqual(client.access_token, "old-access")
self.assertEqual(client.refresh_token, "old-refresh")
def test_incomplete_result_raises(self):
_, err = rejection(FakeSession(200, {"AuthenticationResult": {"AccessToken": "a"}}))
self.assertIsNone(err.code)
self.assertEqual(err.display_reason, "no reason given")
class Rejections(unittest.TestCase):
def test_wrong_password_is_a_credentials_failure(self):
_, err = rejection(FakeSession(400, {"__type": "NotAuthorizedException", "message": "Incorrect username or password."}))
self.assertEqual(err.code, "NotAuthorizedException")
self.assertEqual(err.kind, "credentials")
self.assertEqual(err.display_reason, "Incorrect username or password")
self.assertIn("400", str(err))
def test_unknown_user_is_a_credentials_failure(self):
_, err = rejection(FakeSession(400, {"__type": "UserNotFoundException", "message": "User does not exist."}))
self.assertEqual(err.kind, "credentials")
def test_lambda_rejection_is_a_token_failure(self):
_, err = rejection(FakeSession(400, {
"__type": "UserLambdaValidationException",
"message": "PreAuthentication failed with error 'domain'.",
}))
self.assertEqual(err.kind, "token")
self.assertEqual(err.display_reason, "PreAuthentication failed with error 'domain'")
def test_namespaced_type_is_stripped(self):
_, err = rejection(FakeSession(400, {
"__type": "com.amazonaws.cognito.identity.idp.model#NotAuthorizedException",
"message": "x",
}))
self.assertEqual(err.code, "NotAuthorizedException")
def test_other_type_is_an_other_failure(self):
for status in (401, 403):
_, err = rejection(FakeSession(status, {"__type": "InvalidParameterException", "message": "USER_PASSWORD_AUTH flow not enabled"}))
self.assertEqual(err.kind, "other")
self.assertEqual(err.display_reason, "USER_PASSWORD_AUTH flow not enabled")
def test_non_json_body_becomes_truncated_reason(self):
_, err = rejection(FakeSession(403, "<html>" + "x" * 500 + "</html>"))
self.assertIsNone(err.code)
self.assertEqual(err.kind, "other")
self.assertLessEqual(len(err.reason), 200)
self.assertTrue(err.reason.startswith("<html>"))
def test_empty_body_has_fallback_reason(self):
_, err = rejection(FakeSession(400, ""))
self.assertEqual(err.display_reason, "no reason given")
def test_rejection_keeps_existing_tokens(self):
client, _ = rejection(FakeSession(400, {"__type": "NotAuthorizedException", "message": "x"}))
self.assertEqual(client.access_token, "old-access")
class OtherFailures(unittest.TestCase):
def test_server_error_is_an_api_error(self):
client = api.PerfectDraftApiClient(FakeSession(500, "boom"))
with self.assertRaises(exceptions.PerfectDraftApiError) as ctx:
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
self.assertEqual(ctx.exception.status, 500)
def test_network_failure_is_a_connection_error(self):
client = api.PerfectDraftApiClient(FakeSession(raises=aiohttp.ClientError("down")))
with self.assertRaises(exceptions.PerfectDraftConnectionError):
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
class SecretsAreNotLogged(unittest.TestCase):
def test_no_secret_reaches_the_log(self):
cases = [
FakeSession(200, {"AuthenticationResult": TOKENS}),
FakeSession(400, {"__type": "NotAuthorizedException", "message": "Incorrect username or password."}),
]
for session in cases:
with self.assertLogs(api._LOGGER, level="DEBUG") as logs:
api._LOGGER.debug("marker")
client = api.PerfectDraftApiClient(session)
try:
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
except exceptions.AuthenticationError:
pass
text = "\n".join(logs.output)
for secret in (PASSWORD, TOKEN, *TOKENS.values()):
self.assertNotIn(secret, text)
class LegacyRaises(unittest.TestCase):
def test_single_argument_raise_still_works(self):
err = exceptions.AuthenticationError("No refresh token available")
self.assertIsNone(err.code)
self.assertEqual(err.kind, "other")
self.assertEqual(str(err), "No refresh token available")
if __name__ == "__main__":
unittest.main()
+159 -3
View File
@@ -57,6 +57,24 @@ STORED_DATA = {
}
WRONG_PASSWORD = AuthenticationError(
"Sign-in rejected (400)",
code="NotAuthorizedException",
reason="Incorrect username or password.",
)
TOKEN_REJECTED_REASON = "PreAuthentication failed with error 'domain'"
TOKEN_REJECTED = AuthenticationError(
"Sign-in rejected (400)",
code="UserLambdaValidationException",
reason=f"{TOKEN_REJECTED_REASON}.",
)
OTHER_FAILURE = AuthenticationError(
"Sign-in rejected (400)",
code="InvalidParameterException",
reason="USER_PASSWORD_AUTH flow not enabled for this client",
)
def _mock_client(*, authenticate_error=None, machines=((MACHINE_ID,))):
"""An API client that hands back recognisably new tokens."""
client = AsyncMock()
@@ -182,16 +200,60 @@ async def test_reauth_accepts_same_account_different_case(
async def test_reauth_bad_token_keeps_old_tokens(hass: HomeAssistant) -> None:
entry = _entry(hass)
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
client = _mock_client(authenticate_error=TOKEN_REJECTED)
result = await _run_reauth(hass, entry, client)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "token"
assert result["errors"] == {"base": "invalid_auth"}
assert result["errors"] == {"base": "token_rejected"}
assert result["description_placeholders"]["reason"] == TOKEN_REJECTED_REASON
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
async def test_reauth_wrong_password_returns_to_reauth_confirm(
hass: HomeAssistant,
) -> None:
entry = _entry(hass)
client = _mock_client(authenticate_error=WRONG_PASSWORD)
result = await _run_reauth(hass, entry, client)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "invalid_credentials"}
assert result["description_placeholders"]["reason"] == "Incorrect username or password"
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
# Corrected credentials lead to a fresh token, then success.
client.authenticate.side_effect = None
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
assert result["step_id"] == "token"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
await hass.async_block_till_done()
assert result["reason"] == "reauth_successful"
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
async def test_reauth_other_failure_is_invalid_auth(hass: HomeAssistant) -> None:
entry = _entry(hass)
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
result = await _run_reauth(hass, entry, client)
assert result["step_id"] == "token"
assert result["errors"] == {"base": "invalid_auth"}
assert result["description_placeholders"]["reason"] == "no reason given"
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
async def test_reauth_skips_profile_when_machine_id_known(
hass: HomeAssistant,
) -> None:
@@ -240,8 +302,11 @@ async def test_add_integration_while_reauth_pending(hass: HomeAssistant) -> None
)
await hass.async_block_till_done()
# Core up to 2025.x aborts in async_set_unique_id; 2026.x no longer
# counts the parked reauth flow as in progress and reaches the
# duplicate guard instead. Both reasons are translated.
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_in_progress"
assert result["reason"] in ("already_in_progress", "already_configured")
# --- User setup: must be unchanged by this fix ---
@@ -318,6 +383,49 @@ async def test_user_setup_connection_error(hass: HomeAssistant) -> None:
assert result["errors"] == {"base": "cannot_connect"}
async def _run_user_setup(hass, client):
"""Drive user then token, returning the token step's result."""
with patch(CLIENT_PATH, return_value=client):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["description_placeholders"]["reason"] == ""
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
assert result["description_placeholders"]["reason"] == ""
return await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
async def test_user_setup_wrong_password_returns_to_user_form(
hass: HomeAssistant,
) -> None:
result = await _run_user_setup(hass, _mock_client(authenticate_error=WRONG_PASSWORD))
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_credentials"}
assert result["description_placeholders"]["reason"] == "Incorrect username or password"
async def test_user_setup_token_rejected(hass: HomeAssistant) -> None:
result = await _run_user_setup(hass, _mock_client(authenticate_error=TOKEN_REJECTED))
assert result["step_id"] == "token"
assert result["errors"] == {"base": "token_rejected"}
assert result["description_placeholders"]["reason"] == TOKEN_REJECTED_REASON
async def test_user_setup_other_auth_failure(hass: HomeAssistant) -> None:
result = await _run_user_setup(hass, _mock_client(authenticate_error=OTHER_FAILURE))
assert result["step_id"] == "token"
assert result["errors"] == {"base": "invalid_auth"}
assert result["description_placeholders"]["reason"] == "USER_PASSWORD_AUTH flow not enabled for this client"
# --- Translations must cover every reachable abort reason ---
COMPONENT_DIR = Path(__file__).parent.parent / "custom_components" / "perfectdraft"
@@ -383,3 +491,51 @@ def test_every_abort_reason_is_translated(filename: str) -> None:
)["config"]["abort"]
missing = sorted(_abort_reasons_in_source() - set(declared))
assert not missing, f"{filename} is missing abort reasons: {missing}"
# --- ...and every error key the forms can show ---
def _error_keys_in_source() -> set[str]:
"""String constants assigned to ``errors["base"]`` or listed in ``_AUTH_ERRORS``."""
tree = ast.parse((COMPONENT_DIR / "config_flow.py").read_text(encoding="utf-8"))
keys: set[str] = set()
for node in ast.walk(tree):
if not isinstance(node, ast.Assign):
continue
target = node.targets[0]
if (
isinstance(target, ast.Subscript)
and isinstance(target.slice, ast.Constant)
and target.slice.value == "base"
and isinstance(node.value, ast.Constant)
):
keys.add(node.value.value)
if (
isinstance(target, ast.Name)
and target.id == "_AUTH_ERRORS"
and isinstance(node.value, ast.Dict)
):
keys.update(v.value for v in node.value.values if isinstance(v, ast.Constant))
return keys
def test_error_key_scanner_sees_the_known_keys() -> None:
assert {
"cannot_connect",
"unknown",
"invalid_auth",
"invalid_credentials",
"token_rejected",
} <= _error_keys_in_source()
@pytest.mark.parametrize("filename", ["strings.json", "translations/en.json"])
def test_every_error_key_is_translated(filename: str) -> None:
declared = json.loads(
(COMPONENT_DIR / filename).read_text(encoding="utf-8")
)["config"]["error"]
missing = sorted(_error_keys_in_source() - set(declared))
assert not missing, f"{filename} is missing error keys: {missing}"