1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
|
"""Test auth functions."""
import json
import logging
from os import listdir
from os.path import isfile, join
from unittest.mock import patch
import aiohttp
import jwt
import pytest
from aioresponses import aioresponses
from pyenphase import Envoy, EnvoyTokenAuth
from pyenphase.auth import EnvoyLegacyAuth
from pyenphase.const import (
URL_AUTH_CHECK_JWT,
URL_DEVICE_DATA,
URL_PRODUCTION_INVERTERS,
SupportedFeatures,
)
from pyenphase.exceptions import EnvoyAuthenticationError, EnvoyAuthenticationRequired
from .common import (
get_mock_envoy,
load_fixture,
load_json_fixture,
prep_envoy,
start_7_firmware_mock,
temporary_log_level,
)
LOGGER = logging.getLogger(__name__)
@pytest.mark.asyncio
async def test_wrong_auth_order_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test data collected fails before auth is done"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationRequired):
await envoy.update()
# now in correct order
await envoy.authenticate("username", "password")
data = await envoy.update()
assert data
@pytest.mark.asyncio
async def test_with_3_9_36_firmware_bad_auth(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Verify with 3.9.36 firmware with incorrect auth."""
version = "3.9.36_bad_auth"
mock_aioresponse.get(
"https://127.0.0.1/info", status=200, body=await load_fixture(version, "info")
)
mock_aioresponse.get("https://127.0.0.1/info.xml", status=200, body="")
mock_aioresponse.get("https://127.0.0.1/production", status=404)
mock_aioresponse.get("https://127.0.0.1/production.json", status=404)
mock_aioresponse.get(
"https://127.0.0.1/api/v1/production",
status=401,
payload=await load_json_fixture(version, "api_v1_production"),
)
mock_aioresponse.get(
"https://127.0.0.1/api/v1/production/inverters",
status=200,
payload=await load_json_fixture(version, "api_v1_production_inverters"),
)
mock_aioresponse.get(
"https://127.0.0.1/ivp/ensemble/inventory", status=200, payload=[]
)
path = f"tests/fixtures/{version}"
files = [f for f in listdir(path) if isfile(join(path, f))]
if "admin_lib_tariff" in files:
try:
json_data = await load_json_fixture(version, "admin_lib_tariff")
except json.decoder.JSONDecodeError:
json_data = None
mock_aioresponse.get(
"https://127.0.0.1/admin/lib/tariff", status=200, payload=json_data
)
else:
mock_aioresponse.get("https://127.0.0.1/admin/lib/tariff", status=401)
mock_aioresponse.get("https://127.0.0.1/ivp/meters", status=200, payload=[])
# Add the HTTP version of api/v1/production with 401 as well
mock_aioresponse.get(
"http://127.0.0.1/api/v1/production",
status=401,
payload=await load_json_fixture(version, "api_v1_production"),
)
# Add other required endpoints for the probe
mock_aioresponse.get("https://127.0.0.1/production.json?details=1", status=404)
mock_aioresponse.get("http://127.0.0.1/production.json?details=1", status=404)
mock_aioresponse.get(
"http://127.0.0.1/production",
status=200,
body=await load_fixture(version, "production"),
)
with pytest.raises(EnvoyAuthenticationRequired):
await get_mock_envoy(test_client_session)
@pytest.mark.asyncio
async def test_production_with_3_9_36_firmware_bad_auth(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Authentication failed for http://127.0.0.1/api/v1/production."""
version = "3.9.36_bad_auth"
mock_aioresponse.get(
"https://127.0.0.1/info", status=200, body=await load_fixture(version, "info")
)
mock_aioresponse.get("https://127.0.0.1/info.xml", status=200, body="")
mock_aioresponse.get("https://127.0.0.1/production", status=404)
mock_aioresponse.get("https://127.0.0.1/production.json", status=404)
mock_aioresponse.get(
"https://127.0.0.1/api/v1/production",
status=401,
payload=await load_json_fixture(version, "api_v1_production"),
)
mock_aioresponse.get(
"https://127.0.0.1/api/v1/production/inverters",
status=200,
payload=await load_json_fixture(version, "api_v1_production_inverters"),
)
mock_aioresponse.get(
"https://127.0.0.1/ivp/ensemble/inventory", status=200, payload=[]
)
path = f"tests/fixtures/{version}"
files = [f for f in listdir(path) if isfile(join(path, f))]
if "admin_lib_tariff" in files:
try:
json_data = await load_json_fixture(version, "admin_lib_tariff")
except json.decoder.JSONDecodeError:
json_data = None
mock_aioresponse.get(
"https://127.0.0.1/admin/lib/tariff", status=200, payload=json_data
)
else:
mock_aioresponse.get("https://127.0.0.1/admin/lib/tariff", status=401)
mock_aioresponse.get("https://127.0.0.1/ivp/meters", status=200, payload=[])
# Add the HTTP version of api/v1/production with 401 as well
mock_aioresponse.get(
"http://127.0.0.1/api/v1/production",
status=401,
payload=await load_json_fixture(version, "api_v1_production"),
)
# Add other required endpoints for the probe
mock_aioresponse.get("https://127.0.0.1/production.json?details=1", status=404)
mock_aioresponse.get("http://127.0.0.1/production.json?details=1", status=404)
mock_aioresponse.get(
"http://127.0.0.1/production",
status=200,
body=await load_fixture(version, "production"),
)
with pytest.raises(EnvoyAuthenticationRequired):
await get_mock_envoy(test_client_session)
@pytest.mark.parametrize(
(
"username",
"password",
),
[
("installer", ""),
("envoy", ""),
],
)
@pytest.mark.asyncio
async def test_known_users_with_3_9_36_firmware(
username: str,
password: str,
mock_aioresponse: aioresponses,
test_client_session: aiohttp.ClientSession,
) -> None:
"""Test successful login with known usernames."""
version = "3.9.36"
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
await envoy.authenticate(username, password)
# test cookies function now cookies are not on request
assert envoy.auth
used_cookies = envoy.auth.cookies
assert used_cookies == {}
data = await envoy.update()
assert data
# cov: force test failure of Digest authentication for local Envoy.
assert isinstance(envoy.auth, EnvoyLegacyAuth)
envoy.auth.local_password = ""
assert envoy.auth.auth is None
@pytest.mark.asyncio
async def test_unknown_user_with_3_9_36_firmware(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Could not setup authentication object with 3.9.x"""
version = "3.9.36"
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationRequired):
await envoy.authenticate("unknown", None)
@pytest.mark.parametrize(
(
"username",
"password",
),
[
("installer", ""),
("envoy", ""),
("unknown", ""),
],
)
@pytest.mark.asyncio
async def test_blank_passwords_with_7_6_175_standard(
username: str,
password: str,
mock_aioresponse: aioresponses,
test_client_session: aiohttp.ClientSession,
) -> None:
"""Test Could not setup authentication object with 7.6.x"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationRequired):
await envoy.authenticate(username, password)
@pytest.mark.asyncio
async def test_no_token_obtained_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Unable to obtain token for Envoy authentication"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
with patch("pyenphase.EnvoyTokenAuth._obtain_token", return_value=None):
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationError):
await envoy.authenticate("username", "password")
@pytest.mark.asyncio
async def test_jwt_failure_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Unable to verify token for Envoy authentication"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
from .common import override_mock
override_mock(
mock_aioresponse,
"get",
"https://127.0.0.1" + URL_AUTH_CHECK_JWT,
status=404,
body="no jwt",
)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationError):
await envoy.authenticate("username", "password")
@pytest.mark.asyncio
async def test_no_remote_login_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Unable to login to Enlighten to obtain session ID from https://enlighten.enphaseenergy.com/login/login.json?"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
from .common import override_mock
override_mock(
mock_aioresponse,
"post",
"https://enlighten.enphaseenergy.com/login/login.json?",
status=500,
payload={
"session_id": "1234567890",
"user_id": "1234567890",
"user_name": "test",
"first_name": "Test",
"is_consumer": True,
"manager_token": "1234567890",
},
)
override_mock(
mock_aioresponse,
"post",
"https://entrez.enphaseenergy.com/tokens",
status=500,
body="token",
)
override_mock(
mock_aioresponse,
"get",
"https://127.0.0.1/auth/check_jwt",
status=200,
payload={},
)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationError):
await envoy.authenticate("username", "password")
@pytest.mark.asyncio
async def test_no_remote_token_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Unable to obtain token for Envoy authentication from https://entrez.enphaseenergy.com/tokens"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
from .common import override_mock
# The login endpoint is already mocked with 200 by start_7_firmware_mock
# Only override the tokens endpoint to fail
override_mock(
mock_aioresponse,
"post",
"https://entrez.enphaseenergy.com/tokens",
status=500,
body="token",
)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationError):
await envoy.authenticate("username", "password")
assert isinstance(envoy.auth, EnvoyTokenAuth)
with pytest.raises(EnvoyAuthenticationRequired):
assert envoy.auth.token_type == "owner"
@pytest.mark.asyncio
async def test_enlighten_json_error_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test Unable to decode response from Enlighten"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
from .common import override_mock
# Override the login endpoint to return invalid JSON
override_mock(
mock_aioresponse,
"post",
"https://enlighten.enphaseenergy.com/login/login.json?",
status=200,
body="nojson",
)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
with pytest.raises(EnvoyAuthenticationError):
await envoy.authenticate("username", "password")
@pytest.mark.asyncio
async def test_token_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test auth using token"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
token = jwt.encode(
payload={"name": "envoy", "exp": 1707837780, "enphaseUser": "owner"},
key="secret",
algorithm="HS256",
)
await envoy.authenticate("username", "password", token)
assert isinstance(envoy.auth, EnvoyTokenAuth)
assert envoy.auth.expire_timestamp == 1707837780
assert envoy.auth.token == token
assert envoy.auth.token_type == "owner"
# test cookies function now cookies are not on request
assert envoy.auth.cookies == {}
# execute refresh code cov
await envoy.auth.refresh()
# cov: test force no serial error
# Your firmware requires token authentication,
# but no envoy serial number was provided to obtain the token
used_serial = envoy.auth.envoy_serial
envoy.auth.envoy_serial = None
with pytest.raises(EnvoyAuthenticationError):
await envoy.auth.refresh()
envoy.auth.envoy_serial = used_serial
# cov: test force no cloud credentials error
# Your firmware requires token authentication
# but no cloud credentials were provided to obtain the token
envoy.auth.cloud_password = None
with pytest.raises(EnvoyAuthenticationError):
await envoy.auth.refresh()
@pytest.mark.asyncio
async def test_remote_login_response_with_7_6_175_standard(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test enlighten login response for is_consumer and manager_token"""
version = "7.6.175_standard"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
# set log level to info 1 time for GET and 1 time for POST to improve COV
with temporary_log_level("pyenphase", logging.INFO):
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
await envoy.authenticate("username", "password")
assert isinstance(envoy.auth, EnvoyTokenAuth)
assert envoy.auth.manager_token == "1234567890"
assert envoy.auth.is_consumer
# read unused auth from EnvoyTokenAuth to improve COV
assert envoy.auth.auth is None
@pytest.mark.asyncio
async def test_device_data_with_8_2_4345_with_device_data(
mock_aioresponse: aioresponses, test_client_session: aiohttp.ClientSession
) -> None:
"""Test device data fails with no auth"""
version = "8.2.4345_with_device_data"
start_7_firmware_mock(mock_aioresponse)
await prep_envoy(mock_aioresponse, "127.0.0.1", version)
from .common import override_mock, updater_features
# 401 on device data endpoint and inverters production endpoint
# This simulates the case where the user does not have access to any inverter data
for url in [
"https://127.0.0.1" + URL_DEVICE_DATA,
"http://127.0.0.1" + URL_DEVICE_DATA,
"https://127.0.0.1" + URL_PRODUCTION_INVERTERS,
"http://127.0.0.1" + URL_PRODUCTION_INVERTERS,
]:
override_mock(
mock_aioresponse,
"get",
url,
status=401,
body="no device data",
)
envoy = Envoy("127.0.0.1", client=test_client_session)
await envoy.setup()
await envoy.authenticate("username", "password")
await envoy.probe()
assert SupportedFeatures.INVERTERS not in envoy.supported_features
# 200 on device data endpoint only
# This simulates the case where the user has access to device data but not to inverter production data
for url in [
"https://127.0.0.1" + URL_DEVICE_DATA,
"http://127.0.0.1" + URL_DEVICE_DATA,
]:
override_mock(
mock_aioresponse,
"get",
url,
status=200,
payload=await load_json_fixture(version, "ivp_pdm_device_data"),
)
await envoy.probe()
assert updater_features(envoy._updaters) == {
"EnvoyDeviceDataInvertersUpdater": SupportedFeatures.INVERTERS
| SupportedFeatures.DETAILED_INVERTERS,
"EnvoyEnembleUpdater": SupportedFeatures.ENCHARGE | SupportedFeatures.ENPOWER,
"EnvoyMetersUpdater": SupportedFeatures.CTMETERS,
"EnvoyProductionJsonUpdater": SupportedFeatures.METERING
| SupportedFeatures.TOTAL_CONSUMPTION
| SupportedFeatures.NET_CONSUMPTION
| SupportedFeatures.PRODUCTION,
"EnvoyTariffUpdater": SupportedFeatures.TARIFF,
}
# S
|