pyhubblenetwork 0.8.0__tar.gz → 0.9.0__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.
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/PKG-INFO +1 -1
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/pyproject.toml +1 -1
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/ble.py +10 -1
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/cli.py +185 -80
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/cloud.py +7 -1
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/crypto.py +7 -1
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/org.py +26 -10
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/packets.py +11 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_aes_eax.py +58 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_cloud_integration.py +28 -4
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_org_delete_device.py +98 -1
- pyhubblenetwork-0.9.0/tests/test_register_device_cloud.py +91 -0
- pyhubblenetwork-0.9.0/tests/test_register_device_validation.py +87 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/.gitignore +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/LICENSE +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/README.md +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/plugins/pyhubblenetwork/skills/hubble-ready-test/README.md +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/__init__.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/device.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/errors.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/ready.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/src/hubblenetwork/sat.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/__init__.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/conftest.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_ble_validate.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_cli_payload.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_counter_eid.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_metrics.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_sat.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_sat_integration.py +0 -0
- {pyhubblenetwork-0.8.0 → pyhubblenetwork-0.9.0}/tests/test_unencrypted.py +0 -0
|
@@ -75,8 +75,17 @@ def _make_packet(raw: bytes, rssi: int) -> HubblePacket:
|
|
|
75
75
|
version = raw[0] >> 2
|
|
76
76
|
|
|
77
77
|
if version == 0:
|
|
78
|
+
# AES-CTR advertisement layout: seq_no (2) | EID (4) | auth_tag (4) | ciphertext.
|
|
79
|
+
eid = int.from_bytes(raw[2:6], "big") if len(raw) >= 6 else None
|
|
80
|
+
auth_tag = bytes(raw[6:10]) if len(raw) >= 10 else None
|
|
78
81
|
return EncryptedPacket(
|
|
79
|
-
timestamp=ts,
|
|
82
|
+
timestamp=ts,
|
|
83
|
+
location=_FAKE_LOCATION,
|
|
84
|
+
payload=raw,
|
|
85
|
+
rssi=rssi,
|
|
86
|
+
protocol_version=version,
|
|
87
|
+
eid=eid,
|
|
88
|
+
auth_tag=auth_tag,
|
|
80
89
|
)
|
|
81
90
|
elif version == 1:
|
|
82
91
|
parsed = parse_unencrypted(raw)
|
|
@@ -18,7 +18,6 @@ from tabulate import tabulate
|
|
|
18
18
|
from hubblenetwork import Organization
|
|
19
19
|
from hubblenetwork import Device, DecryptedPacket, EncryptedPacket, decrypt_eax
|
|
20
20
|
from hubblenetwork.packets import SatellitePacket, UnencryptedPacket, AesEaxPacket, UnknownPacket
|
|
21
|
-
from hubblenetwork.org import _VALID_COUNTER_SOURCES
|
|
22
21
|
from hubblenetwork import ble as ble_mod
|
|
23
22
|
from hubblenetwork import ready as ready_mod
|
|
24
23
|
from hubblenetwork import sat as sat_mod
|
|
@@ -123,7 +122,35 @@ def _get_org_and_token(org_id, token) -> tuple[str, str]:
|
|
|
123
122
|
return org_id, token
|
|
124
123
|
|
|
125
124
|
|
|
126
|
-
def
|
|
125
|
+
def _add_raw_adv_fields(data: dict, pkt) -> None:
|
|
126
|
+
"""Emit protocol_version/eid/auth_tag to `data` when present on `pkt`."""
|
|
127
|
+
version = getattr(pkt, "protocol_version", None)
|
|
128
|
+
if version is not None:
|
|
129
|
+
data["protocol_version"] = version
|
|
130
|
+
eid = getattr(pkt, "eid", None)
|
|
131
|
+
if eid is not None:
|
|
132
|
+
data["eid"] = f"{eid:x}"
|
|
133
|
+
auth_tag = getattr(pkt, "auth_tag", None)
|
|
134
|
+
if auth_tag is not None:
|
|
135
|
+
data["auth_tag"] = auth_tag.hex()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _ctr_display_payload(pkt) -> bytes:
|
|
139
|
+
"""Return payload bytes with the AES-CTR header stripped, if applicable.
|
|
140
|
+
|
|
141
|
+
The seq_no/EID/auth_tag header is already rendered in dedicated columns,
|
|
142
|
+
so only the trailing ciphertext belongs in the PAYLOAD field.
|
|
143
|
+
"""
|
|
144
|
+
if isinstance(pkt, EncryptedPacket) and len(pkt.payload) >= 10:
|
|
145
|
+
return pkt.payload[10:]
|
|
146
|
+
return pkt.payload
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _packet_to_dict(
|
|
150
|
+
pkt,
|
|
151
|
+
payload_format: str = "base64",
|
|
152
|
+
decrypt_status: Optional[str] = None,
|
|
153
|
+
) -> dict:
|
|
127
154
|
"""Convert a packet to a dictionary for JSON serialization."""
|
|
128
155
|
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%c")
|
|
129
156
|
data = {
|
|
@@ -132,20 +159,17 @@ def _packet_to_dict(pkt, payload_format: str = "base64") -> dict:
|
|
|
132
159
|
"rssi": pkt.rssi,
|
|
133
160
|
}
|
|
134
161
|
|
|
162
|
+
_add_raw_adv_fields(data, pkt)
|
|
163
|
+
|
|
135
164
|
if isinstance(pkt, UnencryptedPacket):
|
|
136
|
-
data["protocol_version"] = pkt.protocol_version
|
|
137
165
|
data["network_id"] = pkt.network_id
|
|
138
166
|
elif isinstance(pkt, AesEaxPacket):
|
|
139
|
-
data["protocol_version"] = pkt.protocol_version
|
|
140
|
-
data["eid"] = hex(pkt.eid)
|
|
141
167
|
data["nonce_salt"] = pkt.nonce_salt.hex()
|
|
142
|
-
elif isinstance(pkt, UnknownPacket):
|
|
143
|
-
data["protocol_version"] = pkt.protocol_version
|
|
144
168
|
elif isinstance(pkt, DecryptedPacket):
|
|
145
169
|
data["counter"] = pkt.counter
|
|
146
170
|
data["sequence"] = pkt.sequence
|
|
147
171
|
|
|
148
|
-
data["payload"] = _format_payload(pkt
|
|
172
|
+
data["payload"] = _format_payload(_ctr_display_payload(pkt), payload_format)
|
|
149
173
|
|
|
150
174
|
if not pkt.location.fake:
|
|
151
175
|
data["location"] = {
|
|
@@ -153,6 +177,9 @@ def _packet_to_dict(pkt, payload_format: str = "base64") -> dict:
|
|
|
153
177
|
"lon": pkt.location.lon,
|
|
154
178
|
}
|
|
155
179
|
|
|
180
|
+
if decrypt_status is not None:
|
|
181
|
+
data["decrypt_status"] = decrypt_status
|
|
182
|
+
|
|
156
183
|
return data
|
|
157
184
|
|
|
158
185
|
|
|
@@ -242,10 +269,11 @@ def _format_ready_json_error(
|
|
|
242
269
|
class _StreamingPrinterBase:
|
|
243
270
|
"""Base class for streaming packet printers."""
|
|
244
271
|
|
|
245
|
-
def __init__(self):
|
|
272
|
+
def __init__(self, show_decrypt_status: bool = False):
|
|
246
273
|
self._packet_count = 0
|
|
274
|
+
self._show_decrypt_status = show_decrypt_status
|
|
247
275
|
|
|
248
|
-
def print_row(self, pkt) -> None:
|
|
276
|
+
def print_row(self, pkt, decrypt_status: Optional[str] = None) -> None:
|
|
249
277
|
"""Print a single packet. Override in subclasses."""
|
|
250
278
|
raise NotImplementedError
|
|
251
279
|
|
|
@@ -269,54 +297,50 @@ class _StreamingTablePrinter(_StreamingPrinterBase):
|
|
|
269
297
|
# Fixed column widths for consistent alignment
|
|
270
298
|
_COL_WIDTHS = {
|
|
271
299
|
"TIMESTAMP": 12,
|
|
272
|
-
"TIME":
|
|
300
|
+
"TIME": 10,
|
|
273
301
|
"RSSI": 6,
|
|
274
302
|
"COUNTER": 8,
|
|
275
|
-
"SEQ": 6,
|
|
276
303
|
"NET_ID": 12,
|
|
277
304
|
"VERSION": 8,
|
|
278
305
|
"EID": 20,
|
|
279
|
-
"
|
|
306
|
+
"TAG": 10,
|
|
307
|
+
"SALT/SEQ": 10,
|
|
280
308
|
"COORDINATES": 22,
|
|
281
309
|
"PAYLOAD": 20,
|
|
310
|
+
"DECRYPT": 8,
|
|
282
311
|
}
|
|
283
312
|
|
|
284
|
-
def __init__(self, payload_format: str = "base64"):
|
|
285
|
-
super().__init__()
|
|
313
|
+
def __init__(self, payload_format: str = "base64", show_decrypt_status: bool = False):
|
|
314
|
+
super().__init__(show_decrypt_status=show_decrypt_status)
|
|
286
315
|
self._header_printed = False
|
|
287
316
|
self._headers: List[str] = []
|
|
288
|
-
self.
|
|
317
|
+
self._show_net_id = False
|
|
318
|
+
self._show_coordinates = False
|
|
289
319
|
self._payload_format = payload_format
|
|
290
320
|
|
|
291
|
-
def _determine_columns(self, pkt) ->
|
|
292
|
-
"""Determine column headers
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
if
|
|
303
|
-
headers.
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
321
|
+
def _determine_columns(self, pkt) -> List[str]:
|
|
322
|
+
"""Determine column headers based on the first packet seen.
|
|
323
|
+
|
|
324
|
+
AES-EAX and AES-CTR packets share a single unified layout — VERSION,
|
|
325
|
+
EID, TAG, COUNTER, and SALT/SEQ are always present, with "-" shown
|
|
326
|
+
where a field doesn't apply.
|
|
327
|
+
"""
|
|
328
|
+
self._show_net_id = isinstance(pkt, UnencryptedPacket)
|
|
329
|
+
self._show_coordinates = not pkt.location.fake
|
|
330
|
+
|
|
331
|
+
headers: List[str] = []
|
|
332
|
+
if self._show_decrypt_status:
|
|
333
|
+
headers.append("DECRYPT")
|
|
334
|
+
headers.extend(
|
|
335
|
+
["TIMESTAMP", "TIME", "RSSI", "VERSION", "EID", "TAG", "COUNTER", "SALT/SEQ"]
|
|
336
|
+
)
|
|
337
|
+
if self._show_net_id:
|
|
338
|
+
headers.append("NET_ID")
|
|
339
|
+
if self._show_coordinates:
|
|
309
340
|
headers.append("COORDINATES")
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
return headers, {
|
|
314
|
-
"is_decrypted": is_decrypted,
|
|
315
|
-
"is_unencrypted": is_unencrypted,
|
|
316
|
-
"is_aes_eax": is_aes_eax,
|
|
317
|
-
"is_unknown": is_unknown,
|
|
318
|
-
"has_real_location": has_real_location,
|
|
319
|
-
}
|
|
341
|
+
headers.append("PAYLOAD")
|
|
342
|
+
|
|
343
|
+
return headers
|
|
320
344
|
|
|
321
345
|
def _format_row(self, values: List) -> str:
|
|
322
346
|
"""Format a row with fixed column widths."""
|
|
@@ -334,42 +358,52 @@ class _StreamingTablePrinter(_StreamingPrinterBase):
|
|
|
334
358
|
parts.append("-" * width)
|
|
335
359
|
return "+-" + "-+-".join(parts) + "-+"
|
|
336
360
|
|
|
337
|
-
def print_row(self, pkt) -> None:
|
|
361
|
+
def print_row(self, pkt, decrypt_status: Optional[str] = None) -> None:
|
|
338
362
|
"""Print a single packet row, printing header first if needed."""
|
|
339
363
|
if not self._header_printed:
|
|
340
|
-
self._headers
|
|
341
|
-
# Print header with separator
|
|
364
|
+
self._headers = self._determine_columns(pkt)
|
|
342
365
|
click.echo("")
|
|
343
366
|
click.echo(self._make_separator())
|
|
344
367
|
click.secho(self._format_row(self._headers), bold=True)
|
|
345
368
|
click.echo(self._make_separator())
|
|
346
369
|
self._header_printed = True
|
|
347
370
|
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
371
|
+
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%H:%M:%S")
|
|
372
|
+
row: List = []
|
|
373
|
+
if self._show_decrypt_status:
|
|
374
|
+
row.append("OK" if decrypt_status == "ok" else "FAIL" if decrypt_status == "fail" else "-")
|
|
375
|
+
row.extend([pkt.timestamp, ts, pkt.rssi if pkt.rssi is not None else "None"])
|
|
351
376
|
|
|
352
|
-
|
|
353
|
-
|
|
377
|
+
version = getattr(pkt, "protocol_version", None)
|
|
378
|
+
row.append(version if version is not None else "-")
|
|
354
379
|
|
|
355
|
-
|
|
356
|
-
|
|
380
|
+
eid = getattr(pkt, "eid", None)
|
|
381
|
+
row.append(f"{eid:x}" if eid is not None else "-")
|
|
357
382
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
row.extend([pkt.protocol_version, hex(pkt.eid), salt_int])
|
|
383
|
+
auth_tag = getattr(pkt, "auth_tag", None)
|
|
384
|
+
row.append(auth_tag.hex() if auth_tag is not None else "-")
|
|
361
385
|
|
|
362
|
-
if
|
|
363
|
-
row.append(pkt.
|
|
386
|
+
if isinstance(pkt, DecryptedPacket) and pkt.counter is not None:
|
|
387
|
+
row.append(pkt.counter)
|
|
388
|
+
else:
|
|
389
|
+
row.append("-")
|
|
364
390
|
|
|
365
|
-
if
|
|
391
|
+
if isinstance(pkt, DecryptedPacket):
|
|
392
|
+
row.append(pkt.sequence if pkt.sequence is not None else "-")
|
|
393
|
+
elif isinstance(pkt, AesEaxPacket):
|
|
394
|
+
row.append(int.from_bytes(pkt.nonce_salt, "big"))
|
|
395
|
+
else:
|
|
396
|
+
row.append("-")
|
|
397
|
+
|
|
398
|
+
if self._show_net_id:
|
|
399
|
+
row.append(pkt.network_id if isinstance(pkt, UnencryptedPacket) else "-")
|
|
400
|
+
|
|
401
|
+
if self._show_coordinates:
|
|
366
402
|
loc = pkt.location
|
|
367
403
|
row.append(f"{loc.lat:.6f},{loc.lon:.6f}")
|
|
368
404
|
|
|
369
|
-
|
|
370
|
-
row.append(_format_payload(pkt.payload, self._payload_format))
|
|
405
|
+
row.append(_format_payload(_ctr_display_payload(pkt), self._payload_format))
|
|
371
406
|
|
|
372
|
-
# Print the data row
|
|
373
407
|
click.echo(self._format_row(row))
|
|
374
408
|
click.echo(self._make_separator())
|
|
375
409
|
self._packet_count += 1
|
|
@@ -378,8 +412,13 @@ class _StreamingTablePrinter(_StreamingPrinterBase):
|
|
|
378
412
|
class _StreamingJsonPrinter(_StreamingPrinterBase):
|
|
379
413
|
"""Print packets as a streaming JSON array."""
|
|
380
414
|
|
|
381
|
-
def __init__(
|
|
382
|
-
|
|
415
|
+
def __init__(
|
|
416
|
+
self,
|
|
417
|
+
payload_format: str = "base64",
|
|
418
|
+
to_dict_fn=None,
|
|
419
|
+
show_decrypt_status: bool = False,
|
|
420
|
+
):
|
|
421
|
+
super().__init__(show_decrypt_status=show_decrypt_status)
|
|
383
422
|
self._array_started = False
|
|
384
423
|
self._payload_format = payload_format
|
|
385
424
|
self._to_dict_fn = to_dict_fn or _packet_to_dict
|
|
@@ -388,9 +427,10 @@ class _StreamingJsonPrinter(_StreamingPrinterBase):
|
|
|
388
427
|
def suppress_info_messages(self) -> bool:
|
|
389
428
|
return True
|
|
390
429
|
|
|
391
|
-
def print_row(self, pkt) -> None:
|
|
430
|
+
def print_row(self, pkt, decrypt_status: Optional[str] = None) -> None:
|
|
392
431
|
"""Print a single packet as JSON."""
|
|
393
|
-
|
|
432
|
+
status = decrypt_status if self._show_decrypt_status else None
|
|
433
|
+
pkt_dict = self._to_dict_fn(pkt, self._payload_format, decrypt_status=status)
|
|
394
434
|
if not self._array_started:
|
|
395
435
|
click.echo("[")
|
|
396
436
|
self._array_started = True
|
|
@@ -424,7 +464,11 @@ _STREAMING_PRINTERS = {
|
|
|
424
464
|
# ---------------------------------------------------------------------------
|
|
425
465
|
|
|
426
466
|
|
|
427
|
-
def _sat_packet_to_dict(
|
|
467
|
+
def _sat_packet_to_dict(
|
|
468
|
+
pkt: SatellitePacket,
|
|
469
|
+
payload_format: str = "base64",
|
|
470
|
+
**_: object,
|
|
471
|
+
) -> dict:
|
|
428
472
|
"""Convert a SatellitePacket to a dictionary for JSON serialization."""
|
|
429
473
|
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%c")
|
|
430
474
|
return {
|
|
@@ -879,6 +923,12 @@ def ble_detect(
|
|
|
879
923
|
show_default=True,
|
|
880
924
|
help="Encoding format for packet payload",
|
|
881
925
|
)
|
|
926
|
+
@click.option(
|
|
927
|
+
"--show-failed-decryption",
|
|
928
|
+
is_flag=True,
|
|
929
|
+
default=False,
|
|
930
|
+
help="Show encrypted packets that fail decryption/authentication with the provided key. Adds a DECRYPT column indicating OK/FAIL.",
|
|
931
|
+
)
|
|
882
932
|
@click.pass_context
|
|
883
933
|
def ble_scan(
|
|
884
934
|
ctx,
|
|
@@ -892,6 +942,7 @@ def ble_scan(
|
|
|
892
942
|
scale_factor: int = 0,
|
|
893
943
|
output_format: str = "tabular",
|
|
894
944
|
payload_format: str = "base64",
|
|
945
|
+
show_failed_decryption: bool = False,
|
|
895
946
|
) -> None:
|
|
896
947
|
"""
|
|
897
948
|
Scan for UUID 0xFCA6 and print packets as they are found.
|
|
@@ -918,7 +969,10 @@ def ble_scan(
|
|
|
918
969
|
printer_class = _STREAMING_PRINTERS.get(
|
|
919
970
|
output_format.lower(), _StreamingTablePrinter
|
|
920
971
|
)
|
|
921
|
-
printer = printer_class(
|
|
972
|
+
printer = printer_class(
|
|
973
|
+
payload_format=payload_format,
|
|
974
|
+
show_decrypt_status=show_failed_decryption,
|
|
975
|
+
)
|
|
922
976
|
|
|
923
977
|
if not printer.suppress_info_messages:
|
|
924
978
|
click.secho("[INFO] Scanning for Hubble devices... (Press Ctrl+C to stop)")
|
|
@@ -967,26 +1021,24 @@ def ble_scan(
|
|
|
967
1021
|
if decoded_key:
|
|
968
1022
|
decrypted_pkt = decrypt_eax(decoded_key, pkt, scale_factor=scale_factor)
|
|
969
1023
|
if decrypted_pkt:
|
|
970
|
-
printer.print_row(decrypted_pkt)
|
|
971
|
-
|
|
972
|
-
printer.print_row(pkt)
|
|
1024
|
+
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
1025
|
+
elif show_failed_decryption:
|
|
1026
|
+
printer.print_row(pkt, decrypt_status="fail")
|
|
973
1027
|
else:
|
|
974
1028
|
printer.print_row(pkt)
|
|
975
|
-
# Encrypted packets: optionally decrypt and/or ingest
|
|
976
1029
|
elif isinstance(pkt, EncryptedPacket):
|
|
977
1030
|
if decoded_key:
|
|
978
1031
|
decrypted_pkt = decrypt(
|
|
979
1032
|
decoded_key, pkt, days=days, counter_mode=counter_mode
|
|
980
1033
|
)
|
|
981
1034
|
if decrypted_pkt:
|
|
982
|
-
printer.print_row(decrypted_pkt)
|
|
1035
|
+
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
983
1036
|
if ingest:
|
|
984
1037
|
org.ingest_packet(pkt)
|
|
985
|
-
|
|
986
|
-
printer.print_row(pkt)
|
|
1038
|
+
elif show_failed_decryption:
|
|
1039
|
+
printer.print_row(pkt, decrypt_status="fail")
|
|
987
1040
|
else:
|
|
988
1041
|
printer.print_row(pkt)
|
|
989
|
-
# Unknown version packets: always show
|
|
990
1042
|
elif isinstance(pkt, UnknownPacket):
|
|
991
1043
|
printer.print_row(pkt)
|
|
992
1044
|
except KeyboardInterrupt:
|
|
@@ -2613,6 +2665,24 @@ def list_devices(org: Organization) -> None:
|
|
|
2613
2665
|
_print_device(device)
|
|
2614
2666
|
|
|
2615
2667
|
|
|
2668
|
+
_PERIOD_EXPONENT_LABELS = {
|
|
2669
|
+
10: "≈17m",
|
|
2670
|
+
11: "≈34m",
|
|
2671
|
+
12: "≈1.1h",
|
|
2672
|
+
13: "≈2.3h",
|
|
2673
|
+
14: "≈4.6h",
|
|
2674
|
+
15: "≈9h",
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
|
|
2678
|
+
def _format_period_exponent(n: int) -> str:
|
|
2679
|
+
"""Human-readable duration label for a period exponent (period = 2^n seconds)."""
|
|
2680
|
+
label = _PERIOD_EXPONENT_LABELS.get(n)
|
|
2681
|
+
if label is not None:
|
|
2682
|
+
return label
|
|
2683
|
+
return f"{2 ** n}s" if n >= 0 else f"2^{n}s"
|
|
2684
|
+
|
|
2685
|
+
|
|
2616
2686
|
@org.command("register-device")
|
|
2617
2687
|
@click.option(
|
|
2618
2688
|
"--encryption",
|
|
@@ -2620,25 +2690,60 @@ def list_devices(org: Organization) -> None:
|
|
|
2620
2690
|
type=str,
|
|
2621
2691
|
default=None,
|
|
2622
2692
|
show_default=False,
|
|
2623
|
-
help="Encryption type [AES-256-CTR, AES-128-CTR, NONE]",
|
|
2693
|
+
help="Encryption type [AES-256-CTR, AES-128-CTR, AES-128-EAX, NONE]",
|
|
2624
2694
|
)
|
|
2625
2695
|
@click.option(
|
|
2626
2696
|
"--counter-source",
|
|
2627
2697
|
"-c",
|
|
2628
|
-
type=click.Choice(sorted(
|
|
2698
|
+
type=click.Choice(sorted([UNIX_TIME, DEVICE_UPTIME])),
|
|
2629
2699
|
default=None,
|
|
2630
2700
|
show_default=False,
|
|
2631
2701
|
help="EID rotation counter source",
|
|
2632
2702
|
)
|
|
2703
|
+
@click.option(
|
|
2704
|
+
"--period-seconds",
|
|
2705
|
+
type=int,
|
|
2706
|
+
default=None,
|
|
2707
|
+
show_default=False,
|
|
2708
|
+
help="EID rotation period in seconds (AES-128-EAX + DEVICE_UPTIME only).",
|
|
2709
|
+
)
|
|
2710
|
+
@click.option(
|
|
2711
|
+
"--period-exponent",
|
|
2712
|
+
type=int,
|
|
2713
|
+
default=None,
|
|
2714
|
+
show_default=False,
|
|
2715
|
+
help="EID rotation period exponent; period = 2^n seconds. Cloud accepts 10-15 (default 15).",
|
|
2716
|
+
)
|
|
2633
2717
|
@pass_orgcfg
|
|
2634
|
-
def register_device(org: Organization, encryption, counter_source) -> None:
|
|
2718
|
+
def register_device(org: Organization, encryption, counter_source, period_seconds, period_exponent) -> None:
|
|
2719
|
+
if period_seconds is not None and period_exponent is not None:
|
|
2720
|
+
raise click.UsageError("provide at most one of --period-seconds / --period-exponent")
|
|
2721
|
+
|
|
2635
2722
|
if encryption:
|
|
2636
2723
|
click.secho(f'[INFO] Overriding default encryption, using "{encryption}"')
|
|
2637
2724
|
if counter_source:
|
|
2638
2725
|
click.secho(f'[INFO] EID rotation counter source: "{counter_source}"')
|
|
2726
|
+
if period_seconds is not None:
|
|
2727
|
+
click.secho(f'[INFO] EID rotation period: {period_seconds}s')
|
|
2728
|
+
if period_exponent is not None:
|
|
2729
|
+
click.secho(
|
|
2730
|
+
f'[INFO] EID rotation period exponent: {period_exponent} ({_format_period_exponent(period_exponent)})'
|
|
2731
|
+
)
|
|
2732
|
+
if (
|
|
2733
|
+
encryption == "AES-128-EAX"
|
|
2734
|
+
and counter_source == DEVICE_UPTIME
|
|
2735
|
+
and period_seconds is None
|
|
2736
|
+
and period_exponent is None
|
|
2737
|
+
):
|
|
2738
|
+
click.secho(
|
|
2739
|
+
f'[INFO] Using default EID rotation period exponent: 15 ({_format_period_exponent(15)})'
|
|
2740
|
+
)
|
|
2741
|
+
|
|
2639
2742
|
click.secho(str(org.register_device(
|
|
2640
2743
|
encryption=encryption,
|
|
2641
2744
|
counter_source=counter_source,
|
|
2745
|
+
period_seconds=period_seconds,
|
|
2746
|
+
period_exponent=period_exponent,
|
|
2642
2747
|
)))
|
|
2643
2748
|
|
|
2644
2749
|
|
|
@@ -170,6 +170,8 @@ def register_device(
|
|
|
170
170
|
env: Environment,
|
|
171
171
|
encryption: str = "AES-256-CTR",
|
|
172
172
|
counter_source: Optional[str] = None,
|
|
173
|
+
period_in_seconds: Optional[int] = None,
|
|
174
|
+
period_exponent: Optional[int] = None,
|
|
173
175
|
) -> Any:
|
|
174
176
|
"""Create a new device and return it."""
|
|
175
177
|
data: dict = {
|
|
@@ -177,7 +179,11 @@ def register_device(
|
|
|
177
179
|
"encryption": encryption or "AES-256-CTR",
|
|
178
180
|
}
|
|
179
181
|
if counter_source is not None:
|
|
180
|
-
eid_rotation: dict = {"counter_source": counter_source
|
|
182
|
+
eid_rotation: dict = {"counter_source": counter_source}
|
|
183
|
+
if period_in_seconds is not None:
|
|
184
|
+
eid_rotation["period_in_seconds"] = period_in_seconds
|
|
185
|
+
if period_exponent is not None:
|
|
186
|
+
eid_rotation["period_exponent"] = period_exponent
|
|
181
187
|
data["eid_rotation"] = eid_rotation
|
|
182
188
|
return cloud_request(
|
|
183
189
|
method="POST",
|
|
@@ -135,8 +135,11 @@ def decrypt_eax(
|
|
|
135
135
|
tags={},
|
|
136
136
|
payload=decrypted,
|
|
137
137
|
rssi=pkt.rssi,
|
|
138
|
-
counter=
|
|
138
|
+
counter=i,
|
|
139
139
|
sequence=int.from_bytes(pkt.nonce_salt, "big"),
|
|
140
|
+
protocol_version=pkt.protocol_version,
|
|
141
|
+
eid=pkt.eid,
|
|
142
|
+
auth_tag=pkt.auth_tag,
|
|
140
143
|
)
|
|
141
144
|
|
|
142
145
|
return None
|
|
@@ -194,6 +197,9 @@ def decrypt(
|
|
|
194
197
|
rssi=encrypted_pkt.rssi,
|
|
195
198
|
counter=candidate,
|
|
196
199
|
sequence=parsed.seq_no,
|
|
200
|
+
protocol_version=encrypted_pkt.protocol_version,
|
|
201
|
+
eid=encrypted_pkt.eid,
|
|
202
|
+
auth_tag=parsed.auth_tag,
|
|
197
203
|
)
|
|
198
204
|
return None
|
|
199
205
|
|
|
@@ -10,10 +10,7 @@ from .crypto import UNIX_TIME, DEVICE_UPTIME
|
|
|
10
10
|
from .errors import InvalidCredentialsError, ValidationError
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
_VALID_COUNTER_SOURCES = {UNIX_TIME, DEVICE_UPTIME
|
|
14
|
-
|
|
15
|
-
# Cloud API still uses EPOCH_TIME; map UNIX_TIME → EPOCH_TIME at the boundary.
|
|
16
|
-
_COUNTER_SOURCE_TO_API = {UNIX_TIME: "EPOCH_TIME"}
|
|
13
|
+
_VALID_COUNTER_SOURCES = {UNIX_TIME, DEVICE_UPTIME}
|
|
17
14
|
|
|
18
15
|
|
|
19
16
|
class Organization:
|
|
@@ -53,28 +50,47 @@ class Organization:
|
|
|
53
50
|
self,
|
|
54
51
|
encryption: Optional[str] = None,
|
|
55
52
|
counter_source: Optional[str] = None,
|
|
53
|
+
period_seconds: Optional[int] = None,
|
|
54
|
+
period_exponent: Optional[int] = None,
|
|
56
55
|
) -> Device:
|
|
57
56
|
"""
|
|
58
57
|
Register a new device in this organization and return it.
|
|
59
58
|
Returned Device will have an ID and provisioned key.
|
|
60
59
|
|
|
61
60
|
Args:
|
|
62
|
-
encryption: Encryption type ("AES-256-CTR", "AES-128-CTR", or "NONE").
|
|
61
|
+
encryption: Encryption type ("AES-256-CTR", "AES-128-CTR", "AES-128-EAX", or "NONE").
|
|
63
62
|
Defaults to "AES-256-CTR".
|
|
64
63
|
counter_source: EID rotation counter source ("UNIX_TIME" or "DEVICE_UPTIME").
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
period_seconds: EID rotation period in seconds. Only valid when
|
|
65
|
+
encryption='AES-128-EAX' and counter_source='DEVICE_UPTIME'.
|
|
66
|
+
period_exponent: EID rotation period exponent (period = 2^n seconds). Only valid
|
|
67
|
+
when encryption='AES-128-EAX' and counter_source='DEVICE_UPTIME'.
|
|
68
|
+
Mutually exclusive with period_seconds.
|
|
67
69
|
"""
|
|
68
70
|
if counter_source is not None and counter_source not in _VALID_COUNTER_SOURCES:
|
|
69
71
|
raise ValidationError(
|
|
70
72
|
f"counter_source must be one of {sorted(_VALID_COUNTER_SOURCES)}, got {counter_source!r}"
|
|
71
73
|
)
|
|
72
|
-
|
|
74
|
+
if period_seconds is not None and period_exponent is not None:
|
|
75
|
+
raise ValidationError(
|
|
76
|
+
"provide at most one of period_seconds, period_exponent"
|
|
77
|
+
)
|
|
78
|
+
if period_seconds is not None or period_exponent is not None:
|
|
79
|
+
if encryption != "AES-128-EAX":
|
|
80
|
+
raise ValidationError(
|
|
81
|
+
"period_seconds/period_exponent requires encryption='AES-128-EAX'"
|
|
82
|
+
)
|
|
83
|
+
if counter_source != DEVICE_UPTIME:
|
|
84
|
+
raise ValidationError(
|
|
85
|
+
"period_seconds/period_exponent requires counter_source='DEVICE_UPTIME'"
|
|
86
|
+
)
|
|
73
87
|
resp = cloud.register_device(
|
|
74
88
|
credentials=self.credentials,
|
|
75
89
|
env=self.env,
|
|
76
90
|
encryption=encryption,
|
|
77
|
-
counter_source=
|
|
91
|
+
counter_source=counter_source,
|
|
92
|
+
period_in_seconds=period_seconds,
|
|
93
|
+
period_exponent=period_exponent,
|
|
78
94
|
)
|
|
79
95
|
device = resp["devices"][0]
|
|
80
96
|
key_bytes = base64.b64decode(device["key"]) if device.get("key") else None
|
|
@@ -163,7 +179,7 @@ class Organization:
|
|
|
163
179
|
lon=packet["location"]["longitude"],
|
|
164
180
|
),
|
|
165
181
|
tags=packet["device"]["tags"],
|
|
166
|
-
payload=packet["device"]["payload"],
|
|
182
|
+
payload=base64.b64decode(packet["device"]["payload"]),
|
|
167
183
|
rssi=packet["device"]["rssi"],
|
|
168
184
|
counter=packet["device"]["counter"],
|
|
169
185
|
sequence=packet["device"]["sequence_number"],
|
|
@@ -22,6 +22,11 @@ class EncryptedPacket:
|
|
|
22
22
|
location: Optional[Location] # None if unknown
|
|
23
23
|
payload: bytes # opaque encrypted bytes
|
|
24
24
|
rssi: int # received signal strength (dBm)
|
|
25
|
+
# Fields extracted from the raw advertisement, when present. AES-CTR
|
|
26
|
+
# carries auth_tag but no EID; None means the field isn't applicable.
|
|
27
|
+
protocol_version: Optional[int] = None
|
|
28
|
+
eid: Optional[int] = None
|
|
29
|
+
auth_tag: Optional[bytes] = None
|
|
25
30
|
|
|
26
31
|
|
|
27
32
|
@dataclass(frozen=True)
|
|
@@ -74,6 +79,12 @@ class DecryptedPacket:
|
|
|
74
79
|
rssi: int # received signal strength (dBm)
|
|
75
80
|
counter: Optional[int] = None
|
|
76
81
|
sequence: Optional[int] = None
|
|
82
|
+
# Preserved from the raw packet so the original version / EID / auth tag
|
|
83
|
+
# can still be displayed alongside the decrypted payload. AES-CTR has no
|
|
84
|
+
# EID.
|
|
85
|
+
protocol_version: Optional[int] = None
|
|
86
|
+
eid: Optional[int] = None
|
|
87
|
+
auth_tag: Optional[bytes] = None
|
|
77
88
|
|
|
78
89
|
|
|
79
90
|
@dataclass(frozen=True)
|
|
@@ -371,6 +371,64 @@ class TestCliAesEaxScan:
|
|
|
371
371
|
assert len(parsed) == 1
|
|
372
372
|
assert parsed[0]["counter"] == 7
|
|
373
373
|
|
|
374
|
+
@patch("hubblenetwork.cli.decrypt_eax")
|
|
375
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
376
|
+
def test_scan_aes_eax_auth_fail_skipped_by_default(self, mock_scan, mock_decrypt):
|
|
377
|
+
"""Packets failing AES-EAX auth are skipped when --show-failed-decryption is off."""
|
|
378
|
+
pkt = _make_dummy_aes_eax_packet()
|
|
379
|
+
mock_scan.side_effect = [pkt, None]
|
|
380
|
+
mock_decrypt.return_value = None # auth failure
|
|
381
|
+
|
|
382
|
+
runner = CliRunner()
|
|
383
|
+
key_b64 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
|
384
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", key_b64, "-o", "json"])
|
|
385
|
+
assert result.exit_code == 0
|
|
386
|
+
parsed = json.loads(result.output)
|
|
387
|
+
assert parsed == []
|
|
388
|
+
|
|
389
|
+
@patch("hubblenetwork.cli.decrypt_eax")
|
|
390
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
391
|
+
def test_scan_aes_eax_auth_fail_shown_when_flag_set(self, mock_scan, mock_decrypt):
|
|
392
|
+
"""With --show-failed-decryption, failing packets are shown with fail status."""
|
|
393
|
+
pkt = _make_dummy_aes_eax_packet()
|
|
394
|
+
mock_scan.side_effect = [pkt, None]
|
|
395
|
+
mock_decrypt.return_value = None # auth failure
|
|
396
|
+
|
|
397
|
+
runner = CliRunner()
|
|
398
|
+
key_b64 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
|
399
|
+
result = runner.invoke(
|
|
400
|
+
cli,
|
|
401
|
+
["ble", "scan", "--timeout", "1", "--key", key_b64, "-o", "json", "--show-failed-decryption"],
|
|
402
|
+
)
|
|
403
|
+
assert result.exit_code == 0
|
|
404
|
+
parsed = json.loads(result.output)
|
|
405
|
+
assert len(parsed) == 1
|
|
406
|
+
assert parsed[0]["decrypt_status"] == "fail"
|
|
407
|
+
assert parsed[0]["protocol_version"] == 2
|
|
408
|
+
|
|
409
|
+
@patch("hubblenetwork.cli.decrypt_eax")
|
|
410
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
411
|
+
def test_scan_aes_eax_success_shows_ok_when_flag_set(self, mock_scan, mock_decrypt):
|
|
412
|
+
"""With --show-failed-decryption, successful decrypts carry ok status."""
|
|
413
|
+
pkt = _make_dummy_aes_eax_packet()
|
|
414
|
+
mock_scan.side_effect = [pkt, None]
|
|
415
|
+
mock_decrypt.return_value = DecryptedPacket(
|
|
416
|
+
timestamp=1700000000, device_id="", device_name="",
|
|
417
|
+
location=Location(lat=90, lon=0, fake=True), tags={},
|
|
418
|
+
payload=b"decrypted", rssi=-65, counter=7, sequence=None,
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
runner = CliRunner()
|
|
422
|
+
key_b64 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
|
423
|
+
result = runner.invoke(
|
|
424
|
+
cli,
|
|
425
|
+
["ble", "scan", "--timeout", "1", "--key", key_b64, "-o", "json", "--show-failed-decryption"],
|
|
426
|
+
)
|
|
427
|
+
assert result.exit_code == 0
|
|
428
|
+
parsed = json.loads(result.output)
|
|
429
|
+
assert len(parsed) == 1
|
|
430
|
+
assert parsed[0]["decrypt_status"] == "ok"
|
|
431
|
+
|
|
374
432
|
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
375
433
|
def test_scan_unknown_packet_tabular(self, mock_scan):
|
|
376
434
|
"""Unknown version packet shows version in tabular output."""
|
|
@@ -71,9 +71,9 @@ class TestProdEnvironment:
|
|
|
71
71
|
)
|
|
72
72
|
assert updated is not None
|
|
73
73
|
|
|
74
|
-
def
|
|
74
|
+
def test_register_device_with_unix_time(self, credentials, env):
|
|
75
75
|
result = register_device(
|
|
76
|
-
credentials=credentials, env=env, counter_source="
|
|
76
|
+
credentials=credentials, env=env, counter_source="UNIX_TIME"
|
|
77
77
|
)
|
|
78
78
|
assert "devices" in result
|
|
79
79
|
assert len(result["devices"]) > 0
|
|
@@ -87,6 +87,18 @@ class TestProdEnvironment:
|
|
|
87
87
|
assert len(result["devices"]) > 0
|
|
88
88
|
assert result["devices"][0]["device_id"]
|
|
89
89
|
|
|
90
|
+
def test_register_device_aes_128_eax(self, credentials, env):
|
|
91
|
+
result = register_device(
|
|
92
|
+
credentials=credentials,
|
|
93
|
+
env=env,
|
|
94
|
+
encryption="AES-128-EAX",
|
|
95
|
+
counter_source="DEVICE_UPTIME",
|
|
96
|
+
period_in_seconds=1024,
|
|
97
|
+
)
|
|
98
|
+
assert "devices" in result
|
|
99
|
+
assert len(result["devices"]) > 0
|
|
100
|
+
assert result["devices"][0]["device_id"]
|
|
101
|
+
|
|
90
102
|
def test_retrieve_packets(self, credentials, env):
|
|
91
103
|
# First get a device to query
|
|
92
104
|
devices_result, _ = list_devices(credentials=credentials, env=env)
|
|
@@ -149,9 +161,9 @@ class TestTestingEnvironment:
|
|
|
149
161
|
)
|
|
150
162
|
assert updated is not None
|
|
151
163
|
|
|
152
|
-
def
|
|
164
|
+
def test_register_device_with_unix_time(self, credentials, env):
|
|
153
165
|
result = register_device(
|
|
154
|
-
credentials=credentials, env=env, counter_source="
|
|
166
|
+
credentials=credentials, env=env, counter_source="UNIX_TIME"
|
|
155
167
|
)
|
|
156
168
|
assert "devices" in result
|
|
157
169
|
assert len(result["devices"]) > 0
|
|
@@ -165,6 +177,18 @@ class TestTestingEnvironment:
|
|
|
165
177
|
assert len(result["devices"]) > 0
|
|
166
178
|
assert result["devices"][0]["device_id"]
|
|
167
179
|
|
|
180
|
+
def test_register_device_aes_128_eax(self, credentials, env):
|
|
181
|
+
result = register_device(
|
|
182
|
+
credentials=credentials,
|
|
183
|
+
env=env,
|
|
184
|
+
encryption="AES-128-EAX",
|
|
185
|
+
counter_source="DEVICE_UPTIME",
|
|
186
|
+
period_in_seconds=1024,
|
|
187
|
+
)
|
|
188
|
+
assert "devices" in result
|
|
189
|
+
assert len(result["devices"]) > 0
|
|
190
|
+
assert result["devices"][0]["device_id"]
|
|
191
|
+
|
|
168
192
|
|
|
169
193
|
class TestInvalidCredentials:
|
|
170
194
|
"""Test behavior with invalid credentials."""
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"""Tests for org delete-device
|
|
1
|
+
"""Tests for org commands (delete-device, get-packets)."""
|
|
2
|
+
import base64
|
|
2
3
|
import pytest
|
|
3
4
|
from unittest.mock import patch, MagicMock
|
|
4
5
|
from click.testing import CliRunner
|
|
@@ -127,3 +128,99 @@ class TestDeleteDeviceCLI:
|
|
|
127
128
|
|
|
128
129
|
assert result.exit_code != 0
|
|
129
130
|
assert result.exception is not None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class TestOrgRetrievePackets:
|
|
134
|
+
"""Tests for org.retrieve_packets — ensures payload is bytes, not a raw API string."""
|
|
135
|
+
|
|
136
|
+
def _make_api_response(self, payload_bytes: bytes):
|
|
137
|
+
"""Return a minimal cloud API response dict with payload base64-encoded as the API does."""
|
|
138
|
+
return {
|
|
139
|
+
"packets": [
|
|
140
|
+
{
|
|
141
|
+
"device": {
|
|
142
|
+
"timestamp": 1700000000,
|
|
143
|
+
"id": "dev-abc",
|
|
144
|
+
"name": "My Device",
|
|
145
|
+
"tags": {},
|
|
146
|
+
"payload": base64.b64encode(payload_bytes).decode("ascii"),
|
|
147
|
+
"rssi": -65,
|
|
148
|
+
"counter": 1,
|
|
149
|
+
"sequence_number": 0,
|
|
150
|
+
},
|
|
151
|
+
"location": {"latitude": 0.0, "longitude": 0.0},
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
def test_payload_is_bytes(self):
|
|
157
|
+
from hubblenetwork.org import Organization
|
|
158
|
+
from hubblenetwork.packets import DecryptedPacket
|
|
159
|
+
|
|
160
|
+
raw = b'\xde\xad\xbe\xef'
|
|
161
|
+
api_resp = self._make_api_response(raw)
|
|
162
|
+
|
|
163
|
+
org = MagicMock(spec=Organization)
|
|
164
|
+
org.credentials = MagicMock()
|
|
165
|
+
org.env = MagicMock()
|
|
166
|
+
|
|
167
|
+
with patch("hubblenetwork.org.cloud.retrieve_packets", return_value=(api_resp, None)):
|
|
168
|
+
packets = Organization.retrieve_packets(org, MagicMock())
|
|
169
|
+
|
|
170
|
+
assert len(packets) == 1
|
|
171
|
+
pkt = packets[0]
|
|
172
|
+
assert isinstance(pkt, DecryptedPacket)
|
|
173
|
+
assert isinstance(pkt.payload, bytes), "payload must be bytes, not a string"
|
|
174
|
+
assert pkt.payload == raw
|
|
175
|
+
|
|
176
|
+
def test_payload_format_hex_in_cli(self):
|
|
177
|
+
"""--payload-format hex must show hex output, not base64."""
|
|
178
|
+
from hubblenetwork.cli import cli
|
|
179
|
+
|
|
180
|
+
raw = b'\xab\xc6\x79'
|
|
181
|
+
api_resp = {
|
|
182
|
+
"packets": [
|
|
183
|
+
{
|
|
184
|
+
"device": {
|
|
185
|
+
"timestamp": 1700000000,
|
|
186
|
+
"id": "dev-abc",
|
|
187
|
+
"name": "My Device",
|
|
188
|
+
"tags": {},
|
|
189
|
+
"payload": base64.b64encode(raw).decode("ascii"),
|
|
190
|
+
"rssi": -65,
|
|
191
|
+
"counter": 1,
|
|
192
|
+
"sequence_number": 0,
|
|
193
|
+
},
|
|
194
|
+
"location": {"latitude": 0.0, "longitude": 0.0},
|
|
195
|
+
}
|
|
196
|
+
]
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
from hubblenetwork.packets import DecryptedPacket, Location
|
|
200
|
+
|
|
201
|
+
runner = CliRunner()
|
|
202
|
+
with patch("hubblenetwork.cli.Organization") as mock_org_cls:
|
|
203
|
+
mock_org_cls.return_value = MagicMock(spec=Organization)
|
|
204
|
+
mock_org = mock_org_cls.return_value
|
|
205
|
+
mock_org.retrieve_packets.return_value = [
|
|
206
|
+
DecryptedPacket(
|
|
207
|
+
timestamp=1700000000,
|
|
208
|
+
device_id="dev-abc",
|
|
209
|
+
device_name="My Device",
|
|
210
|
+
location=Location(lat=0.0, lon=0.0, fake=True),
|
|
211
|
+
tags={},
|
|
212
|
+
payload=raw,
|
|
213
|
+
rssi=-65,
|
|
214
|
+
counter=1,
|
|
215
|
+
sequence=0,
|
|
216
|
+
)
|
|
217
|
+
]
|
|
218
|
+
result = runner.invoke(
|
|
219
|
+
cli,
|
|
220
|
+
["org", "--org-id", "fake-org", "--token", "fake-token",
|
|
221
|
+
"get-packets", "dev-abc", "--payload-format", "hex"],
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
assert result.exit_code == 0, result.output
|
|
225
|
+
assert "ABC679" in result.output
|
|
226
|
+
assert base64.b64encode(raw).decode("ascii") not in result.output
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from unittest.mock import patch, MagicMock
|
|
3
|
+
from hubblenetwork.cloud import register_device, Credentials, Environment
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.fixture
|
|
7
|
+
def env():
|
|
8
|
+
return Environment(name="TESTING", url="https://test.example.com")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture
|
|
12
|
+
def credentials():
|
|
13
|
+
return Credentials(org_id="test-org", api_token="test-token")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TestRegisterDeviceRequestBody:
|
|
17
|
+
@patch("hubblenetwork.cloud.cloud_request")
|
|
18
|
+
def test_default_body(self, mock_request, credentials, env):
|
|
19
|
+
mock_request.return_value = ({"devices": [{"device_id": "d1", "key": "abc="}]}, None)
|
|
20
|
+
register_device(credentials=credentials, env=env)
|
|
21
|
+
body = mock_request.call_args.kwargs["json"]
|
|
22
|
+
assert body == {"n_devices": 1, "encryption": "AES-256-CTR"}
|
|
23
|
+
|
|
24
|
+
@patch("hubblenetwork.cloud.cloud_request")
|
|
25
|
+
def test_counter_source_no_pool_size(self, mock_request, credentials, env):
|
|
26
|
+
"""pool_size should NOT be included in the request body."""
|
|
27
|
+
mock_request.return_value = ({"devices": [{"device_id": "d1", "key": "abc="}]}, None)
|
|
28
|
+
register_device(credentials=credentials, env=env, counter_source="DEVICE_UPTIME")
|
|
29
|
+
body = mock_request.call_args.kwargs["json"]
|
|
30
|
+
assert body == {
|
|
31
|
+
"n_devices": 1,
|
|
32
|
+
"encryption": "AES-256-CTR",
|
|
33
|
+
"eid_rotation": {"counter_source": "DEVICE_UPTIME"},
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
@patch("hubblenetwork.cloud.cloud_request")
|
|
37
|
+
def test_aes_eax_with_period_seconds(self, mock_request, credentials, env):
|
|
38
|
+
mock_request.return_value = ({"devices": [{"device_id": "d1", "key": "abc="}]}, None)
|
|
39
|
+
register_device(
|
|
40
|
+
credentials=credentials,
|
|
41
|
+
env=env,
|
|
42
|
+
encryption="AES-128-EAX",
|
|
43
|
+
counter_source="DEVICE_UPTIME",
|
|
44
|
+
period_in_seconds=1024,
|
|
45
|
+
)
|
|
46
|
+
body = mock_request.call_args.kwargs["json"]
|
|
47
|
+
assert body == {
|
|
48
|
+
"n_devices": 1,
|
|
49
|
+
"encryption": "AES-128-EAX",
|
|
50
|
+
"eid_rotation": {
|
|
51
|
+
"counter_source": "DEVICE_UPTIME",
|
|
52
|
+
"period_in_seconds": 1024,
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@patch("hubblenetwork.cloud.cloud_request")
|
|
57
|
+
def test_counter_source_without_period(self, mock_request, credentials, env):
|
|
58
|
+
"""period_in_seconds omitted when not provided."""
|
|
59
|
+
mock_request.return_value = ({"devices": [{"device_id": "d1", "key": "abc="}]}, None)
|
|
60
|
+
register_device(
|
|
61
|
+
credentials=credentials,
|
|
62
|
+
env=env,
|
|
63
|
+
encryption="AES-128-EAX",
|
|
64
|
+
counter_source="DEVICE_UPTIME",
|
|
65
|
+
)
|
|
66
|
+
body = mock_request.call_args.kwargs["json"]
|
|
67
|
+
assert body == {
|
|
68
|
+
"n_devices": 1,
|
|
69
|
+
"encryption": "AES-128-EAX",
|
|
70
|
+
"eid_rotation": {"counter_source": "DEVICE_UPTIME"},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
@patch("hubblenetwork.cloud.cloud_request")
|
|
74
|
+
def test_aes_eax_with_period_exponent(self, mock_request, credentials, env):
|
|
75
|
+
mock_request.return_value = ({"devices": [{"device_id": "d1", "key": "abc="}]}, None)
|
|
76
|
+
register_device(
|
|
77
|
+
credentials=credentials,
|
|
78
|
+
env=env,
|
|
79
|
+
encryption="AES-128-EAX",
|
|
80
|
+
counter_source="DEVICE_UPTIME",
|
|
81
|
+
period_exponent=15,
|
|
82
|
+
)
|
|
83
|
+
body = mock_request.call_args.kwargs["json"]
|
|
84
|
+
assert body == {
|
|
85
|
+
"n_devices": 1,
|
|
86
|
+
"encryption": "AES-128-EAX",
|
|
87
|
+
"eid_rotation": {
|
|
88
|
+
"counter_source": "DEVICE_UPTIME",
|
|
89
|
+
"period_exponent": 15,
|
|
90
|
+
},
|
|
91
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from unittest.mock import patch, MagicMock
|
|
3
|
+
from hubblenetwork.org import Organization
|
|
4
|
+
from hubblenetwork.errors import ValidationError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@pytest.fixture
|
|
8
|
+
def org():
|
|
9
|
+
"""Create an Organization with mocked cloud calls."""
|
|
10
|
+
with patch("hubblenetwork.org.cloud.get_env_from_credentials") as mock_env, \
|
|
11
|
+
patch("hubblenetwork.org.cloud.retrieve_org_metadata") as mock_meta:
|
|
12
|
+
mock_env.return_value = MagicMock(name="TESTING", url="https://test.example.com")
|
|
13
|
+
mock_meta.return_value = {"name": "Test Org"}
|
|
14
|
+
return Organization(org_id="test-org", api_token="test-token")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TestPeriodSecondsValidation:
|
|
18
|
+
def test_period_seconds_requires_aes_128_eax(self, org):
|
|
19
|
+
with pytest.raises(ValidationError, match="AES-128-EAX"):
|
|
20
|
+
org.register_device(
|
|
21
|
+
encryption="AES-256-CTR",
|
|
22
|
+
counter_source="DEVICE_UPTIME",
|
|
23
|
+
period_seconds=1024,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def test_period_seconds_requires_device_uptime(self, org):
|
|
27
|
+
with pytest.raises(ValidationError, match="DEVICE_UPTIME"):
|
|
28
|
+
org.register_device(
|
|
29
|
+
encryption="AES-128-EAX",
|
|
30
|
+
counter_source="UNIX_TIME",
|
|
31
|
+
period_seconds=1024,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TestPeriodExponentValidation:
|
|
36
|
+
def test_period_exponent_requires_aes_128_eax(self, org):
|
|
37
|
+
with pytest.raises(ValidationError, match="AES-128-EAX"):
|
|
38
|
+
org.register_device(
|
|
39
|
+
encryption="AES-256-CTR",
|
|
40
|
+
counter_source="DEVICE_UPTIME",
|
|
41
|
+
period_exponent=15,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def test_period_exponent_requires_device_uptime(self, org):
|
|
45
|
+
with pytest.raises(ValidationError, match="DEVICE_UPTIME"):
|
|
46
|
+
org.register_device(
|
|
47
|
+
encryption="AES-128-EAX",
|
|
48
|
+
counter_source="UNIX_TIME",
|
|
49
|
+
period_exponent=15,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TestMutualExclusion:
|
|
54
|
+
def test_period_seconds_and_exponent_both_set_rejected(self, org):
|
|
55
|
+
with pytest.raises(ValidationError, match="at most one of period_seconds, period_exponent"):
|
|
56
|
+
org.register_device(
|
|
57
|
+
encryption="AES-128-EAX",
|
|
58
|
+
counter_source="DEVICE_UPTIME",
|
|
59
|
+
period_seconds=1024,
|
|
60
|
+
period_exponent=10,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TestForwardingToCloud:
|
|
65
|
+
@patch("hubblenetwork.org.cloud.register_device")
|
|
66
|
+
def test_period_seconds_forwarded_as_period_in_seconds(self, mock_reg, org):
|
|
67
|
+
mock_reg.return_value = {"devices": [{"device_id": "d1", "key": "YWJj"}]}
|
|
68
|
+
org.register_device(
|
|
69
|
+
encryption="AES-128-EAX",
|
|
70
|
+
counter_source="DEVICE_UPTIME",
|
|
71
|
+
period_seconds=1024,
|
|
72
|
+
)
|
|
73
|
+
kwargs = mock_reg.call_args.kwargs
|
|
74
|
+
assert kwargs["period_in_seconds"] == 1024
|
|
75
|
+
assert kwargs["period_exponent"] is None
|
|
76
|
+
|
|
77
|
+
@patch("hubblenetwork.org.cloud.register_device")
|
|
78
|
+
def test_period_exponent_forwarded_unchanged(self, mock_reg, org):
|
|
79
|
+
mock_reg.return_value = {"devices": [{"device_id": "d1", "key": "YWJj"}]}
|
|
80
|
+
org.register_device(
|
|
81
|
+
encryption="AES-128-EAX",
|
|
82
|
+
counter_source="DEVICE_UPTIME",
|
|
83
|
+
period_exponent=15,
|
|
84
|
+
)
|
|
85
|
+
kwargs = mock_reg.call_args.kwargs
|
|
86
|
+
assert kwargs["period_exponent"] == 15
|
|
87
|
+
assert kwargs["period_in_seconds"] is None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|