2023-11-20 13:17:10 +00:00
|
|
|
import json
|
|
|
|
import logging
|
2024-07-24 17:58:37 +00:00
|
|
|
import re
|
2023-11-20 13:17:10 +00:00
|
|
|
import secrets
|
|
|
|
import time
|
|
|
|
from contextlib import nullcontext as does_not_raise
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
import aiohttp
|
2023-11-20 13:17:10 +00:00
|
|
|
import pytest
|
2024-01-29 15:26:00 +00:00
|
|
|
from yarl import URL
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
from ..aestransport import AesTransport
|
2023-11-20 13:17:10 +00:00
|
|
|
from ..credentials import Credentials
|
2023-12-29 19:17:15 +00:00
|
|
|
from ..deviceconfig import DeviceConfig
|
2024-01-18 09:57:33 +00:00
|
|
|
from ..exceptions import (
|
2024-02-21 15:52:55 +00:00
|
|
|
AuthenticationError,
|
|
|
|
KasaException,
|
|
|
|
TimeoutError,
|
|
|
|
_ConnectionError,
|
|
|
|
_RetryableError,
|
2024-01-18 09:57:33 +00:00
|
|
|
)
|
|
|
|
from ..httpclient import HttpClient
|
2023-12-04 18:50:05 +00:00
|
|
|
from ..iotprotocol import IotProtocol
|
2023-12-29 19:17:15 +00:00
|
|
|
from ..klaptransport import (
|
|
|
|
KlapEncryptionSession,
|
|
|
|
KlapTransport,
|
|
|
|
KlapTransportV2,
|
|
|
|
_sha256,
|
|
|
|
)
|
2024-01-23 14:44:32 +00:00
|
|
|
from ..protocol import DEFAULT_CREDENTIALS, get_default_credentials
|
2023-12-04 18:50:05 +00:00
|
|
|
from ..smartprotocol import SmartProtocol
|
|
|
|
|
|
|
|
DUMMY_QUERY = {"foobar": {"foo": "bar", "bar": "foo"}}
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
class _mock_response:
|
2024-01-18 17:32:26 +00:00
|
|
|
def __init__(self, status, content: bytes):
|
|
|
|
self.status = status
|
2023-11-20 13:17:10 +00:00
|
|
|
self.content = content
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
async def __aenter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
async def __aexit__(self, exc_t, exc_v, exc_tb):
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def read(self):
|
|
|
|
return self.content
|
|
|
|
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-20 17:08:04 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("error", "retry_expectation"),
|
2023-12-20 17:08:04 +00:00
|
|
|
[
|
2024-01-18 09:57:33 +00:00
|
|
|
(Exception("dummy exception"), False),
|
2024-01-18 17:32:26 +00:00
|
|
|
(aiohttp.ServerTimeoutError("dummy exception"), True),
|
2024-01-23 22:15:18 +00:00
|
|
|
(aiohttp.ServerDisconnectedError("dummy exception"), True),
|
2024-01-18 17:32:26 +00:00
|
|
|
(aiohttp.ClientOSError("dummy exception"), True),
|
2023-12-20 17:08:04 +00:00
|
|
|
],
|
2024-01-23 22:15:18 +00:00
|
|
|
ids=("Exception", "ServerTimeoutError", "ServerDisconnectedError", "ClientOSError"),
|
2023-12-20 17:08:04 +00:00
|
|
|
)
|
2023-12-04 18:50:05 +00:00
|
|
|
@pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
|
|
|
|
@pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
|
2023-11-20 13:17:10 +00:00
|
|
|
@pytest.mark.parametrize("retry_count", [1, 3, 5])
|
2024-01-20 12:35:05 +00:00
|
|
|
async def test_protocol_retries_via_client_session(
|
2023-12-20 17:08:04 +00:00
|
|
|
mocker, retry_count, protocol_class, transport_class, error, retry_expectation
|
|
|
|
):
|
2023-12-04 18:50:05 +00:00
|
|
|
host = "127.0.0.1"
|
2024-01-18 17:32:26 +00:00
|
|
|
conn = mocker.patch.object(aiohttp.ClientSession, "post", side_effect=error)
|
2023-12-29 19:17:15 +00:00
|
|
|
|
|
|
|
config = DeviceConfig(host)
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-20 12:35:05 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
|
|
|
DUMMY_QUERY, retry_count=retry_count
|
|
|
|
)
|
|
|
|
|
|
|
|
expected_count = retry_count + 1 if retry_expectation else 1
|
|
|
|
assert conn.call_count == expected_count
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("error", "retry_expectation"),
|
2024-01-20 12:35:05 +00:00
|
|
|
[
|
2024-02-21 15:52:55 +00:00
|
|
|
(KasaException("dummy exception"), False),
|
|
|
|
(_RetryableError("dummy exception"), True),
|
|
|
|
(TimeoutError("dummy exception"), True),
|
2024-01-20 12:35:05 +00:00
|
|
|
],
|
2024-02-21 15:52:55 +00:00
|
|
|
ids=("KasaException", "_RetryableError", "TimeoutError"),
|
2024-01-20 12:35:05 +00:00
|
|
|
)
|
|
|
|
@pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
|
|
|
|
@pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
|
|
|
|
@pytest.mark.parametrize("retry_count", [1, 3, 5])
|
|
|
|
async def test_protocol_retries_via_httpclient(
|
|
|
|
mocker, retry_count, protocol_class, transport_class, error, retry_expectation
|
|
|
|
):
|
|
|
|
host = "127.0.0.1"
|
|
|
|
conn = mocker.patch.object(HttpClient, "post", side_effect=error)
|
2024-01-24 08:20:44 +00:00
|
|
|
mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
|
2024-01-20 12:35:05 +00:00
|
|
|
|
|
|
|
config = DeviceConfig(host)
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2023-12-29 19:17:15 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-04 18:50:05 +00:00
|
|
|
DUMMY_QUERY, retry_count=retry_count
|
|
|
|
)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-20 17:08:04 +00:00
|
|
|
expected_count = retry_count + 1 if retry_expectation else 1
|
|
|
|
assert conn.call_count == expected_count
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
@pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
|
|
|
|
@pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
|
|
|
|
async def test_protocol_no_retry_on_connection_error(
|
|
|
|
mocker, protocol_class, transport_class
|
|
|
|
):
|
|
|
|
host = "127.0.0.1"
|
2023-11-20 13:17:10 +00:00
|
|
|
conn = mocker.patch.object(
|
2024-01-18 17:32:26 +00:00
|
|
|
aiohttp.ClientSession,
|
2023-12-05 14:56:29 +00:00
|
|
|
"post",
|
2024-02-21 15:52:55 +00:00
|
|
|
side_effect=AuthenticationError("foo"),
|
2023-11-20 13:17:10 +00:00
|
|
|
)
|
2024-01-24 08:20:44 +00:00
|
|
|
mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig(host)
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2023-12-29 19:17:15 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-04 18:50:05 +00:00
|
|
|
DUMMY_QUERY, retry_count=5
|
|
|
|
)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
assert conn.call_count == 1
|
|
|
|
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
@pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
|
|
|
|
@pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
|
|
|
|
async def test_protocol_retry_recoverable_error(
|
|
|
|
mocker, protocol_class, transport_class
|
|
|
|
):
|
|
|
|
host = "127.0.0.1"
|
2023-11-20 13:17:10 +00:00
|
|
|
conn = mocker.patch.object(
|
2024-01-18 17:32:26 +00:00
|
|
|
aiohttp.ClientSession,
|
2023-12-05 14:56:29 +00:00
|
|
|
"post",
|
2024-01-18 17:32:26 +00:00
|
|
|
side_effect=aiohttp.ClientOSError("foo"),
|
2023-11-20 13:17:10 +00:00
|
|
|
)
|
2024-09-27 08:34:30 +00:00
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig(host)
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2023-12-29 19:17:15 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-04 18:50:05 +00:00
|
|
|
DUMMY_QUERY, retry_count=5
|
|
|
|
)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
assert conn.call_count == 6
|
|
|
|
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
@pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
|
|
|
|
@pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
|
2023-11-20 13:17:10 +00:00
|
|
|
@pytest.mark.parametrize("retry_count", [1, 3, 5])
|
2023-12-04 18:50:05 +00:00
|
|
|
async def test_protocol_reconnect(mocker, retry_count, protocol_class, transport_class):
|
|
|
|
host = "127.0.0.1"
|
2023-11-20 13:17:10 +00:00
|
|
|
remaining = retry_count
|
2023-12-10 15:41:53 +00:00
|
|
|
mock_response = {"result": {"great": "success"}, "error_code": 0}
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
def _fail_one_less_than_retry_count(*_, **__):
|
2023-12-04 18:50:05 +00:00
|
|
|
nonlocal remaining
|
2023-11-20 13:17:10 +00:00
|
|
|
remaining -= 1
|
|
|
|
if remaining:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise _ConnectionError("Simulated connection failure")
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
return mock_response
|
|
|
|
|
2023-12-19 14:11:59 +00:00
|
|
|
mocker.patch.object(transport_class, "perform_handshake")
|
|
|
|
if hasattr(transport_class, "perform_login"):
|
|
|
|
mocker.patch.object(transport_class, "perform_login")
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
send_mock = mocker.patch.object(
|
|
|
|
transport_class,
|
|
|
|
"send",
|
|
|
|
side_effect=_fail_one_less_than_retry_count,
|
|
|
|
)
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig(host)
|
|
|
|
response = await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-04 18:50:05 +00:00
|
|
|
DUMMY_QUERY, retry_count=retry_count
|
|
|
|
)
|
2023-12-20 17:08:04 +00:00
|
|
|
assert "result" in response or "foobar" in response
|
2023-12-04 18:50:05 +00:00
|
|
|
assert send_mock.call_count == retry_count
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("log_level", [logging.WARNING, logging.DEBUG])
|
|
|
|
async def test_protocol_logging(mocker, caplog, log_level):
|
|
|
|
caplog.set_level(log_level)
|
|
|
|
logging.getLogger("kasa").setLevel(log_level)
|
|
|
|
|
|
|
|
def _return_encrypted(*_, **__):
|
|
|
|
nonlocal encryption_session
|
|
|
|
# Do the encrypt just before returning the value so the incrementing sequence number is correct
|
|
|
|
encrypted, seq = encryption_session.encrypt('{"great":"success"}')
|
|
|
|
return 200, encrypted
|
|
|
|
|
|
|
|
seed = secrets.token_bytes(16)
|
2023-12-04 18:50:05 +00:00
|
|
|
auth_hash = KlapTransport.generate_auth_hash(Credentials("foo", "bar"))
|
2023-11-20 13:17:10 +00:00
|
|
|
encryption_session = KlapEncryptionSession(seed, seed, auth_hash)
|
2023-12-29 19:17:15 +00:00
|
|
|
|
|
|
|
config = DeviceConfig("127.0.0.1")
|
|
|
|
protocol = IotProtocol(transport=KlapTransport(config=config))
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
protocol._transport._handshake_done = True
|
|
|
|
protocol._transport._session_expire_at = time.time() + 86400
|
|
|
|
protocol._transport._encryption_session = encryption_session
|
2024-01-18 09:57:33 +00:00
|
|
|
mocker.patch.object(HttpClient, "post", side_effect=_return_encrypted)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
response = await protocol.query({})
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
if log_level == logging.DEBUG:
|
|
|
|
assert "success" in caplog.text
|
|
|
|
else:
|
|
|
|
assert "success" not in caplog.text
|
|
|
|
|
|
|
|
|
|
|
|
def test_encrypt():
|
|
|
|
d = json.dumps({"foo": 1, "bar": 2})
|
|
|
|
|
|
|
|
seed = secrets.token_bytes(16)
|
2023-12-04 18:50:05 +00:00
|
|
|
auth_hash = KlapTransport.generate_auth_hash(Credentials("foo", "bar"))
|
2023-11-20 13:17:10 +00:00
|
|
|
encryption_session = KlapEncryptionSession(seed, seed, auth_hash)
|
|
|
|
|
|
|
|
encrypted, seq = encryption_session.encrypt(d)
|
|
|
|
|
|
|
|
assert d == encryption_session.decrypt(encrypted)
|
|
|
|
|
|
|
|
|
|
|
|
def test_encrypt_unicode():
|
|
|
|
d = "{'snowman': '\u2603'}"
|
|
|
|
|
|
|
|
seed = secrets.token_bytes(16)
|
2023-12-04 18:50:05 +00:00
|
|
|
auth_hash = KlapTransport.generate_auth_hash(Credentials("foo", "bar"))
|
2023-11-20 13:17:10 +00:00
|
|
|
encryption_session = KlapEncryptionSession(seed, seed, auth_hash)
|
|
|
|
|
|
|
|
encrypted, seq = encryption_session.encrypt(d)
|
|
|
|
|
|
|
|
decrypted = encryption_session.decrypt(encrypted)
|
|
|
|
|
|
|
|
assert d == decrypted
|
|
|
|
|
|
|
|
|
2024-07-22 18:33:31 +00:00
|
|
|
async def test_transport_decrypt(mocker):
|
|
|
|
"""Test transport decryption."""
|
|
|
|
d = {"great": "success"}
|
|
|
|
|
|
|
|
seed = secrets.token_bytes(16)
|
|
|
|
auth_hash = KlapTransport.generate_auth_hash(Credentials("foo", "bar"))
|
|
|
|
encryption_session = KlapEncryptionSession(seed, seed, auth_hash)
|
|
|
|
|
|
|
|
transport = KlapTransport(config=DeviceConfig(host="127.0.0.1"))
|
|
|
|
transport._handshake_done = True
|
|
|
|
transport._session_expire_at = time.monotonic() + 60
|
|
|
|
transport._encryption_session = encryption_session
|
|
|
|
|
|
|
|
async def _return_response(url: URL, params=None, data=None, *_, **__):
|
|
|
|
encryption_session = KlapEncryptionSession(
|
|
|
|
transport._encryption_session.local_seed,
|
|
|
|
transport._encryption_session.remote_seed,
|
|
|
|
transport._encryption_session.user_hash,
|
|
|
|
)
|
|
|
|
seq = params.get("seq")
|
|
|
|
encryption_session._seq = seq - 1
|
|
|
|
encrypted, seq = encryption_session.encrypt(json.dumps(d))
|
|
|
|
seq = seq
|
|
|
|
return 200, encrypted
|
|
|
|
|
|
|
|
mocker.patch.object(HttpClient, "post", side_effect=_return_response)
|
|
|
|
|
|
|
|
resp = await transport.send(json.dumps({}))
|
|
|
|
assert d == resp
|
|
|
|
|
|
|
|
|
|
|
|
async def test_transport_decrypt_error(mocker, caplog):
|
|
|
|
"""Test that a decryption error raises a kasa exception."""
|
|
|
|
d = {"great": "success"}
|
|
|
|
|
|
|
|
seed = secrets.token_bytes(16)
|
|
|
|
auth_hash = KlapTransport.generate_auth_hash(Credentials("foo", "bar"))
|
|
|
|
encryption_session = KlapEncryptionSession(seed, seed, auth_hash)
|
|
|
|
|
|
|
|
transport = KlapTransport(config=DeviceConfig(host="127.0.0.1"))
|
|
|
|
transport._handshake_done = True
|
|
|
|
transport._session_expire_at = time.monotonic() + 60
|
|
|
|
transport._encryption_session = encryption_session
|
|
|
|
|
|
|
|
async def _return_response(url: URL, params=None, data=None, *_, **__):
|
|
|
|
encryption_session = KlapEncryptionSession(
|
|
|
|
secrets.token_bytes(16),
|
|
|
|
transport._encryption_session.remote_seed,
|
|
|
|
transport._encryption_session.user_hash,
|
|
|
|
)
|
|
|
|
seq = params.get("seq")
|
|
|
|
encryption_session._seq = seq - 1
|
|
|
|
encrypted, seq = encryption_session.encrypt(json.dumps(d))
|
|
|
|
seq = seq
|
|
|
|
return 200, encrypted
|
|
|
|
|
|
|
|
mocker.patch.object(HttpClient, "post", side_effect=_return_response)
|
|
|
|
|
|
|
|
with pytest.raises(
|
|
|
|
KasaException,
|
2024-07-24 17:58:37 +00:00
|
|
|
match=re.escape("Error trying to decrypt device 127.0.0.1 response:"),
|
2024-07-22 18:33:31 +00:00
|
|
|
):
|
|
|
|
await transport.send(json.dumps({}))
|
|
|
|
|
|
|
|
|
2023-11-20 13:17:10 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("device_credentials", "expectation"),
|
2023-11-20 13:17:10 +00:00
|
|
|
[
|
|
|
|
(Credentials("foo", "bar"), does_not_raise()),
|
2023-12-29 19:17:15 +00:00
|
|
|
(Credentials(), does_not_raise()),
|
2023-11-20 13:17:10 +00:00
|
|
|
(
|
2024-01-23 14:44:32 +00:00
|
|
|
get_default_credentials(DEFAULT_CREDENTIALS["KASA"]),
|
2023-11-20 13:17:10 +00:00
|
|
|
does_not_raise(),
|
|
|
|
),
|
|
|
|
(
|
|
|
|
Credentials("shouldfail", "shouldfail"),
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(AuthenticationError),
|
2023-11-20 13:17:10 +00:00
|
|
|
),
|
|
|
|
],
|
|
|
|
ids=("client", "blank", "kasa_setup", "shouldfail"),
|
|
|
|
)
|
2023-12-29 19:17:15 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("transport_class", "seed_auth_hash_calc"),
|
2023-12-29 19:17:15 +00:00
|
|
|
[
|
|
|
|
pytest.param(KlapTransport, lambda c, s, a: c + a, id="KLAP"),
|
|
|
|
pytest.param(KlapTransportV2, lambda c, s, a: c + s + a, id="KLAPV2"),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_handshake1(
|
|
|
|
mocker, device_credentials, expectation, transport_class, seed_auth_hash_calc
|
|
|
|
):
|
2023-11-20 13:17:10 +00:00
|
|
|
async def _return_handshake1_response(url, params=None, data=None, *_, **__):
|
|
|
|
nonlocal client_seed, server_seed, device_auth_hash
|
|
|
|
|
|
|
|
client_seed = data
|
2023-12-29 19:17:15 +00:00
|
|
|
seed_auth_hash = _sha256(
|
|
|
|
seed_auth_hash_calc(client_seed, server_seed, device_auth_hash)
|
|
|
|
)
|
|
|
|
return _mock_response(200, server_seed + seed_auth_hash)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
client_seed = None
|
|
|
|
server_seed = secrets.token_bytes(16)
|
|
|
|
client_credentials = Credentials("foo", "bar")
|
2023-12-29 19:17:15 +00:00
|
|
|
device_auth_hash = transport_class.generate_auth_hash(device_credentials)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
mocker.patch.object(
|
2024-01-18 17:32:26 +00:00
|
|
|
aiohttp.ClientSession, "post", side_effect=_return_handshake1_response
|
2023-11-20 13:17:10 +00:00
|
|
|
)
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1", credentials=client_credentials)
|
|
|
|
protocol = IotProtocol(transport=transport_class(config=config))
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
with expectation:
|
|
|
|
(
|
|
|
|
local_seed,
|
|
|
|
device_remote_seed,
|
|
|
|
auth_hash,
|
2023-12-04 18:50:05 +00:00
|
|
|
) = await protocol._transport.perform_handshake1()
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
assert local_seed == client_seed
|
|
|
|
assert device_remote_seed == server_seed
|
|
|
|
assert device_auth_hash == auth_hash
|
|
|
|
await protocol.close()
|
|
|
|
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("transport_class", "seed_auth_hash_calc1", "seed_auth_hash_calc2"),
|
2023-12-29 19:17:15 +00:00
|
|
|
[
|
|
|
|
pytest.param(
|
|
|
|
KlapTransport, lambda c, s, a: c + a, lambda c, s, a: s + a, id="KLAP"
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
KlapTransportV2,
|
|
|
|
lambda c, s, a: c + s + a,
|
|
|
|
lambda c, s, a: s + c + a,
|
|
|
|
id="KLAPV2",
|
|
|
|
),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_handshake(
|
|
|
|
mocker, transport_class, seed_auth_hash_calc1, seed_auth_hash_calc2
|
|
|
|
):
|
2024-01-29 15:26:00 +00:00
|
|
|
client_seed = None
|
|
|
|
server_seed = secrets.token_bytes(16)
|
|
|
|
client_credentials = Credentials("foo", "bar")
|
|
|
|
device_auth_hash = transport_class.generate_auth_hash(client_credentials)
|
|
|
|
|
|
|
|
async def _return_handshake_response(url: URL, params=None, data=None, *_, **__):
|
2023-12-29 19:17:15 +00:00
|
|
|
nonlocal client_seed, server_seed, device_auth_hash
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2024-09-06 14:27:23 +00:00
|
|
|
if url == URL("http://127.0.0.1:80/app/handshake1"):
|
2023-11-20 13:17:10 +00:00
|
|
|
client_seed = data
|
2023-12-29 19:17:15 +00:00
|
|
|
seed_auth_hash = _sha256(
|
|
|
|
seed_auth_hash_calc1(client_seed, server_seed, device_auth_hash)
|
|
|
|
)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
return _mock_response(200, server_seed + seed_auth_hash)
|
2024-09-06 14:27:23 +00:00
|
|
|
elif url == URL("http://127.0.0.1:80/app/handshake2"):
|
2023-12-29 19:17:15 +00:00
|
|
|
seed_auth_hash = _sha256(
|
|
|
|
seed_auth_hash_calc2(client_seed, server_seed, device_auth_hash)
|
|
|
|
)
|
|
|
|
assert data == seed_auth_hash
|
2023-11-20 13:17:10 +00:00
|
|
|
return _mock_response(response_status, b"")
|
|
|
|
|
|
|
|
mocker.patch.object(
|
2024-01-18 17:32:26 +00:00
|
|
|
aiohttp.ClientSession, "post", side_effect=_return_handshake_response
|
2023-11-20 13:17:10 +00:00
|
|
|
)
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1", credentials=client_credentials)
|
|
|
|
protocol = IotProtocol(transport=transport_class(config=config))
|
2024-01-18 17:32:26 +00:00
|
|
|
protocol._transport.http_client = aiohttp.ClientSession()
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
response_status = 200
|
2023-12-04 18:50:05 +00:00
|
|
|
await protocol._transport.perform_handshake()
|
|
|
|
assert protocol._transport._handshake_done is True
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
response_status = 403
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2023-12-04 18:50:05 +00:00
|
|
|
await protocol._transport.perform_handshake()
|
|
|
|
assert protocol._transport._handshake_done is False
|
2023-11-20 13:17:10 +00:00
|
|
|
await protocol.close()
|
|
|
|
|
|
|
|
|
|
|
|
async def test_query(mocker):
|
2024-01-29 15:26:00 +00:00
|
|
|
client_seed = None
|
|
|
|
last_seq = None
|
|
|
|
seq = None
|
|
|
|
server_seed = secrets.token_bytes(16)
|
|
|
|
client_credentials = Credentials("foo", "bar")
|
|
|
|
device_auth_hash = KlapTransport.generate_auth_hash(client_credentials)
|
|
|
|
|
|
|
|
async def _return_response(url: URL, params=None, data=None, *_, **__):
|
2023-12-29 19:17:15 +00:00
|
|
|
nonlocal client_seed, server_seed, device_auth_hash, seq
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2024-09-06 14:27:23 +00:00
|
|
|
if url == URL("http://127.0.0.1:80/app/handshake1"):
|
2023-11-20 13:17:10 +00:00
|
|
|
client_seed = data
|
|
|
|
client_seed_auth_hash = _sha256(data + device_auth_hash)
|
|
|
|
|
|
|
|
return _mock_response(200, server_seed + client_seed_auth_hash)
|
2024-09-06 14:27:23 +00:00
|
|
|
elif url == URL("http://127.0.0.1:80/app/handshake2"):
|
2023-11-20 13:17:10 +00:00
|
|
|
return _mock_response(200, b"")
|
2024-09-06 14:27:23 +00:00
|
|
|
elif url == URL("http://127.0.0.1:80/app/request"):
|
2023-11-20 13:17:10 +00:00
|
|
|
encryption_session = KlapEncryptionSession(
|
2023-12-04 18:50:05 +00:00
|
|
|
protocol._transport._encryption_session.local_seed,
|
|
|
|
protocol._transport._encryption_session.remote_seed,
|
|
|
|
protocol._transport._encryption_session.user_hash,
|
2023-11-20 13:17:10 +00:00
|
|
|
)
|
|
|
|
seq = params.get("seq")
|
|
|
|
encryption_session._seq = seq - 1
|
|
|
|
encrypted, seq = encryption_session.encrypt('{"great": "success"}')
|
|
|
|
seq = seq
|
|
|
|
return _mock_response(200, encrypted)
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
mocker.patch.object(aiohttp.ClientSession, "post", side_effect=_return_response)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1", credentials=client_credentials)
|
|
|
|
protocol = IotProtocol(transport=KlapTransport(config=config))
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
for _ in range(10):
|
|
|
|
resp = await protocol.query({})
|
|
|
|
assert resp == {"great": "success"}
|
|
|
|
# Check the protocol is incrementing the sequence number
|
|
|
|
assert last_seq is None or last_seq + 1 == seq
|
|
|
|
last_seq = seq
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("response_status", "credentials_match", "expectation"),
|
2023-11-20 13:17:10 +00:00
|
|
|
[
|
2024-02-05 20:49:26 +00:00
|
|
|
pytest.param(
|
|
|
|
(403, 403, 403),
|
|
|
|
True,
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(KasaException),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="handshake1-403-status",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
(200, 403, 403),
|
|
|
|
True,
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(KasaException),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="handshake2-403-status",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
(200, 200, 403),
|
|
|
|
True,
|
2024-02-22 17:02:03 +00:00
|
|
|
pytest.raises(_RetryableError),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="request-403-status",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
(200, 200, 400),
|
|
|
|
True,
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(KasaException),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="request-400-status",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
(200, 200, 200),
|
|
|
|
False,
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(AuthenticationError),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="handshake1-wrong-auth",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
(200, 200, 200),
|
|
|
|
secrets.token_bytes(16),
|
2024-02-21 15:52:55 +00:00
|
|
|
pytest.raises(KasaException),
|
2024-02-05 20:49:26 +00:00
|
|
|
id="handshake1-bad-auth-length",
|
|
|
|
),
|
2023-11-20 13:17:10 +00:00
|
|
|
],
|
|
|
|
)
|
2024-02-05 20:49:26 +00:00
|
|
|
async def test_authentication_failures(
|
|
|
|
mocker, response_status, credentials_match, expectation
|
|
|
|
):
|
2024-01-29 15:26:00 +00:00
|
|
|
client_seed = None
|
|
|
|
|
|
|
|
server_seed = secrets.token_bytes(16)
|
|
|
|
client_credentials = Credentials("foo", "bar")
|
2024-02-05 20:49:26 +00:00
|
|
|
device_credentials = (
|
|
|
|
client_credentials if credentials_match else Credentials("bar", "foo")
|
|
|
|
)
|
|
|
|
device_auth_hash = KlapTransport.generate_auth_hash(device_credentials)
|
2024-01-29 15:26:00 +00:00
|
|
|
|
|
|
|
async def _return_response(url: URL, params=None, data=None, *_, **__):
|
2024-02-05 20:49:26 +00:00
|
|
|
nonlocal \
|
|
|
|
client_seed, \
|
|
|
|
server_seed, \
|
|
|
|
device_auth_hash, \
|
|
|
|
response_status, \
|
|
|
|
credentials_match
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2024-09-06 14:27:23 +00:00
|
|
|
if url == URL("http://127.0.0.1:80/app/handshake1"):
|
2023-11-20 13:17:10 +00:00
|
|
|
client_seed = data
|
|
|
|
client_seed_auth_hash = _sha256(data + device_auth_hash)
|
2024-02-05 20:49:26 +00:00
|
|
|
if credentials_match is not False and credentials_match is not True:
|
|
|
|
client_seed_auth_hash += credentials_match
|
2023-11-20 13:17:10 +00:00
|
|
|
return _mock_response(
|
|
|
|
response_status[0], server_seed + client_seed_auth_hash
|
|
|
|
)
|
2024-09-06 14:27:23 +00:00
|
|
|
elif url == URL("http://127.0.0.1:80/app/handshake2"):
|
2024-02-05 20:49:26 +00:00
|
|
|
client_seed = data
|
|
|
|
client_seed_auth_hash = _sha256(data + device_auth_hash)
|
|
|
|
return _mock_response(
|
|
|
|
response_status[1], server_seed + client_seed_auth_hash
|
|
|
|
)
|
2024-09-06 14:27:23 +00:00
|
|
|
elif url == URL("http://127.0.0.1:80/app/request"):
|
2024-01-29 15:26:00 +00:00
|
|
|
return _mock_response(response_status[2], b"")
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
mocker.patch.object(aiohttp.ClientSession, "post", side_effect=_return_response)
|
2023-11-20 13:17:10 +00:00
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1", credentials=client_credentials)
|
|
|
|
protocol = IotProtocol(transport=KlapTransport(config=config))
|
2023-11-20 13:17:10 +00:00
|
|
|
|
|
|
|
with expectation:
|
|
|
|
await protocol.query({})
|
2024-02-03 14:28:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def test_port_override():
|
|
|
|
"""Test that port override sets the app_url."""
|
|
|
|
host = "127.0.0.1"
|
|
|
|
config = DeviceConfig(
|
|
|
|
host, credentials=Credentials("foo", "bar"), port_override=12345
|
|
|
|
)
|
|
|
|
transport = KlapTransport(config=config)
|
|
|
|
|
|
|
|
assert str(transport._app_url) == "http://127.0.0.1:12345/app"
|