pyhubblenetwork 0.9.0__tar.gz → 0.10.1__tar.gz

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.
Files changed (32) hide show
  1. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/PKG-INFO +1 -1
  2. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/pyproject.toml +1 -1
  3. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/cli.py +240 -51
  4. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/crypto.py +9 -9
  5. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_aes_eax.py +144 -0
  6. pyhubblenetwork-0.10.1/tests/test_cli_ctr_autodetect.py +137 -0
  7. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/.gitignore +0 -0
  8. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/LICENSE +0 -0
  9. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/README.md +0 -0
  10. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/plugins/pyhubblenetwork/skills/hubble-ready-test/README.md +0 -0
  11. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/__init__.py +0 -0
  12. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/ble.py +0 -0
  13. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/cloud.py +0 -0
  14. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/device.py +0 -0
  15. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/errors.py +0 -0
  16. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/org.py +0 -0
  17. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/packets.py +0 -0
  18. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/ready.py +0 -0
  19. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/src/hubblenetwork/sat.py +0 -0
  20. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/__init__.py +0 -0
  21. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/conftest.py +0 -0
  22. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_ble_validate.py +0 -0
  23. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_cli_payload.py +0 -0
  24. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_cloud_integration.py +0 -0
  25. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_counter_eid.py +0 -0
  26. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_metrics.py +0 -0
  27. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_org_delete_device.py +0 -0
  28. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_register_device_cloud.py +0 -0
  29. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_register_device_validation.py +0 -0
  30. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_sat.py +0 -0
  31. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_sat_integration.py +0 -0
  32. {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.1}/tests/test_unencrypted.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyhubblenetwork
3
- Version: 0.9.0
3
+ Version: 0.10.1
4
4
  Summary: Hubble SDK host-side tools
5
5
  Author-email: Paul Buckley <paul@hubble.com>
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pyhubblenetwork"
7
- version = "0.9.0"
7
+ version = "0.10.1"
8
8
  requires-python = ">=3.9"
