python-kasa 0.7.0.4__py3-none-any.whl → 0.7.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kasa/discover.py CHANGED
@@ -87,7 +87,8 @@ import ipaddress
87
87
  import logging
88
88
  import socket
89
89
  from collections.abc import Awaitable
90
- from typing import Callable, Dict, Optional, Type, cast
90
+ from pprint import pformat as pf
91
+ from typing import Any, Callable, Dict, Optional, Type, cast
91
92
 
92
93
  # When support for cpython older than 3.11 is dropped
93
94
  # async_timeout can be replaced with asyncio.timeout
@@ -112,8 +113,10 @@ from kasa.exceptions import (
112
113
  UnsupportedDeviceError,
113
114
  )
114
115
  from kasa.iot.iotdevice import IotDevice
116
+ from kasa.iotprotocol import REDACTORS as IOT_REDACTORS
115
117
  from kasa.json import dumps as json_dumps
116
118
  from kasa.json import loads as json_loads
119
+ from kasa.protocol import mask_mac, redact_data
117
120
  from kasa.xortransport import XorEncryption
118
121
 
119
122
  _LOGGER = logging.getLogger(__name__)
@@ -123,6 +126,12 @@ OnDiscoveredCallable = Callable[[Device], Awaitable[None]]
123
126
  OnUnsupportedCallable = Callable[[UnsupportedDeviceError], Awaitable[None]]
124
127
  DeviceDict = Dict[str, Device]
125
128
 
129
+ NEW_DISCOVERY_REDACTORS: dict[str, Callable[[Any], Any] | None] = {
130
+ "device_id": lambda x: "REDACTED_" + x[9::],
131
+ "owner": lambda x: "REDACTED_" + x[9::],
132
+ "mac": mask_mac,
133
+ }
134
+
126
135
 
127
136
  class _DiscoverProtocol(asyncio.DatagramProtocol):
