From 8ec75cf88371253c87ff2973856dbe31819c6134 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 13 Jul 2019 00:33:31 -0700 Subject: [PATCH] Verify cloud user exists during boot (#25119) --- homeassistant/components/cloud/__init__.py | 8 +++++- tests/components/cloud/test_init.py | 30 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/cloud/__init__.py b/homeassistant/components/cloud/__init__.py index bb539a270ac..3e17dd70841 100644 --- a/homeassistant/components/cloud/__init__.py +++ b/homeassistant/components/cloud/__init__.py @@ -157,7 +157,13 @@ async def async_setup(hass, config): await prefs.async_initialize() # Cloud user - if not prefs.cloud_user: + user = None + if prefs.cloud_user: + # Fetch the user. It can happen that the user no longer exists if + # an image was restored without restoring the cloud prefs. + user = await hass.auth.async_get_user(prefs.cloud_user) + + if user is None: user = await hass.auth.async_create_system_user( 'Home Assistant Cloud', [GROUP_ID_ADMIN]) await prefs.async_update(cloud_user=user.id) diff --git a/tests/components/cloud/test_init.py b/tests/components/cloud/test_init.py index c938a404964..c8f6a852181 100644 --- a/tests/components/cloud/test_init.py +++ b/tests/components/cloud/test_init.py @@ -127,6 +127,36 @@ async def test_setup_existing_cloud_user(hass, hass_storage): assert hass_storage[STORAGE_KEY]['data']['cloud_user'] == user.id +async def test_setup_invalid_cloud_user(hass, hass_storage): + """Test setup with API push default data.""" + hass_storage[STORAGE_KEY] = { + 'version': 1, + 'data': { + 'cloud_user': 'non-existing' + } + } + with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()): + result = await async_setup_component(hass, 'cloud', { + 'http': {}, + 'cloud': { + cloud.CONF_MODE: cloud.MODE_DEV, + 'cognito_client_id': 'test-cognito_client_id', + 'user_pool_id': 'test-user_pool_id', + 'region': 'test-region', + 'relayer': 'test-relayer', + } + }) + assert result + + assert hass_storage[STORAGE_KEY]['data']['cloud_user'] != 'non-existing' + cloud_user = await hass.auth.async_get_user( + hass_storage[STORAGE_KEY]['data']['cloud_user'] + ) + + assert cloud_user + assert cloud_user.groups[0].id == GROUP_ID_ADMIN + + async def test_setup_setup_cloud_user(hass, hass_storage): """Test setup with API push default data.""" hass_storage[STORAGE_KEY] = {