9
9
  authors = [
10
10
  { name="Paul Buckley", email="paul@hubble.com" },
@@ -34,6 +34,31 @@ _handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
34
34
  logger.addHandler(_handler)
35
35
 
36
36
 
37
+ def _parse_key(key_str: str) -> bytes:
38
+ """Parse an encryption key from hex or base64. Returns raw bytes.
39
+
40
+ Accepts 128-bit (16 bytes) or 256-bit (32 bytes) keys.
41
+ Strings of exactly 32 or 64 characters are tried as hex first, then base64.
42
+ """
43
+ s = key_str.strip()
44
+ if len(s) in (32, 64):
45
+ try:
46
+ return bytes.fromhex(s)
47
+ except ValueError:
48
+ pass
49
+ try:
50
+ key_bytes = base64.b64decode(s, validate=True)
51
+ except binascii.Error as e:
52
+ raise ValueError(
53
+ f"Invalid key format: {e}. Provide hex (32 or 64 hex chars) or base64."
54
+ )
55
+ if len(key_bytes) not in (16, 32):
56
+ raise ValueError(
57
+ f"Key must be 16 bytes (AES-128) or 32 bytes (AES-256), got {len(key_bytes)}."
58
+ )
59
+ return key_bytes
60
+
61
+
37
62
  def _validate_info(msg):
38
63
  click.secho("[INFO] ", fg="cyan", bold=True, nl=False)
39
64
  click.echo(msg + "... ", nl=False)
@@ -87,6 +112,103 @@ def _detect_eid_type(
87
112
  return (None, None, None, False)
88
113
 
89
114
 
115
+ def _announce_auto_detect(auto_ctr: bool, auto_eax: bool, *, suppress: bool) -> None:
116
+ if suppress or not (auto_ctr or auto_eax):
117
+ return
118
+ parts = []
119
+ if auto_ctr:
120
+ parts.append("AES-CTR counter_source")
121
+ if auto_eax:
122
+ parts.append("AES-EAX period_exponent (0..15)")
123
+ click.secho(
124
+ f"[WARN] No {' / '.join(parts)} provided. Auto-detecting "
125
+ f"decryption configuration from incoming packets...",
126
+ fg="yellow",
127
+ err=True,
128
+ )
129
+
130
+
131
+ def _decrypt_eax_with_detect(
132
+ key: bytes,
133
+ pkt: AesEaxPacket,
134
+ *,
135
+ auto_detect: bool,
136
+ fixed_exponent: int,
137
+ cache: dict,
138
+ announced: list[str],
139
+ suppress_info: bool,
140
+ ) -> Optional[DecryptedPacket]:
141
+ if not auto_detect:
142
+ return decrypt_eax(key, pkt, period_exponent=fixed_exponent)
143
+
144
+ cached = cache.get(pkt.eid)
145
+ if cached is not None:
146
+ result = decrypt_eax(key, pkt, period_exponent=cached)
147
+ if result:
148
+ return result
149
+
150
+ for candidate in range(16):
151
+ result = decrypt_eax(key, pkt, period_exponent=candidate)
152
+ if result is None:
153
+ continue
154
+ cache[pkt.eid] = candidate
155
+ if not announced and not suppress_info:
156
+ announced.append("eax")
157
+ click.secho(
158
+ f"[INFO] Detected: AES-128-EAX, counter_source=DEVICE_UPTIME, "
159
+ f"period_exponent={candidate} (period={1 << candidate}s)",
160
+ fg="green",
161
+ err=True,
162
+ )
163
+ return result
164
+ return None
165
+
166
+
167
+ def _decrypt_ctr_with_detect(
168
+ key: bytes,
169
+ pkt: EncryptedPacket,
170
+ *,
171
+ auto_detect: bool,
172
+ fixed_counter_mode: str,
173
+ days: int,
174
+ cache: dict,
175
+ announced: list[str],
176
+ suppress_info: bool,
177
+ ) -> Optional[DecryptedPacket]:
178
+ if not auto_detect:
179
+ return decrypt(key, pkt, days=days, counter_mode=fixed_counter_mode)
180
+
181
+ def _try(mode: str) -> Optional[DecryptedPacket]:
182
+ kwargs = {"counter_mode": mode}
183
+ if mode == UNIX_TIME:
184
+ kwargs["days"] = days
185
+ return decrypt(key, pkt, **kwargs)
186
+
187
+ if pkt.eid is not None:
188
+ cached = cache.get(pkt.eid)
189
+ if cached is not None:
190
+ result = _try(cached)
191
+ if result:
192
+ return result
193
+
194
+ for mode in (UNIX_TIME, DEVICE_UPTIME):
195
+ result = _try(mode)
196
+ if result is None:
197
+ continue
198
+ if pkt.eid is not None:
199
+ cache[pkt.eid] = mode
200
+ if not announced and not suppress_info:
201
+ announced.append("ctr")
202
+ variant = "AES-128-CTR" if len(key) == 16 else "AES-256-CTR"
203
+ click.secho(
204
+ f"[INFO] Detected: {variant}, counter_source={mode}",
205
+ fg="green",
206
+ err=True,
207
+ )
208
+ return result
209
+ return None
210
+
211
+
90
212
  def _format_payload(payload, fmt: str) -> str:
91
213
  """Format packet payload bytes for display."""
92
214
  if not isinstance(payload, bytes):
@@ -695,7 +817,7 @@ def ble() -> None:
695
817
  type=str,
696
818
  default=None,
697
819
  show_default=False,
698
- help="Key to decrypt packets (base64 encoded, required)",
820
+ help="Key to decrypt packets (hex or base64, 16 or 32 bytes)",
699
821
  )
700
822
  @click.option(
701
823
  "--days",
@@ -710,7 +832,15 @@ def ble() -> None:
710
832
  type=click.Choice(["UNIX_TIME", "DEVICE_UPTIME"], case_sensitive=False),
711
833
  default="UNIX_TIME",
712
834
  show_default=True,
713
- help="EID counter mode: UNIX_TIME (UTC day-based) or DEVICE_UPTIME (counter 0-127)",
835
+ help="EID counter mode for AES-CTR packets",
836
+ )
837
+ @click.option(
838
+ "--period-exponent",
839
+ "-e",
840
+ type=int,
841
+ default=0,
842
+ show_default=True,
843
+ help="EID rotation period exponent for AES-EAX packets (0-15). Period = 2^n seconds.",
714
844
  )
715
845
  @click.option(
716
846
  "--format",
@@ -742,6 +872,7 @@ def ble_detect(
742
872
  key: str = None,
743
873
  days: int = 2,
744
874
  counter_mode: str = "UNIX_TIME",
875
+ period_exponent: int = 0,
745
876
  output_format: str = "tabular",
746
877
  payload_format: str = "base64",
747
878
  debug: bool = False,
@@ -753,8 +884,8 @@ def ble_detect(
753
884
  The key parameter is required. Check the 'success' field in JSON output.
754
885
 
755
886
  Example:
756
- hubblenetwork ble detect --key "yourBase64Key=" --timeout 20
757
- hubblenetwork ble detect -k "key=" -o tabular
887
+ hubblenetwork ble detect --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 20
888
+ hubblenetwork ble detect -k "q9vH3u2J4aN8Rw1KpZsO+A==" -o tabular
758
889
  """
759
890
  use_json = output_format.lower() == "json"
760
891
 
@@ -774,15 +905,26 @@ def ble_detect(
774
905
  else:
775
906
  click.secho(f"[ERROR] {msg}", fg="red", err=True)
776
907
 
777
- # Try to decode the base64 key
778
908
  try:
779
- decoded_key = bytearray(base64.b64decode(key))
909
+ decoded_key = bytearray(_parse_key(key))
780
910
  logger.debug("Key decoded successfully")
781
- except (binascii.Error, Exception) as e:
782
- logger.error(f"Base64 decoding failed: {e}")
783
- _output_error("Base64 decoding failed for provided key")
911
+ except ValueError as e:
912
+ logger.error(f"Key decoding failed: {e}")
913
+ _output_error(f"Key decoding failed: {e}")
784
914
  return
785
915
 
916
+ def _explicit(name: str) -> bool:
917
+ return ctx.get_parameter_source(name) == click.core.ParameterSource.COMMANDLINE
918
+
919
+ auto_detect_ctr = not _explicit("counter_mode")
920
+ auto_detect_eax = not _explicit("period_exponent")
921
+
922
+ _announce_auto_detect(auto_detect_ctr, auto_detect_eax, suppress=use_json)
923
+
924
+ detected_ctr_modes: dict = {}
925
+ detected_eax_exponents: dict = {}
926
+ announced: list[str] = []
927
+
786
928
  # Set up timeout tracking
787
929
  start = time.monotonic()
788
930
  deadline = None if timeout is None else start + timeout
@@ -813,10 +955,29 @@ def ble_detect(
813
955
 
814
956
  logger.debug("Packet received, attempting decryption...")
815
957
 
816
- # Attempt to decrypt the packet
817
- decrypted_pkt = decrypt(
818
- decoded_key, pkt, days=days, counter_mode=counter_mode
819
- )
958
+ decrypted_pkt = None
959
+ if isinstance(pkt, AesEaxPacket):
960
+ decrypted_pkt = _decrypt_eax_with_detect(
961
+ decoded_key,
962
+ pkt,
963
+ auto_detect=auto_detect_eax,
964
+ fixed_exponent=period_exponent,
965
+ cache=detected_eax_exponents,
966
+ announced=announced,
967
+ suppress_info=use_json,
968
+ )
969
+ elif isinstance(pkt, EncryptedPacket):
970
+ decrypted_pkt = _decrypt_ctr_with_detect(
971
+ decoded_key,
972
+ pkt,
973
+ auto_detect=auto_detect_ctr,
974
+ fixed_counter_mode=counter_mode,
975
+ days=days,
976
+ cache=detected_ctr_modes,
977
+ announced=announced,
978
+ suppress_info=use_json,
979
+ )
980
+ # UnencryptedPacket and UnknownPacket fall through — keep scanning.
820
981
 
821
982
  if decrypted_pkt:
822
983
  # If we can decrypt it, output success
@@ -874,7 +1035,7 @@ def ble_detect(
874
1035
  type=str,
875
1036
  default=None,
876
1037
  show_default=False,
877
- help="Base64-encoded key to decrypt packets",
1038
+ help="Key to decrypt packets (hex or base64, 16 or 32 bytes)",
878
1039
  )
879
1040
  @click.option(
880
1041
  "--days",
@@ -886,17 +1047,18 @@ def ble_detect(
886
1047
  )
887
1048
  @click.option(
888
1049
  "--counter-mode",
889
- type=click.Choice(["UNIX_TIME", "DEVICE_UPTIME"], case_sensitive=False),
890
- default="UNIX_TIME",
1050
+ type=click.Choice([UNIX_TIME, DEVICE_UPTIME], case_sensitive=False),
1051
+ default=UNIX_TIME,
891
1052
  show_default=True,
892
1053
  help="EID counter mode for AES-CTR packets",
893
1054
  )
894
1055
  @click.option(
895
- "--scale-factor",
1056
+ "--period-exponent",
1057
+ "-e",
896
1058
  type=int,
897
1059
  default=0,
898
1060
  show_default=True,
899
- help="Scale factor for AES-EAX packets (0-15), matches rot_exp in device config",
1061
+ help="EID rotation period exponent for AES-EAX packets (0-15). Period = 2^n seconds. Matches rot_exp in device config.",
900
1062
  )
901
1063
  @click.option(
902
1064
  "--network-id",
@@ -939,7 +1101,7 @@ def ble_scan(
939
1101
  key: Optional[str] = None,
940
1102
  days: int = 2,
941
1103
  counter_mode: str = "UNIX_TIME",
942
- scale_factor: int = 0,
1104
+ period_exponent: int = 0,
943
1105
  output_format: str = "tabular",
944
1106
  payload_format: str = "base64",
945
1107
  show_failed_decryption: bool = False,
@@ -951,7 +1113,7 @@ def ble_scan(
951
1113
 
952
1114
  Example:
953
1115
  hubblenetwork ble scan --timeout 30
954
- hubblenetwork ble scan --key "base64key=" --timeout 60
1116
+ hubblenetwork ble scan --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 60
955
1117
  hubblenetwork ble scan -o json --timeout 10
956
1118
  hubblenetwork ble scan -n 5 # Stop after 5 packets
957
1119
  hubblenetwork ble scan --network-id 4378792717
@@ -990,13 +1152,30 @@ def ble_scan(
990
1152
  decoded_key: Optional[bytearray] = None
991
1153
  if key:
992
1154
  try:
993
- decoded_key = bytearray(base64.b64decode(key))
994
- except (binascii.Error, Exception) as e:
1155
+ decoded_key = bytearray(_parse_key(key))
1156
+ except ValueError as e:
995
1157
  if printer.suppress_info_messages:
996
1158
  click.echo(json.dumps({"error": f"Invalid base64 key: {e}"}))
997
1159
  return
998
1160
  raise click.ClickException(f"Invalid base64 key: {e}")
999
1161
 
1162
+ # Click's parameter source lets users disable auto-detect by passing the
1163
+ # default value verbatim — otherwise we couldn't tell "default" apart
1164
+ # from "user explicitly chose UNIX_TIME / exponent=0".
1165
+ def _explicit(name: str) -> bool:
1166
+ return ctx.get_parameter_source(name) == click.core.ParameterSource.COMMANDLINE
1167
+
1168
+ auto_detect_ctr = decoded_key is not None and not _explicit("counter_mode")
1169
+ auto_detect_eax = decoded_key is not None and not _explicit("period_exponent")
1170
+
1171
+ _announce_auto_detect(
1172
+ auto_detect_ctr, auto_detect_eax, suppress=printer.suppress_info_messages
1173
+ )
1174
+
1175
+ detected_ctr_modes: dict = {}
1176
+ detected_eax_exponents: dict = {}
1177
+ announced: list[str] = []
1178
+
1000
1179
  try:
1001
1180
  while deadline is None or time.monotonic() < deadline:
1002
1181
  # Check if we've hit the count limit
@@ -1019,7 +1198,15 @@ def ble_scan(
1019
1198
  # AES-EAX packets: decrypt if key provided, else show raw fields
1020
1199
  elif isinstance(pkt, AesEaxPacket):
1021
1200
  if decoded_key:
1022
- decrypted_pkt = decrypt_eax(decoded_key, pkt, scale_factor=scale_factor)
1201
+ decrypted_pkt = _decrypt_eax_with_detect(
1202
+ decoded_key,
1203
+ pkt,
1204
+ auto_detect=auto_detect_eax,
1205
+ fixed_exponent=period_exponent,
1206
+ cache=detected_eax_exponents,
1207
+ announced=announced,
1208
+ suppress_info=printer.suppress_info_messages,
1209
+ )
1023
1210
  if decrypted_pkt:
1024
1211
  printer.print_row(decrypted_pkt, decrypt_status="ok")
1025
1212
  elif show_failed_decryption:
@@ -1028,8 +1215,15 @@ def ble_scan(
1028
1215
  printer.print_row(pkt)
1029
1216
  elif isinstance(pkt, EncryptedPacket):
1030
1217
  if decoded_key:
1031
- decrypted_pkt = decrypt(
1032
- decoded_key, pkt, days=days, counter_mode=counter_mode
1218
+ decrypted_pkt = _decrypt_ctr_with_detect(
1219
+ decoded_key,
1220
+ pkt,
1221
+ auto_detect=auto_detect_ctr,
1222
+ fixed_counter_mode=counter_mode,
1223
+ days=days,
1224
+ cache=detected_ctr_modes,
1225
+ announced=announced,
1226
+ suppress_info=printer.suppress_info_messages,
1033
1227
  )
1034
1228
  if decrypted_pkt:
1035
1229
  printer.print_row(decrypted_pkt, decrypt_status="ok")
@@ -1069,7 +1263,7 @@ def ble_scan(
1069
1263
  "-k",
1070
1264
  required=True,
1071
1265
  type=str,
1072
- help="Key for checking time counter (base64 encoded)",
1266
+ help="Key for checking time counter (hex or base64, 16 or 32 bytes)",
1073
1267
  )
1074
1268
  @click.option(
1075
1269
  "--json-output",
@@ -1091,20 +1285,15 @@ def ble_check_time(
1091
1285
  A device is considered out of spec if it is more than 2 days off.
1092
1286
 
1093
1287
  Example:
1094
- hubblenetwork ble check-time --key "yourBase64Key=" --timeout 30
1288
+ hubblenetwork ble check-time --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 30
1095
1289
  """
1096
- # Decode the key
1097
1290
  try:
1098
- decoded_key = bytearray(base64.b64decode(key))
1099
- except (binascii.Error, Exception) as e:
1291
+ decoded_key = bytearray(_parse_key(key))
1292
+ except ValueError as e:
1100
1293
  if json_output:
1101
- click.echo(json.dumps({"error": f"Base64 decoding failed: {e}"}))
1294
+ click.echo(json.dumps({"error": str(e)}))
1102
1295
  else:
1103
- click.secho(
1104
- f"[ERROR] Base64 decoding failed for provided key: {e}",
1105
- fg="red",
1106
- err=True,
1107
- )
1296
+ click.secho(f"[ERROR] {e}", fg="red", err=True)
1108
1297
  return
1109
1298
 
1110
1299
  if not json_output:
@@ -1232,14 +1421,15 @@ def ble_validate(key: str, device_id: str, org_id: str, token: str, timeout: int
1232
1421
  # Step 1: Validate inputs
1233
1422
  _validate_info("Validating format of inputs")
1234
1423
  try:
1235
- decoded_key = base64.b64decode(key, validate=True)
1236
- except Exception:
1424
+ decoded_key = _parse_key(key)
1425
+ except ValueError as e:
1237
1426
  _validate_error(
1238
- 'Incorrectly formatted device key passed in. Must be a base 64'
1239
- '\nencoded string such as (fake keys):'
1240
- '\n 16byte key: "q9vH3u2J4aN8Rw1KpZsO+A=="'
1241
- '\n 32byte key: "N4e7xq9X1pQ0sVbY2mT3uA6fH9rK2dW5cG8jL1oQ0vU="'
1242
- '\nNote the "=" characters at the end which must be included.'
1427
+ f'Incorrectly formatted device key: {e}'
1428
+ '\nAccepted formats (fake keys):'
1429
+ '\n Hex 16-byte: "a562a2f7e4c62bed52ab09633878f62b"'
1430
+ '\n Hex 32-byte: "a562a2f7e4c62bed52ab09633878f62ba562a2f7e4c62bed52ab09633878f62b"'
1431
+ '\n Base64 16-byte: "q9vH3u2J4aN8Rw1KpZsO+A=="'
1432
+ '\n Base64 32-byte: "N4e7xq9X1pQ0sVbY2mT3uA6fH9rK2dW5cG8jL1oQ0vU="'
1243
1433
  )
1244
1434
  try:
1245
1435
  uuid.UUID(device_id)
@@ -2070,7 +2260,7 @@ def ready_read_time(
2070
2260
  "--key",
2071
2261
  "-k",
2072
2262
  required=True,
2073
- help="Base64-encoded encryption key (16 bytes for AES-128-CTR, 32 bytes for AES-256-CTR)",
2263
+ help="Encryption key (hex or base64; 16 bytes = AES-128-CTR, 32 bytes = AES-256-CTR)",
2074
2264
  )
2075
2265
  @click.option(
2076
2266
  "--timeout",
@@ -2100,25 +2290,24 @@ def ready_write_key(
2100
2290
  32 bytes for AES-256-CTR).
2101
2291
 
2102
2292
  Example:
2103
- hubblenetwork ready write-key --address AA:BB:CC:DD:EE:FF --key <base64-key>
2104
- hubblenetwork ready write-key -a AA:BB:CC:DD:EE:FF -k <base64-key> --format json
2293
+ hubblenetwork ready write-key --address AA:BB:CC:DD:EE:FF --key a562a2f7e4c62bed52ab09633878f62b
2294
+ hubblenetwork ready write-key -a AA:BB:CC:DD:EE:FF -k "q9vH3u2J4aN8Rw1KpZsO+A==" --format json
2105
2295
  """
2106
2296
  use_json = output_format.lower() == "json"
2107
2297
 
2108
- # Decode the base64 key
2109
2298
  try:
2110
- key_bytes = base64.b64decode(key)
2111
- except Exception as e:
2299
+ key_bytes = _parse_key(key)
2300
+ except ValueError as e:
2112
2301
  if use_json:
2113
2302
  json_output = _format_ready_json_error(
2114
2303
  command="ready write-key",
2115
2304
  device_address=address,
2116
- error=Exception(f"Invalid base64 key: {e}"),
2305
+ error=Exception(str(e)),
2117
2306
  duration_ms=0,
2118
2307
  )
2119
2308
  click.echo(json.dumps(json_output, indent=2))
2120
2309
  else:
2121
- click.secho(f"[ERROR] Invalid base64 key: {e}", fg="red", err=True)
2310
+ click.secho(f"[ERROR] {e}", fg="red", err=True)
2122
2311
  sys.exit(1)
2123
2312
 
2124
2313
  if not use_json:
@@ -77,11 +77,11 @@ def _derive_eid_key(key: bytes, counter: int) -> bytes:
77
77
  return AES.new(key, AES.MODE_ECB).encrypt(msg1)
78
78
 
79
79
 
80
- def _generate_eid(key: bytes, counter: int, scale_factor: int = 0) -> int:
80
+ def _generate_eid(key: bytes, counter: int, period_exponent: int = 0) -> int:
81
81
  """Generate an 8-byte EID for a given counter value using AES-ECB."""
82
82
  key_0 = _derive_eid_key(key, counter)
83
- masked = counter & ~((1 << scale_factor) - 1)
84
- msg2 = b"\x00" * 11 + scale_factor.to_bytes(1, "big") + masked.to_bytes(4, "big")
83
+ masked = counter & ~((1 << period_exponent) - 1)
84
+ msg2 = b"\x00" * 11 + period_exponent.to_bytes(1, "big") + masked.to_bytes(4, "big")
85
85
  eid_block = AES.new(key_0, AES.MODE_ECB).encrypt(msg2)
86
86
  return int.from_bytes(eid_block[0:8], "big")
87
87
 
@@ -89,7 +89,7 @@ def _generate_eid(key: bytes, counter: int, scale_factor: int = 0) -> int:
89
89
  def decrypt_eax(
90
90
  key: bytes,
91
91
  pkt: AesEaxPacket,
92
- scale_factor: int = 0,
92
+ period_exponent: int = 0,
93
93
  pool_size: int = 128,
94
94
  ) -> Optional[DecryptedPacket]:
95
95
  """Decrypt an AES-EAX packet by trying candidate counters.
@@ -98,19 +98,19 @@ def decrypt_eax(
98
98
  the packet's EID. On match, constructs the nonce and decrypts.
99
99
 
100
100
  Args:
101
- scale_factor: EID rotation scale factor (0-15). Counter values
102
- are multiples of 2**scale_factor. Corresponds to rot_exp
103
- in device config or log2(period_in_seconds) in the API.
101
+ period_exponent: EID rotation period exponent (0-15). Period = 2^n seconds.
102
+ Counter values are multiples of 2**period_exponent. Corresponds to
103
+ rot_exp in device config or log2(period_in_seconds) in the API.
104
104
  pool_size: Number of counters to try (default 128).
105
105
  """
106
- step = 1 << scale_factor
106
+ step = 1 << period_exponent
107
107
  # key_0 is constant when high counter bytes are 00 00 (counter < 65536)
108
108
  key_0 = _derive_eid_key(key, 0)
109
109
  ecb = AES.new(key_0, AES.MODE_ECB)
110
110
 
111
111
  for i in range(pool_size):
112
112
  counter = i * step
113
- msg2 = b"\x00" * 11 + scale_factor.to_bytes(1, "big") + counter.to_bytes(4, "big")
113
+ msg2 = b"\x00" * 11 + period_exponent.to_bytes(1, "big") + counter.to_bytes(4, "big")
114
114
  eid_block = ecb.encrypt(msg2)
115
115
  candidate_eid = int.from_bytes(eid_block[0:8], "big")
116
116
 
@@ -454,6 +454,150 @@ class TestCliAesEaxScan:
454
454
  assert parsed[0]["protocol_version"] == 5
455
455
 
456
456
 
457
+ # ---------------------------------------------------------------------------
458
+ # CLI auto-detect tests for AES-EAX packets
459
+ # ---------------------------------------------------------------------------
460
+
461
+
462
+ def _build_eax_packet_at_exponent(key: bytes, period_exponent: int, plaintext: bytes) -> AesEaxPacket:
463
+ """Build a real AES-EAX packet whose EID/tag matches the given exponent."""
464
+ from hubblenetwork.crypto import _generate_eid as gen_eid
465
+ # Pick a counter that's a multiple of the step (so it's enumerable
466
+ # by decrypt_eax with this exponent).
467
+ step = 1 << period_exponent
468
+ counter = 3 * step # 3rd slot
469
+ eid = gen_eid(key, counter, period_exponent=period_exponent)
470
+ nonce_salt = b"\x9A\xBC"
471
+ nonce = counter.to_bytes(4, "big") + nonce_salt
472
+ cipher = _AES.new(key, _AES.MODE_EAX, mac_len=4, nonce=nonce)
473
+ ciphertext, tag = cipher.encrypt_and_digest(plaintext)
474
+ return AesEaxPacket(
475
+ timestamp=1700000000,
476
+ location=_FAKE_LOCATION,
477
+ protocol_version=2,
478
+ nonce_salt=nonce_salt,
479
+ eid=eid,
480
+ payload=ciphertext,
481
+ auth_tag=tag,
482
+ rssi=-70,
483
+ )
484
+
485
+
486
+ _EAX_KEY_HEX = _EAX_KEY.hex()
487
+
488
+
489
+ class TestCliAesEaxAutoDetect:
490
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
491
+ def test_auto_detect_finds_correct_exponent(self, mock_scan):
492
+ """Without -e, auto-detect resolves period_exponent and decrypts."""
493
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=12, plaintext=b"hi-eax")
494
+ mock_scan.side_effect = [pkt, None]
495
+
496
+ runner = CliRunner()
497
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX])
498
+ assert result.exit_code == 0
499
+ assert "[WARN]" in result.stderr
500
+ assert "Auto-detecting" in result.stderr
501
+ assert "period_exponent=12" in result.stderr
502
+ assert "period=4096s" in result.stderr
503
+ # decrypted payload appears in the table
504
+ assert "hi-eax" in result.stdout or "aGktZWF4" in result.stdout # raw or base64
505
+
506
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
507
+ def test_auto_detect_uses_cache_for_same_eid(self, mock_scan):
508
+ """Second packet with same EID hits cache (no extra detection banner)."""
509
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=5, plaintext=b"a")
510
+ mock_scan.side_effect = [pkt, pkt, None]
511
+
512
+ from hubblenetwork.crypto import decrypt_eax as real_decrypt_eax
513
+ from unittest.mock import MagicMock
514
+ wrapped = MagicMock(side_effect=real_decrypt_eax)
515
+ with patch("hubblenetwork.cli.decrypt_eax", wrapped):
516
+ runner = CliRunner()
517
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX])
518
+
519
+ assert result.exit_code == 0
520
+ # First packet: scan candidates 0..5 (6 calls). Second packet: 1 cache hit.
521
+ assert wrapped.call_count == 7
522
+ # Detection banner emitted exactly once.
523
+ assert result.stderr.count("[INFO] Detected:") == 1
524
+
525
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
526
+ def test_no_warn_when_both_flags_provided(self, mock_scan):
527
+ """With explicit -e and --counter-mode, no auto-detect warning or banner."""
528
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=7, plaintext=b"x")
529
+ mock_scan.side_effect = [pkt, None]
530
+
531
+ runner = CliRunner()
532
+ result = runner.invoke(
533
+ cli,
534
+ [
535
+ "ble", "scan", "--timeout", "1",
536
+ "--key", _EAX_KEY_HEX,
537
+ "-e", "7",
538
+ "--counter-mode", "UNIX_TIME",
539
+ ],
540
+ )
541
+ assert result.exit_code == 0
542
+ assert "[WARN]" not in result.stderr
543
+ assert "[INFO] Detected:" not in result.stderr
544
+
545
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
546
+ def test_warn_only_mentions_active_axes(self, mock_scan):
547
+ """Passing -e but not --counter-mode → warning mentions only CTR axis."""
548
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=7, plaintext=b"x")
549
+ mock_scan.side_effect = [pkt, None]
550
+
551
+ runner = CliRunner()
552
+ result = runner.invoke(
553
+ cli,
554
+ ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX, "-e", "7"],
555
+ )
556
+ assert result.exit_code == 0
557
+ assert "AES-CTR counter_source" in result.stderr
558
+ assert "AES-EAX" not in result.stderr # EAX axis was opted out
559
+ # No EAX detection banner since EAX is not auto-detecting.
560
+ assert "[INFO] Detected:" not in result.stderr
561
+
562
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
563
+ def test_silent_in_json_mode(self, mock_scan):
564
+ """JSON output stays parse-clean even with auto-detect."""
565
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=4, plaintext=b"j")
566
+ mock_scan.side_effect = [pkt, None]
567
+
568
+ runner = CliRunner()
569
+ result = runner.invoke(
570
+ cli,
571
+ ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX, "-o", "json"],
572
+ )
573
+ assert result.exit_code == 0
574
+ parsed = json.loads(result.stdout)
575
+ assert len(parsed) == 1
576
+ # Warning + info banner suppressed entirely (JSON mode suppresses info).
577
+ assert "[WARN]" not in result.stderr
578
+ assert "[INFO] Detected:" not in result.stderr
579
+
580
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
581
+ def test_detection_failure_with_show_failed(self, mock_scan):
582
+ """No exponent matches → no banner, packet shown as fail when flag set."""
583
+ # Build packet with one key, scan with another → all 16 candidates fail.
584
+ wrong_key = bytes(range(16, 32))
585
+ pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=3, plaintext=b"w")
586
+ mock_scan.side_effect = [pkt, None]
587
+
588
+ runner = CliRunner()
589
+ result = runner.invoke(
590
+ cli,
591
+ ["ble", "scan", "--timeout", "1", "--key", wrong_key.hex(),
592
+ "-o", "json", "--show-failed-decryption"],
593
+ )
594
+ assert result.exit_code == 0
595
+ parsed = json.loads(result.stdout)
596
+ assert len(parsed) == 1
597
+ assert parsed[0]["decrypt_status"] == "fail"
598
+ assert "[INFO] Detected:" not in result.stderr
599
+
600
+
457
601
  # ---------------------------------------------------------------------------
458
602
  # Public API export tests
459
603
  # ---------------------------------------------------------------------------
@@ -0,0 +1,137 @@
1
+ """CLI auto-detect tests for AES-CTR (counter_source) in `ble scan`."""
2
+ from __future__ import annotations
3
+
4
+ from unittest.mock import patch
5
+
6
+ from click.testing import CliRunner
7
+
8
+ from hubblenetwork.cli import cli
9
+ from hubblenetwork.packets import DecryptedPacket, EncryptedPacket, Location
10
+
11
+ from tests.test_counter_eid import _encrypt_payload
12
+
13
+
14
+ _FAKE_LOC = Location(lat=0.0, lon=0.0, fake=True)
15
+
16
+
17
+ def _make_ctr_packet_with_eid(key: bytes, counter: int, seq_no: int, plaintext: bytes, eid: int) -> EncryptedPacket:
18
+ payload = _encrypt_payload(key, counter, seq_no, plaintext)
19
+ return EncryptedPacket(
20
+ timestamp=1700000000,
21
+ location=_FAKE_LOC,
22
+ payload=payload,
23
+ rssi=-70,
24
+ protocol_version=0,
25
+ eid=eid,
26
+ auth_tag=payload[6:10],
27
+ )
28
+
29
+
30
+ def _decrypted(payload: bytes = b"d", counter: int = 1, seq_no: int = 1) -> DecryptedPacket:
31
+ return DecryptedPacket(
32
+ timestamp=1700000000,
33
+ device_id="",
34
+ device_name="",
35
+ location=_FAKE_LOC,
36
+ tags={},
37
+ payload=payload,
38
+ rssi=-70,
39
+ counter=counter,
40
+ sequence=seq_no,
41
+ )
42
+
43
+
44
+ _KEY_256_HEX = bytes(range(32)).hex()
45
+ _KEY_128_HEX = bytes(range(16)).hex()
46
+
47
+
48
+ class TestCliCtrAutoDetect:
49
+ @patch("hubblenetwork.cli.decrypt")
50
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
51
+ def test_finds_unix_time(self, mock_scan, mock_decrypt):
52
+ """UNIX_TIME succeeds on first try → banner names UNIX_TIME."""
53
+ pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
54
+ mock_scan.side_effect = [pkt, None]
55
+ mock_decrypt.side_effect = lambda key, p, **kw: (
56
+ _decrypted() if kw.get("counter_mode") == "UNIX_TIME" else None
57
+ )
58
+
59
+ runner = CliRunner()
60
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
61
+ assert result.exit_code == 0
62
+ assert "[INFO] Detected: AES-256-CTR, counter_source=UNIX_TIME" in result.stderr
63
+
64
+ @patch("hubblenetwork.cli.decrypt")
65
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
66
+ def test_finds_device_uptime(self, mock_scan, mock_decrypt):
67
+ """UNIX_TIME fails, DEVICE_UPTIME succeeds → banner names DEVICE_UPTIME."""
68
+ pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
69
+ mock_scan.side_effect = [pkt, None]
70
+ mock_decrypt.side_effect = lambda key, p, **kw: (
71
+ _decrypted() if kw.get("counter_mode") == "DEVICE_UPTIME" else None
72
+ )
73
+
74
+ runner = CliRunner()
75
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
76
+ assert result.exit_code == 0
77
+ assert "[INFO] Detected: AES-256-CTR, counter_source=DEVICE_UPTIME" in result.stderr
78
+
79
+ @patch("hubblenetwork.cli.decrypt")
80
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
81
+ def test_caches_per_eid(self, mock_scan, mock_decrypt):
82
+ """Two packets with same EID: detect on first, cache hit on second."""
83
+ pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xCAFE)
84
+ mock_scan.side_effect = [pkt, pkt, None]
85
+
86
+ # DEVICE_UPTIME succeeds; UNIX_TIME fails (so we exercise both modes
87
+ # on first packet and only DEVICE_UPTIME on the cached second packet).
88
+ mock_decrypt.side_effect = lambda key, p, **kw: (
89
+ _decrypted() if kw.get("counter_mode") == "DEVICE_UPTIME" else None
90
+ )
91
+
92
+ runner = CliRunner()
93
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
94
+ assert result.exit_code == 0
95
+ # First packet: 2 calls (UNIX_TIME fail, DEVICE_UPTIME success).
96
+ # Second packet: 1 call via cache (DEVICE_UPTIME).
97
+ modes_called = [c.kwargs.get("counter_mode") for c in mock_decrypt.call_args_list]
98
+ assert modes_called == ["UNIX_TIME", "DEVICE_UPTIME", "DEVICE_UPTIME"]
99
+ # Detection banner emitted exactly once.
100
+ assert result.stderr.count("[INFO] Detected:") == 1
101
+
102
+ @patch("hubblenetwork.cli.decrypt")
103
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
104
+ def test_no_warn_when_counter_mode_provided(self, mock_scan, mock_decrypt):
105
+ """Explicit --counter-mode + -e disables both auto-detect axes."""
106
+ pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
107
+ mock_scan.side_effect = [pkt, None]
108
+ mock_decrypt.return_value = _decrypted()
109
+
110
+ runner = CliRunner()
111
+ result = runner.invoke(
112
+ cli,
113
+ [
114
+ "ble", "scan", "--timeout", "1",
115
+ "--key", _KEY_256_HEX,
116
+ "--counter-mode", "UNIX_TIME",
117
+ "-e", "0",
118
+ ],
119
+ )
120
+ assert result.exit_code == 0
121
+ assert "[WARN]" not in result.stderr
122
+ assert "[INFO] Detected:" not in result.stderr
123
+ # decrypt() was called without the auto-detect probe (just once).
124
+ assert mock_decrypt.call_count == 1
125
+
126
+ @patch("hubblenetwork.cli.decrypt")
127
+ @patch("hubblenetwork.cli.ble_mod.scan_single")
128
+ def test_reports_correct_key_size(self, mock_scan, mock_decrypt):
129
+ """Banner labels AES-128-CTR for a 16-byte key."""
130
+ pkt = _make_ctr_packet_with_eid(bytes(range(16)), 0, 1, b"x", eid=0xAB)
131
+ mock_scan.side_effect = [pkt, None]
132
+ mock_decrypt.side_effect = lambda key, p, **kw: _decrypted()
133
+
134
+ runner = CliRunner()
135
+ result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_128_HEX])
136
+ assert result.exit_code == 0
137
+ assert "[INFO] Detected: AES-128-CTR, counter_source=UNIX_TIME" in result.stderr