| 1 |
"""Tests for the tools to communicate with the cloud.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from unittest.mock import AsyncMock, MagicMock, patch |
| 5 |
|
| 6 |
from botocore.exceptions import ClientError, EndpointConnectionError |
| 7 |
from pycognito.exceptions import MFAChallengeException |
| 8 |
import pytest |
| 9 |
|
| 10 |
from hass_nabucasa import CloudError, auth as auth_api |
| 11 |
from tests.common import FROZEN_NOW_AS_TIMESTAMP |
| 12 |
|
| 13 |
|
| 14 |
@pytest.fixture |
| 15 |
def mock_cloud(cloud_mock): |
| 16 |
"""Mock cloud.""" |
| 17 |
cloud_mock.is_logged_in = False |
| 18 |
return cloud_mock |
| 19 |
|
| 20 |
|
| 21 |
def aws_error(code, message="Unknown", operation_name="fake_operation_name"): |
| 22 |
"""Generate AWS error response.""" |
| 23 |
response = {"Error": {"Code": code, "Message": message}} |
| 24 |
return ClientError(response, operation_name) |
| 25 |
|
| 26 |
|
| 27 |
async def test_login_invalid_auth(mock_cognito, mock_cloud): |
| 28 |
"""Test trying to login with invalid credentials.""" |
| 29 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 30 |
mock_cognito.authenticate.side_effect = aws_error("NotAuthorizedException") |
| 31 |
|
| 32 |
with pytest.raises(auth_api.Unauthenticated): |
| 33 |
await auth.async_login("user", "pass") |
| 34 |
|
| 35 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 36 |
|
| 37 |
|
| 38 |
async def test_login_user_not_found(mock_cognito, mock_cloud): |
| 39 |
"""Test trying to login with invalid credentials.""" |
| 40 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 41 |
mock_cognito.authenticate.side_effect = aws_error("UserNotFoundException") |
| 42 |
|
| 43 |
with pytest.raises(auth_api.UserNotFound): |
| 44 |
await auth.async_login("user", "pass") |
| 45 |
|
| 46 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 47 |
|
| 48 |
|
| 49 |
async def test_login_user_not_confirmed(mock_cognito, mock_cloud): |
| 50 |
"""Test trying to login without confirming account.""" |
| 51 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 52 |
mock_cognito.authenticate.side_effect = aws_error("UserNotConfirmedException") |
| 53 |
|
| 54 |
with pytest.raises(auth_api.UserNotConfirmed): |
| 55 |
await auth.async_login("user", "pass") |
| 56 |
|
| 57 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 58 |
|
| 59 |
|
| 60 |
async def test_login_connection_error(mock_cognito, mock_cloud): |
| 61 |
"""Test login raises CloudConnectionError instead of UnknownError.""" |
| 62 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 63 |
mock_cognito.authenticate.side_effect = EndpointConnectionError( |
| 64 |
endpoint_url="https://cognito-idp.us-east-1.amazonaws.com/", |
| 65 |
error="Failed to establish a new connection: [Errno 111] Connection refused", |
| 66 |
) |
| 67 |
|
| 68 |
with pytest.raises( |
| 69 |
auth_api.CloudConnectionError, |
| 70 |
match="Connection refused", |
| 71 |
): |
| 72 |
await auth.async_login("user", "pass") |
| 73 |
|
| 74 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 75 |
|
| 76 |
|
| 77 |
async def test_login_user_mfa_required(mock_cognito, mock_cloud): |
| 78 |
"""Test trying to login without MFA when it is required.""" |
| 79 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 80 |
mock_cognito.authenticate.side_effect = MFAChallengeException("MFA required", {}) |
| 81 |
|
| 82 |
with pytest.raises(auth_api.MFARequired): |
| 83 |
await auth.async_login("user", "pass") |
| 84 |
|
| 85 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 86 |
|
| 87 |
|
| 88 |
async def test_login_user_verify_totp_invalid_code(mock_cognito, mock_cloud): |
| 89 |
"""Test trying to login with MFA when it is required.""" |
| 90 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 91 |
mock_cognito.respond_to_software_token_mfa_challenge.side_effect = aws_error( |
| 92 |
"CodeMismatchException", |
| 93 |
) |
| 94 |
|
| 95 |
with pytest.raises(auth_api.InvalidTotpCode): |
| 96 |
await auth.async_login_verify_totp("user", "123456", {"session": "session"}) |
| 97 |
|
| 98 |
assert len(mock_cloud.update_token.mock_calls) == 0 |
| 99 |
|
| 100 |
|
| 101 |
async def test_login_user_verify_totp(mock_cognito, mock_cloud): |
| 102 |
"""Test trying to login with MFA when it is required.""" |
| 103 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 104 |
mock_cognito.id_token = "test_id_token" |
| 105 |
mock_cognito.access_token = "test_access_token" |
| 106 |
mock_cognito.refresh_token = "test_refresh_token" |
| 107 |
|
| 108 |
await auth.async_login_verify_totp("user", "123456", {"session": "session"}) |
| 109 |
|
| 110 |
assert len(mock_cognito.respond_to_software_token_mfa_challenge.mock_calls) == 1 |
| 111 |
mock_cloud.update_token.assert_called_once_with( |
| 112 |
"test_id_token", |
| 113 |
"test_access_token", |
| 114 |
"test_refresh_token", |
| 115 |
) |
| 116 |
|
| 117 |
|
| 118 |
async def test_login(mock_cognito, mock_cloud): |
| 119 |
"""Test trying to login without confirming account.""" |
| 120 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 121 |
mock_cognito.id_token = "test_id_token" |
| 122 |
mock_cognito.access_token = "test_access_token" |
| 123 |
mock_cognito.refresh_token = "test_refresh_token" |
| 124 |
|
| 125 |
await auth.async_login("user", "pass") |
| 126 |
|
| 127 |
assert len(mock_cognito.authenticate.mock_calls) == 1 |
| 128 |
mock_cloud.update_token.assert_called_once_with( |
| 129 |
"test_id_token", |
| 130 |
"test_access_token", |
| 131 |
"test_refresh_token", |
| 132 |
) |
| 133 |
|
| 134 |
|
| 135 |
async def test_login_with_check_connection(mock_cognito, mock_cloud): |
| 136 |
"""Test login with connection check.""" |
| 137 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 138 |
mock_cognito.id_token = "test_id_token" |
| 139 |
mock_cognito.access_token = "test_access_token" |
| 140 |
mock_cognito.refresh_token = "test_refresh_token" |
| 141 |
|
| 142 |
await auth.async_login("user", "pass", check_connection=True) |
| 143 |
|
| 144 |
assert len(mock_cognito.authenticate.mock_calls) == 1 |
| 145 |
mock_cloud.update_token.assert_called_once_with( |
| 146 |
"test_id_token", |
| 147 |
"test_access_token", |
| 148 |
"test_refresh_token", |
| 149 |
) |
| 150 |
|
| 151 |
|
| 152 |
async def test_register(mock_cognito, cloud_mock): |
| 153 |
"""Test registering an account.""" |
| 154 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 155 |
await auth.async_register( |
| 156 |
"[email protected]", |
| 157 |
"password", |
| 158 |
client_metadata={"test": "metadata"}, |
| 159 |
) |
| 160 |
assert len(mock_cognito.register.mock_calls) == 1 |
| 161 |
|
| 162 |
call = mock_cognito.register.mock_calls[0] |
| 163 |
result_user, result_password = call.args |
| 164 |
assert result_user == "[email protected]" |
| 165 |
assert result_password == "password" |
| 166 |
assert call.kwargs["client_metadata"] == {"test": "metadata"} |
| 167 |
|
| 168 |
|
| 169 |
async def test_register_lowercase_email(mock_cognito, cloud_mock): |
| 170 |
"""Test forcing lowercase email when registering an account.""" |
| 171 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 172 |
await auth.async_register("[email protected]", "password") |
| 173 |
assert len(mock_cognito.register.mock_calls) == 1 |
| 174 |
|
| 175 |
call = mock_cognito.register.mock_calls[0] |
| 176 |
result_user = call.args[0] |
| 177 |
assert result_user == "[email protected]" |
| 178 |
|
| 179 |
|
| 180 |
async def test_register_fails(mock_cognito, cloud_mock): |
| 181 |
"""Test registering an account.""" |
| 182 |
mock_cognito.register.side_effect = aws_error("SomeError") |
| 183 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 184 |
with pytest.raises(CloudError): |
| 185 |
await auth.async_register("[email protected]", "password") |
| 186 |
|
| 187 |
|
| 188 |
async def test_resend_email_confirm(mock_cognito, cloud_mock): |
| 189 |
"""Test starting forgot password flow.""" |
| 190 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 191 |
await auth.async_resend_email_confirm("[email protected]") |
| 192 |
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 1 |
| 193 |
|
| 194 |
|
| 195 |
async def test_resend_email_confirm_fails(mock_cognito, cloud_mock): |
| 196 |
"""Test failure when starting forgot password flow.""" |
| 197 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 198 |
mock_cognito.client.resend_confirmation_code.side_effect = aws_error("SomeError") |
| 199 |
with pytest.raises(CloudError): |
| 200 |
await auth.async_resend_email_confirm("[email protected]") |
| 201 |
|
| 202 |
|
| 203 |
async def test_forgot_password(mock_cognito, cloud_mock): |
| 204 |
"""Test starting forgot password flow.""" |
| 205 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 206 |
await auth.async_forgot_password("[email protected]") |
| 207 |
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 1 |
| 208 |
|
| 209 |
|
| 210 |
async def test_forgot_password_fails(mock_cognito, cloud_mock): |
| 211 |
"""Test failure when starting forgot password flow.""" |
| 212 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 213 |
mock_cognito.initiate_forgot_password.side_effect = aws_error("SomeError") |
| 214 |
with pytest.raises(CloudError): |
| 215 |
await auth.async_forgot_password("[email protected]") |
| 216 |
|
| 217 |
|
| 218 |
async def test_check_token_writes_new_token_on_refresh(mock_cognito, cloud_mock): |
| 219 |
"""Test check_token writes new token if refreshed.""" |
| 220 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 221 |
mock_cognito.check_token.return_value = True |
| 222 |
mock_cognito.id_token = "new id token" |
| 223 |
mock_cognito.access_token = "new access token" |
| 224 |
|
| 225 |
await auth.async_check_token() |
| 226 |
|
| 227 |
assert len(mock_cognito.check_token.mock_calls) == 1 |
| 228 |
assert cloud_mock.id_token == "new id token" |
| 229 |
assert cloud_mock.access_token == "new access token" |
| 230 |
cloud_mock.update_token.assert_called_once_with("new id token", "new access token") |
| 231 |
|
| 232 |
|
| 233 |
async def test_check_token_does_not_write_existing_token(mock_cognito, cloud_mock): |
| 234 |
"""Test check_token won't write new token if still valid.""" |
| 235 |
mock_cognito.check_token.return_value = False |
| 236 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 237 |
|
| 238 |
await auth.async_check_token() |
| 239 |
|
| 240 |
assert len(mock_cognito.check_token.mock_calls) == 1 |
| 241 |
assert cloud_mock.id_token != mock_cognito.id_token |
| 242 |
assert cloud_mock.access_token != mock_cognito.access_token |
| 243 |
assert len(cloud_mock.update_token.mock_calls) == 0 |
| 244 |
|
| 245 |
|
| 246 |
async def test_check_token_raises(mock_cognito, cloud_mock): |
| 247 |
"""Test we raise correct error.""" |
| 248 |
mock_cognito.renew_access_token.side_effect = aws_error("SomeError") |
| 249 |
auth = auth_api.CognitoAuth(cloud_mock) |
| 250 |
|
| 251 |
with pytest.raises(CloudError): |
| 252 |
await auth.async_check_token() |
| 253 |
|
| 254 |
assert len(mock_cognito.check_token.mock_calls) == 2 |
| 255 |
assert cloud_mock.id_token != mock_cognito.id_token |
| 256 |
assert cloud_mock.access_token != mock_cognito.access_token |
| 257 |
assert len(cloud_mock.update_token.mock_calls) == 0 |
| 258 |
|
| 259 |
|
| 260 |
async def test_async_setup(cloud_mock): |
| 261 |
"""Test async setup.""" |
| 262 |
auth_api.CognitoAuth(cloud_mock) |
| 263 |
assert len(cloud_mock.iot.mock_calls) == 2 |
| 264 |
on_connect = cloud_mock.iot.mock_calls[0][1][0] |
| 265 |
on_disconnect = cloud_mock.iot.mock_calls[1][1][0] |
| 266 |
|
| 267 |
with ( |
| 268 |
patch("random.randint", return_value=0), |
| 269 |
patch("hass_nabucasa.auth.CognitoAuth.async_renew_access_token") as mock_renew, |
| 270 |
): |
| 271 |
await on_connect() |
| 272 |
# Let handle token sleep once |
| 273 |
await asyncio.sleep(0) |
| 274 |
# Let handle token refresh token |
| 275 |
await asyncio.sleep(0) |
| 276 |
|
| 277 |
assert len(mock_renew.mock_calls) == 1 |
| 278 |
|
| 279 |
await on_disconnect() |
| 280 |
|
| 281 |
# Make sure task is no longer being called |
| 282 |
await asyncio.sleep(0) |
| 283 |
await asyncio.sleep(0) |
| 284 |
assert len(mock_renew.mock_calls) == 1 |
| 285 |
|
| 286 |
|
| 287 |
@pytest.mark.parametrize( |
| 288 |
"auth_mock_kwargs", |
| 289 |
( |
| 290 |
{"access_token": None}, |
| 291 |
{"refresh_token": None}, |
| 292 |
), |
| 293 |
) |
| 294 |
async def test_guard_no_login_authenticated_cognito(auth_mock_kwargs: dict[str, None]): |
| 295 |
"""Test that not authenticated cognito login raises.""" |
| 296 |
auth = auth_api.CognitoAuth(MagicMock(**auth_mock_kwargs)) |
| 297 |
with pytest.raises(auth_api.Unauthenticated): |
| 298 |
await auth._async_authenticated_cognito() |
| 299 |
|
| 300 |
|
| 301 |
@pytest.mark.parametrize( |
| 302 |
"exp_value,random_value,expected_sleep", |
| 303 |
[ |
| 304 |
[None, 2220, "37m"], |
| 305 |
[120, 120, "2m"], |
| 306 |
[121, 120, "2m"], |
| 307 |
[124, 120, "4s"], |
| 308 |
[-124, 120, "2m"], |
| 309 |
[7800, 60, "2h:9m"], |
| 310 |
[1330, 60, "21m:10s"], |
| 311 |
], |
| 312 |
) |
| 313 |
async def test_sleep_time_calculation( |
| 314 |
mock_cloud, |
| 315 |
caplog, |
| 316 |
exp_value, |
| 317 |
random_value, |
| 318 |
expected_sleep, |
| 319 |
): |
| 320 |
"""Test sleep time calculation.""" |
| 321 |
auth = auth_api.CognitoAuth(mock_cloud) |
| 322 |
|
| 323 |
with ( |
| 324 |
patch("hass_nabucasa.auth.cognito.expiration_from_token") as mock_exp, |
| 325 |
patch("hass_nabucasa.auth.cognito.asyncio.sleep", AsyncMock()), |
| 326 |
patch( |
| 327 |
"hass_nabucasa.auth.cognito.CognitoAuth.async_renew_access_token", |
| 328 |
side_effect=asyncio.CancelledError, |
| 329 |
), |
| 330 |
patch("random.randint") as mock_random, |
| 331 |
): |
| 332 |
mock_exp.return_value = ( |
| 333 |
FROZEN_NOW_AS_TIMESTAMP + exp_value if exp_value else None |
| 334 |
) |
| 335 |
mock_random.return_value = random_value |
| 336 |
|
| 337 |
await auth._async_handle_token_refresh() |
| 338 |
|
| 339 |
assert f"Sleeping for {expected_sleep} before refreshing token" in caplog.text |