128
137
  """Implementation of the discovery protocol handler.
@@ -293,6 +302,8 @@ class Discover:
293
302
  DISCOVERY_PORT_2 = 20002
294
303
  DISCOVERY_QUERY_2 = binascii.unhexlify("020000010000000000000000463cb5d3")
295
304
 
305
+ _redact_data = True
306
+
296
307
  @staticmethod
297
308
  async def discover(
298
309
  *,
@@ -484,7 +495,9 @@ class Discover:
484
495
  f"Unable to read response from device: {config.host}: {ex}"
485
496
  ) from ex
486
497
 
487
- _LOGGER.debug("[DISCOVERY] %s << %s", config.host, info)
498
+ if _LOGGER.isEnabledFor(logging.DEBUG):
499
+ data = redact_data(info, IOT_REDACTORS) if Discover._redact_data else info
500
+ _LOGGER.debug("[DISCOVERY] %s << %s", config.host, pf(data))
488
501
 
489
502
  device_class = cast(Type[IotDevice], Discover._get_device_class(info))
490
503
  device = device_class(config.host, config=config)
@@ -504,6 +517,7 @@ class Discover:
504
517
  config: DeviceConfig,
505
518
  ) -> Device:
506
519
  """Get SmartDevice from the new 20002 response."""
520
+ debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
507
521
  try:
508
522
  info = json_loads(data[16:])
509
523
  except Exception as ex:
@@ -514,9 +528,17 @@ class Discover:
514
528
  try:
515
529
  discovery_result = DiscoveryResult(**info["result"])
516
530
  except ValidationError as ex:
517
- _LOGGER.debug(
518
- "Unable to parse discovery from device %s: %s", config.host, info
519
- )
531
+ if debug_enabled:
532
+ data = (
533
+ redact_data(info, NEW_DISCOVERY_REDACTORS)
534
+ if Discover._redact_data
535
+ else info
536
+ )
537
+ _LOGGER.debug(
538
+ "Unable to parse discovery from device %s: %s",
539
+ config.host,
540
+ pf(data),
541
+ )
520
542
  raise UnsupportedDeviceError(
521
543
  f"Unable to parse discovery from device: {config.host}: {ex}"
522
544
  ) from ex
@@ -551,7 +573,13 @@ class Discover:
551
573
  discovery_result=discovery_result.get_dict(),
552
574
  )
553
575
 
554
- _LOGGER.debug("[DISCOVERY] %s << %s", config.host, info)
576
+ if debug_enabled:
577
+ data = (
578
+ redact_data(info, NEW_DISCOVERY_REDACTORS)
579
+ if Discover._redact_data
580
+ else info
581
+ )
582
+ _LOGGER.debug("[DISCOVERY] %s << %s", config.host, pf(data))
555
583
  device = device_class(config.host, protocol=protocol)
556
584
 
557
585
  di = discovery_result.get_dict()
kasa/iotprotocol.py CHANGED
@@ -4,6 +4,8 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import logging
7
+ from pprint import pformat as pf
8
+ from typing import Any, Callable
7
9
 
8
10
  from .deviceconfig import DeviceConfig
9
11
  from .exceptions import (
@@ -14,11 +16,26 @@ from .exceptions import (
14
16
  _RetryableError,
15
17
  )
16
18
  from .json import dumps as json_dumps
17
- from .protocol import BaseProtocol, BaseTransport
19
+ from .protocol import BaseProtocol, BaseTransport, mask_mac, redact_data
18
20
  from .xortransport import XorEncryption, XorTransport
19
21
 
20
22
  _LOGGER = logging.getLogger(__name__)
21
23
 
24
+ REDACTORS: dict[str, Callable[[Any], Any] | None] = {
25
+ "latitude": lambda x: 0,
26
+ "longitude": lambda x: 0,
27
+ "latitude_i": lambda x: 0,
28
+ "longitude_i": lambda x: 0,
29
+ "deviceId": lambda x: "REDACTED_" + x[9::],
30
+ "id": lambda x: "REDACTED_" + x[9::],
31
+ "alias": lambda x: "#MASKED_NAME#" if x else "",
32
+ "mac": mask_mac,
33
+ "mic_mac": mask_mac,
34
+ "ssid": lambda x: "#MASKED_SSID#" if x else "",
35
+ "oemId": lambda x: "REDACTED_" + x[9::],
36
+ "username": lambda _: "user@example.com", # cnCloud
37
+ }
38
+
22
39
 
23
40
  class IotProtocol(BaseProtocol):
24
41
  """Class for the legacy TPLink IOT KASA Protocol."""
@@ -34,6 +51,7 @@ class IotProtocol(BaseProtocol):
34
51
  super().__init__(transport=transport)
35
52
 
36
53
  self._query_lock = asyncio.Lock()
54
+ self._redact_data = True
37
55
 
38
56
  async def query(self, request: str | dict, retry_count: int = 3) -> dict:
39
57
  """Query the device retrying for retry_count on failure."""
@@ -85,7 +103,24 @@ class IotProtocol(BaseProtocol):
85
103
  raise KasaException("Query reached somehow to unreachable")
86
104
 
87
105
  async def _execute_query(self, request: str, retry_count: int) -> dict:
88
- return await self._transport.send(request)
106
+ debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
107
+
108
+ if debug_enabled:
109
+ _LOGGER.debug(
110
+ "%s >> %s",
111
+ self._host,
112
+ request,
113
+ )
114
+ resp = await self._transport.send(request)
115
+
116
+ if debug_enabled:
117
+ data = redact_data(resp, REDACTORS) if self._redact_data else resp
118
+ _LOGGER.debug(
119
+ "%s << %s",
120
+ self._host,
121
+ pf(data),
122
+ )
123
+ return resp
89
124
 
90
125
  async def close(self) -> None:
91
126
  """Close the underlying transport."""
kasa/klaptransport.py CHANGED
@@ -50,7 +50,6 @@ import logging
50
50
  import secrets
51
51
  import struct
52
52
  import time
53
- from pprint import pformat as pf
54
53
  from typing import Any, cast
55
54
 
56
55
  from cryptography.hazmat.primitives import padding
@@ -349,7 +348,7 @@ class KlapTransport(BaseTransport):
349
348
  + f"request with seq {seq}"
350
349
  )
351
350
  else:
352
- _LOGGER.debug("Query posted " + msg)
351
+ _LOGGER.debug("Device %s query posted %s", self._host, msg)
353
352
 
354
353
  # Check for mypy
355
354
  if self._encryption_session is not None:
@@ -357,11 +356,7 @@ class KlapTransport(BaseTransport):
357
356
 
358
357
  json_payload = json_loads(decrypted_response)
359
358
 
360
- _LOGGER.debug(
361
- "%s << %s",
362
- self._host,
363
- _LOGGER.isEnabledFor(logging.DEBUG) and pf(json_payload),
364
- )
359
+ _LOGGER.debug("Device %s query response received", self._host)
365
360
 
366
361
  return json_payload
367
362
 
kasa/protocol.py CHANGED
@@ -18,6 +18,7 @@ import hashlib
18
18
  import logging
19
19
  import struct
20
20
  from abc import ABC, abstractmethod
21
+ from typing import Any, Callable, TypeVar, cast
21
22
 
22
23
  # When support for cpython older than 3.11 is dropped
23
24
  # async_timeout can be replaced with asyncio.timeout
@@ -28,6 +29,46 @@ _LOGGER = logging.getLogger(__name__)
28
29
  _NO_RETRY_ERRORS = {errno.EHOSTDOWN, errno.EHOSTUNREACH, errno.ECONNREFUSED}
29
30
  _UNSIGNED_INT_NETWORK_ORDER = struct.Struct(">I")
30
31
 
32
+ _T = TypeVar("_T")
33
+
34
+
35
+ def redact_data(data: _T, redactors: dict[str, Callable[[Any], Any] | None]) -> _T:
36
+ """Redact sensitive data for logging."""
37
+ if not isinstance(data, (dict, list)):
38
+ return data
39
+
40
+ if isinstance(data, list):
41
+ return cast(_T, [redact_data(val, redactors) for val in data])
42
+
43
+ redacted = {**data}
44
+
45
+ for key, value in redacted.items():
46
+ if value is None:
47
+ continue
48
+ if isinstance(value, str) and not value:
49
+ continue
50
+ if key in redactors:
51
+ if redactor := redactors[key]:
52
+ try:
53
+ redacted[key] = redactor(value)
54
+ except: # noqa: E722
55
+ redacted[key] = "**REDACTEX**"
56
+ else:
57
+ redacted[key] = "**REDACTED**"
58
+ elif isinstance(value, dict):
59
+ redacted[key] = redact_data(value, redactors)
60
+ elif isinstance(value, list):
61
+ redacted[key] = [redact_data(item, redactors) for item in value]
62
+
63
+ return cast(_T, redacted)
64
+
65
+
66
+ def mask_mac(mac: str) -> str:
67
+ """Return mac address with last two octects blanked."""
68
+ delim = ":" if ":" in mac else "-"
69
+ rest = delim.join(format(s, "02x") for s in bytes.fromhex("000000"))
70
+ return f"{mac[:8]}{delim}{rest}"
71
+
31
72
 
32
73
  def md5(payload: bytes) -> bytes:
33
74
  """Return the MD5 hash of the payload."""
@@ -17,7 +17,7 @@ class LightEffect(SmartModule, SmartLightEffect):
17
17
 
18
18
  REQUIRED_COMPONENT = "light_effect"
19
19
  QUERY_GETTER_NAME = "get_dynamic_light_effect_rules"
20
- MINIMUM_UPDATE_INTERVAL_SECS = 60
20
+ MINIMUM_UPDATE_INTERVAL_SECS = 60 * 60 * 24
21
21
  AVAILABLE_BULB_EFFECTS = {
22
22
  "L1": "Party",
23
23
  "L2": "Relax",
@@ -74,6 +74,7 @@ class LightEffect(SmartModule, SmartLightEffect):
74
74
  """Return effect name."""
75
75
  return self._effect
76
76
 
77
+ @allow_update_after
77
78
  async def set_effect(
78
79
  self,
79
80
  effect: str,
kasa/smart/smartdevice.py CHANGED
@@ -193,11 +193,9 @@ class SmartDevice(Device):
193
193
  if not self._features:
194
194
  await self._initialize_features()
195
195
 
196
- _LOGGER.debug(
197
- "Update completed %s: %s",
198
- self.host,
199
- self._last_update if first_update else resp,
200
- )
196
+ if _LOGGER.isEnabledFor(logging.DEBUG):
197
+ updated = self._last_update if first_update else resp
198
+ _LOGGER.debug("Update completed %s: %s", self.host, list(updated.keys()))
201
199
 
202
200
  def _handle_module_post_update_hook(self, module: SmartModule) -> bool:
203
201
  try:
kasa/smartprotocol.py CHANGED
@@ -12,7 +12,7 @@ import logging
12
12
  import time
13
13
  import uuid
14
14
  from pprint import pformat as pf
15
- from typing import Any
15
+ from typing import Any, Callable
16
16
 
17
17
  from .exceptions import (
18
18
  SMART_AUTHENTICATION_ERRORS,
@@ -26,10 +26,31 @@ from .exceptions import (
26
26
  _RetryableError,
27
27
  )
28
28
  from .json import dumps as json_dumps
29
- from .protocol import BaseProtocol, BaseTransport, md5
29
+ from .protocol import BaseProtocol, BaseTransport, mask_mac, md5, redact_data
30
30
 
31
31
  _LOGGER = logging.getLogger(__name__)
32
32
 
33
+ REDACTORS: dict[str, Callable[[Any], Any] | None] = {
34
+ "latitude": lambda x: 0,
35
+ "longitude": lambda x: 0,
36
+ "la": lambda x: 0, # lat on ks240
37
+ "lo": lambda x: 0, # lon on ks240
38
+ "device_id": lambda x: "REDACTED_" + x[9::],
39
+ "parent_device_id": lambda x: "REDACTED_" + x[9::], # Hub attached children
40
+ "original_device_id": lambda x: "REDACTED_" + x[9::], # Strip children
41
+ "nickname": lambda x: "I01BU0tFRF9OQU1FIw==" if x else "",
42
+ "mac": mask_mac,
43
+ "ssid": lambda x: "I01BU0tFRF9TU0lEIw=" if x else "",
44
+ "bssid": lambda _: "000000000000",
45
+ "oem_id": lambda x: "REDACTED_" + x[9::],
46
+ "setup_code": None, # matter
47
+ "setup_payload": None, # matter
48
+ "mfi_setup_code": None, # mfi_ for homekit
49
+ "mfi_setup_id": None,
50
+ "mfi_token_token": None,
51
+ "mfi_token_uuid": None,
52
+ }
53
+
33
54
 
34
55
  class SmartProtocol(BaseProtocol):
35
56
  """Class for the new TPLink SMART protocol."""
@@ -50,6 +71,7 @@ class SmartProtocol(BaseProtocol):
50
71
  self._multi_request_batch_size = (
51
72
  self._transport._config.batch_size or self.DEFAULT_MULTI_REQUEST_BATCH_SIZE
52
73
  )
74
+ self._redact_data = True
53
75
 
54
76
  def get_smart_request(self, method, params=None) -> str:
55
77
  """Get a request message as a string."""
@@ -167,11 +189,15 @@ class SmartProtocol(BaseProtocol):
167
189
  )
168
190
  response_step = await self._transport.send(smart_request)
169
191
  if debug_enabled:
192
+ if self._redact_data:
193
+ data = redact_data(response_step, REDACTORS)
194
+ else:
195
+ data = response_step
170
196
  _LOGGER.debug(
171
197
  "%s %s << %s",
172
198
  self._host,
173
199
  batch_name,
174
- pf(response_step),
200
+ pf(data),
175
201
  )
176
202
  try:
177
203
  self._handle_response_error_code(response_step, batch_name)
@@ -90,21 +90,26 @@ def create_discovery_mock(ip: str, fixture_data: dict):
90
90
  query_data: dict
91
91
  device_type: str
92
92
  encrypt_type: str
93
- _datagram: bytes
94
93
  login_version: int | None = None
95
94
  port_override: int | None = None
96
95
 
96
+ @property
97
+ def _datagram(self) -> bytes:
98
+ if self.default_port == 9999:
99
+ return XorEncryption.encrypt(json_dumps(self.discovery_data))[4:]
100
+ else:
101
+ return (
102
+ b"\x02\x00\x00\x01\x01[\x00\x00\x00\x00\x00\x00W\xcev\xf8"
103
+ + json_dumps(self.discovery_data).encode()
104
+ )
105
+
97
106
  if "discovery_result" in fixture_data:
98
- discovery_data = {"result": fixture_data["discovery_result"]}
107
+ discovery_data = {"result": fixture_data["discovery_result"].copy()}
99
108
  device_type = fixture_data["discovery_result"]["device_type"]
100
109
  encrypt_type = fixture_data["discovery_result"]["mgt_encrypt_schm"][
101
110
  "encrypt_type"
102
111
  ]
103
112
  login_version = fixture_data["discovery_result"]["mgt_encrypt_schm"].get("lv")
104
- datagram = (
105
- b"\x02\x00\x00\x01\x01[\x00\x00\x00\x00\x00\x00W\xcev\xf8"
106
- + json_dumps(discovery_data).encode()
107
- )
108
113
  dm = _DiscoveryMock(
109
114
  ip,
110
115
  80,
@@ -113,16 +118,14 @@ def create_discovery_mock(ip: str, fixture_data: dict):
113
118
  fixture_data,
114
119
  device_type,
115
120
  encrypt_type,
116
- datagram,
117
121
  login_version,
118
122
  )
119
123
  else:
120
124
  sys_info = fixture_data["system"]["get_sysinfo"]
121
- discovery_data = {"system": {"get_sysinfo": sys_info}}
125
+ discovery_data = {"system": {"get_sysinfo": sys_info.copy()}}
122
126
  device_type = sys_info.get("mic_type") or sys_info.get("type")
123
127
  encrypt_type = "XOR"
124
128
  login_version = None
125
- datagram = XorEncryption.encrypt(json_dumps(discovery_data))[4:]
126
129
  dm = _DiscoveryMock(
127
130
  ip,
128
131
  9999,
@@ -131,7 +134,6 @@ def create_discovery_mock(ip: str, fixture_data: dict):
131
134
  fixture_data,
132
135
  device_type,
133
136
  encrypt_type,
134
- datagram,
135
137
  login_version,
136
138
  )
137
139
 
@@ -2,6 +2,7 @@
2
2
  # ruff: noqa: S106
3
3
 
4
4
  import asyncio
5
+ import logging
5
6
  import re
6
7
  import socket
7
8
  from unittest.mock import MagicMock
@@ -565,3 +566,38 @@ async def test_do_discover_external_cancel(mocker):
565
566
  with pytest.raises(asyncio.TimeoutError):
566
567
  async with asyncio_timeout(0):
567
568
  await dp.wait_for_discovery_to_complete()
569
+
570
+
571
+ async def test_discovery_redaction(discovery_mock, caplog: pytest.LogCaptureFixture):
572
+ """Test query sensitive info redaction."""
573
+ mac = "12:34:56:78:9A:BC"
574
+
575
+ if discovery_mock.default_port == 9999:
576
+ sysinfo = discovery_mock.discovery_data["system"]["get_sysinfo"]
577
+ if "mac" in sysinfo:
578
+ sysinfo["mac"] = mac
579
+ elif "mic_mac" in sysinfo:
580
+ sysinfo["mic_mac"] = mac
581
+ else:
582
+ discovery_mock.discovery_data["result"]["mac"] = mac
583
+
584
+ # Info no message logging
585
+ caplog.set_level(logging.INFO)
586
+ await Discover.discover()
587
+
588
+ assert mac not in caplog.text
589
+
590
+ caplog.set_level(logging.DEBUG)
591
+
592
+ # Debug no redaction
593
+ caplog.clear()
594
+ Discover._redact_data = False
595
+ await Discover.discover()
596
+ assert mac in caplog.text
597
+
598
+ # Debug redaction
599
+ caplog.clear()
600
+ Discover._redact_data = True
601
+ await Discover.discover()
602
+ assert mac not in caplog.text
603
+ assert "12:34:56:00:00:00" in caplog.text
@@ -8,9 +8,12 @@ import os
8
8
  import pkgutil
9
9
  import struct
10
10
  import sys
11
+ from typing import cast
11
12
 
12
13
  import pytest
13
14
 
15
+ from kasa.iot import IotDevice
16
+
14
17
  from ..aestransport import AesTransport
15
18
  from ..credentials import Credentials
16
19
  from ..deviceconfig import DeviceConfig
@@ -20,8 +23,12 @@ from ..klaptransport import KlapTransport, KlapTransportV2
20
23
  from ..protocol import (
21
24
  BaseProtocol,
22
25
  BaseTransport,
26
+ mask_mac,
27
+ redact_data,
23
28
  )
24
29
  from ..xortransport import XorEncryption, XorTransport
30
+ from .conftest import device_iot
31
+ from .fakeprotocol_iot import FakeIotTransport
25
32
 
26
33
 
27
34
  @pytest.mark.parametrize(
@@ -614,3 +621,63 @@ def test_deprecated_protocol():
614
621
  host = "127.0.0.1"
615
622
  proto = TPLinkSmartHomeProtocol(host=host)
616
623
  assert proto.config.host == host
624
+
625
+
626
+ @device_iot
627
+ async def test_iot_queries_redaction(dev: IotDevice, caplog: pytest.LogCaptureFixture):
628
+ """Test query sensitive info redaction."""
629
+ device_id = "123456789ABCDEF"
630
+ cast(FakeIotTransport, dev.protocol._transport).proto["system"]["get_sysinfo"][
631
+ "deviceId"
632
+ ] = device_id
633
+
634
+ # Info no message logging
635
+ caplog.set_level(logging.INFO)
636
+ await dev.update()
637
+ assert device_id not in caplog.text
638
+
639
+ caplog.set_level(logging.DEBUG, logger="kasa")
640
+ # The fake iot protocol also logs so disable it
641
+ test_logger = logging.getLogger("kasa.tests.fakeprotocol_iot")
642
+ test_logger.setLevel(logging.INFO)
643
+
644
+ # Debug no redaction
645
+ caplog.clear()
646
+ cast(IotProtocol, dev.protocol)._redact_data = False
647
+ await dev.update()
648
+ assert device_id in caplog.text
649
+
650
+ # Debug redaction
651
+ caplog.clear()
652
+ cast(IotProtocol, dev.protocol)._redact_data = True
653
+ await dev.update()
654
+ assert device_id not in caplog.text
655
+ assert "REDACTED_" + device_id[9::] in caplog.text
656
+
657
+
658
+ async def test_redact_data():
659
+ """Test redact data function."""
660
+ data = {
661
+ "device_id": "123456789ABCDEF",
662
+ "owner": "0987654",
663
+ "mac": "12:34:56:78:90:AB",
664
+ "ip": "192.168.1",
665
+ "no_val": None,
666
+ }
667
+ excpected_data = {
668
+ "device_id": "REDACTED_ABCDEF",
669
+ "owner": "**REDACTED**",
670
+ "mac": "12:34:56:00:00:00",
671
+ "ip": "**REDACTEX**",
672
+ "no_val": None,
673
+ }
674
+ REDACTORS = {
675
+ "device_id": lambda x: "REDACTED_" + x[9::],
676
+ "owner": None,
677
+ "mac": mask_mac,
678
+ "ip": lambda x: "127.0.0." + x.split(".")[3],
679
+ }
680
+
681
+ redacted_data = redact_data(data, REDACTORS)
682
+
683
+ assert redacted_data == excpected_data
@@ -1,8 +1,11 @@
1
1
  import logging
2
+ from typing import cast
2
3
 
3
4
  import pytest
4
5
  import pytest_mock
5
6
 
7
+ from kasa.smart import SmartDevice
8
+
6
9
  from ..exceptions import (
7
10
  SMART_RETRYABLE_ERRORS,
8
11
  DeviceError,
@@ -10,6 +13,7 @@ from ..exceptions import (
10
13
  SmartErrorCode,
11
14
  )
12
15
  from ..smartprotocol import SmartProtocol, _ChildProtocolWrapper
16
+ from .conftest import device_smart
13
17
  from .fakeprotocol_smart import FakeSmartTransport
14
18
 
15
19
  DUMMY_QUERY = {"foobar": {"foo": "bar", "bar": "foo"}}
@@ -409,3 +413,34 @@ async def test_incomplete_list(mocker, caplog):
409
413
  "Device 127.0.0.123 returned empty results list for method get_preset_rules"
410
414
  in caplog.text
411
415
  )
416
+
417
+
418
+ @device_smart
419
+ async def test_smart_queries_redaction(
420
+ dev: SmartDevice, caplog: pytest.LogCaptureFixture
421
+ ):
422
+ """Test query sensitive info redaction."""
423
+ device_id = "123456789ABCDEF"
424
+ cast(FakeSmartTransport, dev.protocol._transport).info["get_device_info"][
425
+ "device_id"
426
+ ] = device_id
427
+
428
+ # Info no message logging
429
+ caplog.set_level(logging.INFO)
430
+ await dev.update()
431
+ assert device_id not in caplog.text
432
+
433
+ caplog.set_level(logging.DEBUG)
434
+
435
+ # Debug no redaction
436
+ caplog.clear()
437
+ dev.protocol._redact_data = False
438
+ await dev.update()
439
+ assert device_id in caplog.text
440
+
441
+ # Debug redaction
442
+ caplog.clear()
443
+ dev.protocol._redact_data = True
444
+ await dev.update()
445
+ assert device_id not in caplog.text
446
+ assert "REDACTED_" + device_id[9::] in caplog.text
kasa/xortransport.py CHANGED
@@ -19,7 +19,6 @@ import logging
19
19
  import socket
20
20
  import struct
21
21
  from collections.abc import Generator
22
- from pprint import pformat as pf
23
22
 
24
23
  # When support for cpython older than 3.11 is dropped
25
24
  # async_timeout can be replaced with asyncio.timeout
@@ -78,9 +77,8 @@ class XorTransport(BaseTransport):
78
77
  """Execute a query on the device and wait for the response."""
79
78
  assert self.writer is not None # noqa: S101
80
79
  assert self.reader is not None # noqa: S101
81
- debug_log = _LOGGER.isEnabledFor(logging.DEBUG)
82
- if debug_log:
83
- _LOGGER.debug("%s >> %s", self._host, request)
80
+ _LOGGER.debug("Device %s sending query %s", self._host, request)
81
+
84
82
  self.writer.write(XorEncryption.encrypt(request))
85
83
  await self.writer.drain()
86
84
 
@@ -90,8 +88,8 @@ class XorTransport(BaseTransport):
90
88
  buffer = await self.reader.readexactly(length)
91
89
  response = XorEncryption.decrypt(buffer)
92
90
  json_payload = json_loads(response)
93
- if debug_log:
94
- _LOGGER.debug("%s << %s", self._host, pf(json_payload))
91
+
92
+ _LOGGER.debug("Device %s query response received", self._host)
95
93
 
96
94
  return json_payload
97
95
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-kasa
3
- Version: 0.7.0.4
3
+ Version: 0.7.0.5
4
4
  Summary: Python API for TP-Link Kasa Smarthome devices
5
5
  Home-page: https://github.com/python-kasa/python-kasa
6
6
  License: GPL-3.0-or-later
@@ -6,7 +6,7 @@ kasa/device.py,sha256=RA229EkOoqXFohRiIWqAZ-hgL_HyMaID3OMO-IRINO8,17150
6
6
  kasa/device_factory.py,sha256=ct22rdnDqXONBc5PMeY_hii84Jy8ncWfkyEq2ZzfheA,6996
7
7
  kasa/device_type.py,sha256=MJW1bVoAcH_MILSW8IBpv3jKRbPWkxmvuWdU-7Ov_D0,744
8
8
  kasa/deviceconfig.py,sha256=F7ObHVaV2iu_X63Azwd8Wxu14i3j_HPrbPZPqsbO9DE,8022
9
- kasa/discover.py,sha256=-YSM4z338cGzQN30kXQcq34vEcNBDrqTHAdK4lT54LM,22538
9
+ kasa/discover.py,sha256=i3fvRNHgamCf50QE3R2C2aqjE_mziLAfC1t9LPheNKI,23557
10
10
  kasa/emeterstatus.py,sha256=-F0QAXR13jmfgdzjMjgLUY3LhEWRqceJ8zkB53HIX1Y,2529
11
11
  kasa/exceptions.py,sha256=Wek1F49MNEsw9xBS7tpzHi92ZeECM7sI_V13RoQ4UoI,4237
12
12
  kasa/feature.py,sha256=TNlaC3CZi1o3fdTune5VT3VQ_4XxExssVakH-t0Xn8k,10036
@@ -42,13 +42,13 @@ kasa/iot/modules/rulemodule.py,sha256=_QgsgMRvnh2M2xLx0ACvPdhn_3LZ9zwTbhpT5oQqxv
42
42
  kasa/iot/modules/schedule.py,sha256=r9MbXp4CRV8qKPlSXWY5RpHqkT6ULdLGLg8P857sEqI,151
43
43
  kasa/iot/modules/time.py,sha256=4cuogMUfHEcbQ3kCVKuD1Ms2qviU0sXK5yQhaYW_Jpg,1415
44
44
  kasa/iot/modules/usage.py,sha256=YeeUdVJ6Koj2eSQ0U9qETdqhBrUVd0j7cnY1XOhVSlc,3819
45
- kasa/iotprotocol.py,sha256=9QzkaaQcyEvoL5cZTxfQ2i-lywU1ciAUmE20mC-jc_k,4464
45
+ kasa/iotprotocol.py,sha256=uj5chjjbPYAVFn3gNSHYIG74qxqzsovsmkRYEHunczY,5566
46
46
  kasa/json.py,sha256=cPLAwsWD1yCp3_dHe4CjgrM29FaICHbqUL37QYoiipk,415
47
- kasa/klaptransport.py,sha256=zomU81pqT5e4-DMoxLvubJ3xYF0gpmb0FxA49xSTKr8,18359
47
+ kasa/klaptransport.py,sha256=pL8rugvsx5WSDsUo5-IFHAGjyEoAntg6Wz4OQ9Kql9o,18253
48
48
  kasa/module.py,sha256=aE9dVuylWKEx_Hb0Mp3Qx8pQCqf_3vf5uoKWrzpFviY,6590
49
49
  kasa/modulemapping.py,sha256=79mtaewNYvhFjn1Jo39xE57aid5gn08A-45bOS0vgMs,499
50
50
  kasa/modulemapping.pyi,sha256=dP-zCo8FiFOC68TtpBlxDcJASDwUur1gFyC9Ei9aaMU,3853
51
- kasa/protocol.py,sha256=suY021K8kfOzUNLLNDXBqJRcoSXlx2UwqUgOughNzzk,3325
51
+ kasa/protocol.py,sha256=MXBrohZBvEGDQg5xq1QQ5I0-rmP9Bfcn3KMNcYpl3l8,4656
52
52
  kasa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
53
  kasa/smart/__init__.py,sha256=gdmi-Doe7dnv7e8ab_892lr9IdOXeFa3XlU3u_CePCk,198
54
54
  kasa/smart/effects.py,sha256=E3oPHeWlc4lzThBbYV_UC2q-3EpdRiWf8eZiENMfb4k,11476
@@ -70,7 +70,7 @@ kasa/smart/modules/frostprotection.py,sha256=NsNhbvMnuCoUJWGbAWfP7_ODoOiIGISTHHE
70
70
  kasa/smart/modules/humiditysensor.py,sha256=T-jsWVEOSVl6oX_IWvFvl_tCyjdncQjeFi-sxzH07Q4,1755
71
71
  kasa/smart/modules/led.py,sha256=VaFhMX8MTv3JZ311glm9DhF-6Auy6-gazNvTf5pVjdI,1517
72
72
  kasa/smart/modules/light.py,sha256=3JQ3OUdknnb_hpM62O-2MUcgCR584VqkzI9amjaneIA,5668
73
- kasa/smart/modules/lighteffect.py,sha256=VUhL8jV-LyMaoqvkQvw0XmdpCZwoxSYkBDahyjUJ01A,6248
73
+ kasa/smart/modules/lighteffect.py,sha256=Rnz1AzIpHGT3z4PL3ROmz6SDZzfI6tBEPpC1mvV8nqI,6282
74
74
  kasa/smart/modules/lightpreset.py,sha256=-A35EjnFylrriQq93IF_toPYdUU39mKRmzzaVLF-g-w,5915
75
75
  kasa/smart/modules/lightstripeffect.py,sha256=iuygSAstKkS5C9pEppVG_vEkAAnNKtXe5Ua_Mc3B8pE,5616
76
76
  kasa/smart/modules/lighttransition.py,sha256=0cfm4U-sl2Oir2F1jW9HAWajDudPVsz9q2HOc7D0F50,8342
@@ -80,13 +80,13 @@ kasa/smart/modules/temperaturesensor.py,sha256=dgqqVJeE03RQ2PRXveLnxC4n-nLz0dQI7
80
80
  kasa/smart/modules/time.py,sha256=CITnlRTe0z48DL2KHu18UDeGLKCy629eghYPq3MOHo8,1891
81
81
  kasa/smart/modules/waterleaksensor.py,sha256=yoQtSjM1MO9sMpU2ldtWzHcTPPd7okZNWvjSXmkb4h0,1880
82
82
  kasa/smart/smartchilddevice.py,sha256=rsyIiOWHqwYanhkfkrhxKmXhe8s41mwpI5DrJHan8c4,2738
83
- kasa/smart/smartdevice.py,sha256=HdeQHJK5u6JKlVJD2IJR7TKiYR7fOh2L7mfMKUtb0Do,26176
83
+ kasa/smart/smartdevice.py,sha256=jyMBbbyCFIrvBVCUwh7JbX1eupmlz8qmBNTho54ZC7o,26224
84
84
  kasa/smart/smartmodule.py,sha256=dNfSVt2UHmq8jWYKb-1GAnYjC_w2N4k-SNor0_vkZkY,5176
85
- kasa/smartprotocol.py,sha256=1b2xJpp6SK5qE_gEfoVcQYP20b4R1FfeshPKMqHbAic,17850
85
+ kasa/smartprotocol.py,sha256=vofQ1KGB60C4dM477k0UBuwfsUeIj6l4S4K3jkNqrC0,18902
86
86
  kasa/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
87
87
  kasa/tests/conftest.py,sha256=SEMjGkposNARLaU2DZO__NBkZmNIn3A-CXJuYIrRk9Q,2791
88
88
  kasa/tests/device_fixtures.py,sha256=p29ye1Q-HjgZERiRXIPk8ik_YNaBD9MhIuNuJsqc-0I,13576
89
- kasa/tests/discovery_fixtures.py,sha256=kFZ-Es3lbT9824sT4lSy_Is4c4U2YjDgPOJyEoGRsFY,8624
89
+ kasa/tests/discovery_fixtures.py,sha256=55hpFQvBhl8Emnpj86uIXNABeF139-fzr8eZv6TYe28,8728
90
90
  kasa/tests/fakeprotocol_iot.py,sha256=tl12kouujaN09LEtxlMQzFPBjj44NaQsmY1ObocTgpw,14435
91
91
  kasa/tests/fakeprotocol_smart.py,sha256=moWwmyqzYhf1yjFtu1T1SpJEbCyrioStLyI5Y_UuYZ4,17426
92
92
  kasa/tests/fixtureinfo.py,sha256=zDxI6jCHfOFb8UVZpBiXdAsNXMqNTfQhfrPp4B_9vBc,5452
@@ -228,7 +228,7 @@ kasa/tests/test_device_factory.py,sha256=9M2ulXuvZsnm9Aqnt1EE_hLh_PBJfaJLUbtHbFC
228
228
  kasa/tests/test_device_type.py,sha256=QiAHVsPbs1lR8mXXvq1IJ4n1OAIs0pmMekjVSTxfp1o,872
229
229
  kasa/tests/test_deviceconfig.py,sha256=uhsZDe3lJhIoUdXEEBe0JYri1lNf8dbWHN7mJWHX4J0,2318
230
230
  kasa/tests/test_dimmer.py,sha256=q5cxLwy3072Aqe3GFqtqIVYvlwy4MZ2qDPoFXemyDNE,3859
231
- kasa/tests/test_discovery.py,sha256=p5D6DTKbnVVtLnEmKuW4-4Co5Ec5-dY01Iib5Bom0k0,19167
231
+ kasa/tests/test_discovery.py,sha256=TlaGAwGM3KiX1Ykqp3ECD03fD6GxWtJlVvcvr-pFTEQ,20162
232
232
  kasa/tests/test_emeter.py,sha256=WZpYeRV_ACb0YVw2qj35-gEUPyL_U5IEkJiKildk6nc,5756
233
233
  kasa/tests/test_feature.py,sha256=0O9ASgP6BLOU-ebsu47vrcUKslc7NhNXn80IvW-rAIQ,6993
234
234
  kasa/tests/test_httpclient.py,sha256=E2CCHlwoGAu3djoUixk_n9PmNnZ9ELS30AHkbBG7mTg,2726
@@ -236,15 +236,15 @@ kasa/tests/test_iotdevice.py,sha256=t4xC57qoiujK281vLPSBTuzSG4A8UfL6bbLR4D_IXKY,
236
236
  kasa/tests/test_klapprotocol.py,sha256=bjXU1uxLdlXJXf0e1nhGAjErDN9-qaWC5oY0k0HCDz0,16974
237
237
  kasa/tests/test_lightstrip.py,sha256=GvjrFyWP8A5UahrHDMCetmLzfZKWe1R8jWBdQf3tWI0,2193
238
238
  kasa/tests/test_plug.py,sha256=GOfU-mVSSPuakHoATbg5iJVVMbqGZl6ZCrWSpqshAkw,1859
239
- kasa/tests/test_protocol.py,sha256=eHkr9iF2SnlWnyxzb3ECS68r53GBK6Z1SW37G8QHSv8,19578
239
+ kasa/tests/test_protocol.py,sha256=wtkuoY-gdHYH86pDBNyEsOhwqbCM-7C3pS0F9c3aSOI,21473
240
240
  kasa/tests/test_readme_examples.py,sha256=gU19c-M-PkNU2UD-JR4WnXWY3jWVr1Ygy2kaJriDJH4,6934
241
241
  kasa/tests/test_smartdevice.py,sha256=dM15HXZW6HiFYy8YYuRJnlfKImcWskpk1T8XqVmh5r4,14601
242
- kasa/tests/test_smartprotocol.py,sha256=p7RJF3SnplHUoJiqfRl1LphykRBFk65zjtqfSr9xz7Q,14270
242
+ kasa/tests/test_smartprotocol.py,sha256=HcB44Xy9RVg0eL-HiZAvDwtNgzn2A6axPXZs2LoUmHU,15182
243
243
  kasa/tests/test_strip.py,sha256=v7-fDl0DTCIxC7Otd8GrAmm_WVkJDqrzBEJ7Yvx9yA0,5017
244
244
  kasa/tests/test_usage.py,sha256=ypM6O_KEpmI3Mw9FRPf045S-FefOKqpM-BF0px6ca6M,2331
245
- kasa/xortransport.py,sha256=nuQqClJIgfSt485WCxkw-vNwrORkmoCy-X-xfJiBwOY,8533
246
- python_kasa-0.7.0.4.dist-info/LICENSE,sha256=Klt9aEsei738epLgYqeikhpdBWwMvU1VAli14Bxlc5c,33218
247
- python_kasa-0.7.0.4.dist-info/METADATA,sha256=H_Rkl0gSaUG0NLYXufMV36F-9KUcHTdf5KYXz-A8_s4,11516
248
- python_kasa-0.7.0.4.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
249
- python_kasa-0.7.0.4.dist-info/entry_points.txt,sha256=RlTlZyXOxJ_r2Ap7lpuPAWyYUud9RfVBnOklBvUKPVA,37
250
- python_kasa-0.7.0.4.dist-info/RECORD,,
245
+ kasa/xortransport.py,sha256=6kcYPhCtMmCq7eNH91mMw1pAPqM0L9QWhudMy5MoNRM,8419
246
+ python_kasa-0.7.0.5.dist-info/LICENSE,sha256=Klt9aEsei738epLgYqeikhpdBWwMvU1VAli14Bxlc5c,33218
247
+ python_kasa-0.7.0.5.dist-info/METADATA,sha256=nOZl6Z9M6Sisb_A3lgIifIwKVCr265aEu3MdMD2g6D8,11516
248
+ python_kasa-0.7.0.5.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
249
+ python_kasa-0.7.0.5.dist-info/entry_points.txt,sha256=RlTlZyXOxJ_r2Ap7lpuPAWyYUud9RfVBnOklBvUKPVA,37
250
+ python_kasa-0.7.0.5.dist-info/RECORD,,