tile-identity-resolver 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kbck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: tile-identity-resolver
3
+ Version: 0.1.0
4
+ Summary: Resolve Tile identities from FEED service data without Bluetooth dependencies
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/kbck/tile-identity-resolver
7
+ Project-URL: Repository, https://github.com/kbck/tile-identity-resolver
8
+ Project-URL: Issues, https://github.com/kbck/tile-identity-resolver/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest<9,>=8; extra == "test"
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest<9,>=8; extra == "dev"
20
+ Requires-Dist: ruff<1,>=0.11; extra == "dev"
21
+ Requires-Dist: build<2,>=1; extra == "dev"
22
+ Requires-Dist: mypy<3,>=1.15; extra == "dev"
23
+ Requires-Dist: twine<7,>=6; extra == "dev"
24
+ Requires-Dist: check-wheel-contents<1,>=0.6; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # Tile Identity Resolver
28
+
29
+ A dependency-free Python library for identifying registered Tile trackers from
30
+ version-2 FEED service data. Requires Python 3.10 or newer.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ python -m pip install tile-identity-resolver
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from tile_identity_resolver import Tile, TileResolver
42
+
43
+ # Replace these example credentials with your Tile's ID and auth key.
44
+ tile = Tile(
45
+ tile_id="0011223344556677",
46
+ auth_key="AAECAwQFBgcICQoLDA0ODw==",
47
+ )
48
+ resolver = TileResolver([tile])
49
+
50
+ # Pass the raw service-data value for UUID 0000feed-0000-1000-8000-00805f9b34fb.
51
+ def handle_feed_payload(payload: bytes) -> None:
52
+ info = resolver.resolve(payload)
53
+ if info is not None:
54
+ print(info.tile.tile_id, info.counter, info.version, info.flags)
55
+ ```
56
+
57
+ Tile IDs are eight-byte lowercase hex strings. Auth keys are sixteen-byte hex
58
+ or padded Base64 strings. Invalid credentials raise `ValueError`.
59
+
60
+ ## API
61
+
62
+ | API | Behavior |
63
+ | --- | --- |
64
+ | `TileResolver(tiles=())` | Register one or more Tiles |
65
+ | `resolver.add(tile)` | Register a Tile; duplicate IDs raise `ValueError` |
66
+ | `resolver.remove(tile_id)` | Remove a Tile; missing IDs raise `KeyError` |
67
+ | `resolver.tiles` | Immutable snapshot of registered Tiles |
68
+ | `resolver.resolve(payload)` | Return `TileInfo` for an unambiguous match, otherwise `None` |
69
+
70
+ `TileInfo` contains the registered `tile`, `counter`, `version`, and `flags`.
71
+ Remove and re-add a Tile to replace its key.
72
+
73
+ Registration precomputes private IDs and uses memory per Tile. In async apps,
74
+ prepare the resolver in a worker thread and serialize access during mutations.
75
+ The library resolves identities only; it does not track Bluetooth addresses or
76
+ presence, and a match does not prove freshness or proximity.
77
+
78
+ ## Development
79
+
80
+ ```sh
81
+ python -m pip install -e '.[dev]'
82
+ python tools/check_package.py
83
+ ```
84
+
85
+ Runs tests, code checks, and package validation.
86
+
87
+ ## Acknowledgements
88
+
89
+ Based on [Security and Privacy Analysis of Tile's Location Tracking Protocol](https://www.usenix.org/conference/usenixsecurity26/presentation/kumar-akshaya)
90
+ by Akshaya Kumar, Anna Raymaker, and Michael A. Specter (USENIX Security 2026).
91
+
92
+ Unofficial; not affiliated with Tile or Life360.
93
+ Licensed under the [MIT License](LICENSE).
@@ -0,0 +1,67 @@
1
+ # Tile Identity Resolver
2
+
3
+ A dependency-free Python library for identifying registered Tile trackers from
4
+ version-2 FEED service data. Requires Python 3.10 or newer.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ python -m pip install tile-identity-resolver
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```python
15
+ from tile_identity_resolver import Tile, TileResolver
16
+
17
+ # Replace these example credentials with your Tile's ID and auth key.
18
+ tile = Tile(
19
+ tile_id="0011223344556677",
20
+ auth_key="AAECAwQFBgcICQoLDA0ODw==",
21
+ )
22
+ resolver = TileResolver([tile])
23
+
24
+ # Pass the raw service-data value for UUID 0000feed-0000-1000-8000-00805f9b34fb.
25
+ def handle_feed_payload(payload: bytes) -> None:
26
+ info = resolver.resolve(payload)
27
+ if info is not None:
28
+ print(info.tile.tile_id, info.counter, info.version, info.flags)
29
+ ```
30
+
31
+ Tile IDs are eight-byte lowercase hex strings. Auth keys are sixteen-byte hex
32
+ or padded Base64 strings. Invalid credentials raise `ValueError`.
33
+
34
+ ## API
35
+
36
+ | API | Behavior |
37
+ | --- | --- |
38
+ | `TileResolver(tiles=())` | Register one or more Tiles |
39
+ | `resolver.add(tile)` | Register a Tile; duplicate IDs raise `ValueError` |
40
+ | `resolver.remove(tile_id)` | Remove a Tile; missing IDs raise `KeyError` |
41
+ | `resolver.tiles` | Immutable snapshot of registered Tiles |
42
+ | `resolver.resolve(payload)` | Return `TileInfo` for an unambiguous match, otherwise `None` |
43
+
44
+ `TileInfo` contains the registered `tile`, `counter`, `version`, and `flags`.
45
+ Remove and re-add a Tile to replace its key.
46
+
47
+ Registration precomputes private IDs and uses memory per Tile. In async apps,
48
+ prepare the resolver in a worker thread and serialize access during mutations.
49
+ The library resolves identities only; it does not track Bluetooth addresses or
50
+ presence, and a match does not prove freshness or proximity.
51
+
52
+ ## Development
53
+
54
+ ```sh
55
+ python -m pip install -e '.[dev]'
56
+ python tools/check_package.py
57
+ ```
58
+
59
+ Runs tests, code checks, and package validation.
60
+
61
+ ## Acknowledgements
62
+
63
+ Based on [Security and Privacy Analysis of Tile's Location Tracking Protocol](https://www.usenix.org/conference/usenixsecurity26/presentation/kumar-akshaya)
64
+ by Akshaya Kumar, Anna Raymaker, and Michael A. Specter (USENIX Security 2026).
65
+
66
+ Unofficial; not affiliated with Tile or Life360.
67
+ Licensed under the [MIT License](LICENSE).
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tile-identity-resolver"
7
+ version = "0.1.0"
8
+ description = "Resolve Tile identities from FEED service data without Bluetooth dependencies"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = []
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Operating System :: OS Independent",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/kbck/tile-identity-resolver"
23
+ Repository = "https://github.com/kbck/tile-identity-resolver"
24
+ Issues = "https://github.com/kbck/tile-identity-resolver/issues"
25
+
26
+ [project.optional-dependencies]
27
+ test = ["pytest>=8,<9"]
28
+ dev = [
29
+ "pytest>=8,<9",
30
+ "ruff>=0.11,<1",
31
+ "build>=1,<2",
32
+ "mypy>=1.15,<3",
33
+ "twine>=6,<7",
34
+ "check-wheel-contents>=0.6,<1",
35
+ ]
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.setuptools.package-data]
41
+ tile_identity_resolver = ["py.typed"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+ pythonpath = ["src"]
46
+
47
+ [tool.ruff]
48
+ target-version = "py310"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E4", "E7", "E9", "F", "I"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Resolve configured Tiles from raw FEED service-data bytes."""
2
+
3
+ from .models import Tile, TileInfo
4
+ from .resolver import TileResolver
5
+
6
+ __all__ = ["Tile", "TileInfo", "TileResolver"]
@@ -0,0 +1,50 @@
1
+ """Tile credentials and metadata decoded from a matching payload."""
2
+
3
+ import base64
4
+ from dataclasses import dataclass, field
5
+
6
+
7
+ def _to_bytes(value: str | bytes) -> bytes:
8
+ """Accept raw bytes or decode hexadecimal or padded Base64 text."""
9
+ if isinstance(value, bytes):
10
+ return value
11
+ if not isinstance(value, str):
12
+ raise ValueError("Expected raw bytes, hexadecimal, or Base64 text")
13
+ value = value.strip()
14
+ if value.endswith("="):
15
+ return base64.b64decode(value, validate=True)
16
+ return bytes.fromhex(value)
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Tile:
21
+ """Immutable Tile credentials stored as text.
22
+
23
+ The ID is lowercase hex; the key is hex or padded Base64.
24
+ """
25
+
26
+ tile_id: str
27
+ auth_key: str = field(repr=False)
28
+
29
+ def __post_init__(self) -> None:
30
+ tile_id = _to_bytes(self.tile_id)
31
+ if len(tile_id) != 8 or tile_id.hex() != self.tile_id:
32
+ raise ValueError("Tile ID must be 16 lowercase hexadecimal digits")
33
+ if (
34
+ not isinstance(self.auth_key, str)
35
+ or len(_to_bytes(self.auth_key)) != 16
36
+ ):
37
+ raise ValueError("Auth key must decode to sixteen bytes")
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class TileInfo:
41
+ """A registered Tile and metadata from one matching FEED payload.
42
+
43
+ A match does not establish freshness, proximity, or availability.
44
+ Flags are exposed verbatim; their meaning is not interpreted here.
45
+ """
46
+
47
+ tile: Tile
48
+ counter: int
49
+ version: int
50
+ flags: int
@@ -0,0 +1,110 @@
1
+ """Register Tile identities and resolve version-2 FEED payloads."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ from collections.abc import Iterable
6
+
7
+ from .models import Tile, TileInfo, _to_bytes
8
+
9
+
10
+ def _generate_private_ids(tile: Tile) -> dict[bytes, int]:
11
+ tile_id = bytes.fromhex(tile.tile_id)
12
+ auth_key = _to_bytes(tile.auth_key)
13
+ identity_message = tile_id + b"identity" + bytes(16)
14
+ identity_key = hmac.digest(auth_key, identity_message, hashlib.sha256)[:16]
15
+
16
+ private_ids = {}
17
+ for counter in range(8640):
18
+ counter_message = counter.to_bytes(4, "little") + bytes(28)
19
+ private_id = hmac.digest(
20
+ identity_key, counter_message, hashlib.sha256
21
+ )[:8]
22
+ private_ids[private_id] = counter
23
+ return private_ids
24
+
25
+
26
+ class TileResolver:
27
+ """Resolve payloads against any number of registered Tiles.
28
+
29
+ Each resolver prepares and owns candidates for its registered Tiles.
30
+ Calls are synchronous; callers must serialize concurrent mutations.
31
+ """
32
+
33
+ def __init__(self, tiles: Iterable[Tile] = ()) -> None:
34
+ self._tiles: dict[str, Tile] = {}
35
+ self._private_ids: dict[str, list[bytes]] = {}
36
+ self._index: dict[
37
+ bytes, tuple[Tile, int] | dict[str, tuple[Tile, int]]
38
+ ] = {}
39
+ for tile in tiles:
40
+ self.add(tile)
41
+
42
+ @property
43
+ def tiles(self) -> tuple[Tile, ...]:
44
+ """Return a snapshot of Tiles in registration order."""
45
+ return tuple(self._tiles.values())
46
+
47
+ def add(self, tile: Tile) -> None:
48
+ """Register a Tile and prepare its candidate IDs.
49
+
50
+ Duplicate stable IDs raise ValueError. To change a key, remove
51
+ the existing Tile and add its replacement.
52
+ """
53
+ if not isinstance(tile, Tile):
54
+ raise TypeError("Expected a Tile")
55
+ if tile.tile_id in self._tiles:
56
+ raise ValueError("Tile ID is already registered")
57
+ private_ids = _generate_private_ids(tile)
58
+ self._tiles[tile.tile_id] = tile
59
+ self._private_ids[tile.tile_id] = list(private_ids)
60
+ for private_id, counter in private_ids.items():
61
+ match = (tile, counter)
62
+ owners = self._index.get(private_id)
63
+ if owners is None:
64
+ self._index[private_id] = match
65
+ elif isinstance(owners, tuple):
66
+ # Allocate an owners dictionary only for collisions.
67
+ self._index[private_id] = {
68
+ owners[0].tile_id: owners,
69
+ tile.tile_id: match,
70
+ }
71
+ else:
72
+ owners[tile.tile_id] = match
73
+
74
+ def remove(self, tile_id: str) -> None:
75
+ """Remove a Tile by hex ID; raise KeyError if it is unknown."""
76
+ del self._tiles[tile_id]
77
+ private_ids = self._private_ids.pop(tile_id)
78
+ for private_id in private_ids:
79
+ owners = self._index[private_id]
80
+ if isinstance(owners, tuple):
81
+ del self._index[private_id]
82
+ else:
83
+ del owners[tile_id]
84
+ if len(owners) == 1:
85
+ self._index[private_id] = next(iter(owners.values()))
86
+
87
+ def resolve(
88
+ self, payload: bytes | bytearray | memoryview
89
+ ) -> TileInfo | None:
90
+ """Resolve FEED data without UUID or advertising headers.
91
+
92
+ Return None for short, unsupported, unknown, or ambiguous data.
93
+ Allow trailing bytes. Other input types raise TypeError.
94
+ No state is updated by resolving a payload.
95
+ """
96
+ if not isinstance(payload, (bytes, bytearray, memoryview)):
97
+ raise TypeError("Payload must be bytes, bytearray, or memoryview")
98
+ payload = bytes(payload)
99
+ if len(payload) < 10 or payload[0] != 2:
100
+ return None
101
+ match = self._index.get(payload[2:10])
102
+ if not isinstance(match, tuple):
103
+ return None
104
+ tile, counter = match
105
+ return TileInfo(
106
+ tile=tile,
107
+ counter=counter,
108
+ version=payload[0],
109
+ flags=payload[1],
110
+ )
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: tile-identity-resolver
3
+ Version: 0.1.0
4
+ Summary: Resolve Tile identities from FEED service data without Bluetooth dependencies
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/kbck/tile-identity-resolver
7
+ Project-URL: Repository, https://github.com/kbck/tile-identity-resolver
8
+ Project-URL: Issues, https://github.com/kbck/tile-identity-resolver/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest<9,>=8; extra == "test"
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest<9,>=8; extra == "dev"
20
+ Requires-Dist: ruff<1,>=0.11; extra == "dev"
21
+ Requires-Dist: build<2,>=1; extra == "dev"
22
+ Requires-Dist: mypy<3,>=1.15; extra == "dev"
23
+ Requires-Dist: twine<7,>=6; extra == "dev"
24
+ Requires-Dist: check-wheel-contents<1,>=0.6; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # Tile Identity Resolver
28
+
29
+ A dependency-free Python library for identifying registered Tile trackers from
30
+ version-2 FEED service data. Requires Python 3.10 or newer.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ python -m pip install tile-identity-resolver
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from tile_identity_resolver import Tile, TileResolver
42
+
43
+ # Replace these example credentials with your Tile's ID and auth key.
44
+ tile = Tile(
45
+ tile_id="0011223344556677",
46
+ auth_key="AAECAwQFBgcICQoLDA0ODw==",
47
+ )
48
+ resolver = TileResolver([tile])
49
+
50
+ # Pass the raw service-data value for UUID 0000feed-0000-1000-8000-00805f9b34fb.
51
+ def handle_feed_payload(payload: bytes) -> None:
52
+ info = resolver.resolve(payload)
53
+ if info is not None:
54
+ print(info.tile.tile_id, info.counter, info.version, info.flags)
55
+ ```
56
+
57
+ Tile IDs are eight-byte lowercase hex strings. Auth keys are sixteen-byte hex
58
+ or padded Base64 strings. Invalid credentials raise `ValueError`.
59
+
60
+ ## API
61
+
62
+ | API | Behavior |
63
+ | --- | --- |
64
+ | `TileResolver(tiles=())` | Register one or more Tiles |
65
+ | `resolver.add(tile)` | Register a Tile; duplicate IDs raise `ValueError` |
66
+ | `resolver.remove(tile_id)` | Remove a Tile; missing IDs raise `KeyError` |
67
+ | `resolver.tiles` | Immutable snapshot of registered Tiles |
68
+ | `resolver.resolve(payload)` | Return `TileInfo` for an unambiguous match, otherwise `None` |
69
+
70
+ `TileInfo` contains the registered `tile`, `counter`, `version`, and `flags`.
71
+ Remove and re-add a Tile to replace its key.
72
+
73
+ Registration precomputes private IDs and uses memory per Tile. In async apps,
74
+ prepare the resolver in a worker thread and serialize access during mutations.
75
+ The library resolves identities only; it does not track Bluetooth addresses or
76
+ presence, and a match does not prove freshness or proximity.
77
+
78
+ ## Development
79
+
80
+ ```sh
81
+ python -m pip install -e '.[dev]'
82
+ python tools/check_package.py
83
+ ```
84
+
85
+ Runs tests, code checks, and package validation.
86
+
87
+ ## Acknowledgements
88
+
89
+ Based on [Security and Privacy Analysis of Tile's Location Tracking Protocol](https://www.usenix.org/conference/usenixsecurity26/presentation/kumar-akshaya)
90
+ by Akshaya Kumar, Anna Raymaker, and Michael A. Specter (USENIX Security 2026).
91
+
92
+ Unofficial; not affiliated with Tile or Life360.
93
+ Licensed under the [MIT License](LICENSE).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/tile_identity_resolver/__init__.py
5
+ src/tile_identity_resolver/models.py
6
+ src/tile_identity_resolver/py.typed
7
+ src/tile_identity_resolver/resolver.py
8
+ src/tile_identity_resolver.egg-info/PKG-INFO
9
+ src/tile_identity_resolver.egg-info/SOURCES.txt
10
+ src/tile_identity_resolver.egg-info/dependency_links.txt
11
+ src/tile_identity_resolver.egg-info/requires.txt
12
+ src/tile_identity_resolver.egg-info/top_level.txt
13
+ tests/test_resolver.py
@@ -0,0 +1,11 @@
1
+
2
+ [dev]
3
+ pytest<9,>=8
4
+ ruff<1,>=0.11
5
+ build<2,>=1
6
+ mypy<3,>=1.15
7
+ twine<7,>=6
8
+ check-wheel-contents<1,>=0.6
9
+
10
+ [test]
11
+ pytest<9,>=8
@@ -0,0 +1,277 @@
1
+ """Test protocol derivation, matching, and registration lifecycle."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import hmac
6
+ from dataclasses import FrozenInstanceError
7
+
8
+ import pytest
9
+
10
+ from tile_identity_resolver import Tile, TileInfo, TileResolver
11
+ from tile_identity_resolver import resolver as implementation
12
+
13
+ TILE_ID = "0011223344556677"
14
+ OTHER_ID = "8899aabbccddeeff"
15
+ KEY = base64.b64encode(bytes(range(16))).decode()
16
+ OTHER_KEY = base64.b64encode(bytes(reversed(range(16)))).decode()
17
+
18
+
19
+ def payload_for(tile: Tile, counter: int, flags: int = 0) -> bytes:
20
+ """Construct a payload using explicit protocol message layouts."""
21
+ key = base64.b64decode(tile.auth_key)
22
+ seed = hmac.new(
23
+ key,
24
+ bytes.fromhex(tile.tile_id) + b"identity" + bytes(16),
25
+ hashlib.sha256,
26
+ ).digest()[:16]
27
+ identity = hmac.new(
28
+ seed, counter.to_bytes(4, "little") + bytes(28), hashlib.sha256
29
+ ).digest()[:8]
30
+ return bytes([2, flags]) + identity
31
+
32
+
33
+ @pytest.fixture
34
+ def tiles():
35
+ return (
36
+ Tile(TILE_ID, KEY),
37
+ Tile(OTHER_ID, OTHER_KEY),
38
+ )
39
+
40
+
41
+ @pytest.mark.parametrize(
42
+ "tile_id",
43
+ [
44
+ None, bytes(8), bytearray(8), "", "xyz", "00", "00" * 9,
45
+ OTHER_ID.upper(), " " + TILE_ID,
46
+ ],
47
+ )
48
+ def test_invalid_tile_id(tile_id):
49
+ with pytest.raises(ValueError):
50
+ Tile(tile_id, KEY)
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "auth_key",
55
+ [
56
+ None, bytes(16), bytearray(16), "bad-key", "", "\u2603", "====",
57
+ base64.b64encode(bytes(15)).decode(),
58
+ base64.b64encode(bytes(17)).decode(),
59
+ ],
60
+ )
61
+ def test_invalid_key_is_not_echoed(auth_key):
62
+ with pytest.raises(ValueError) as caught:
63
+ Tile(TILE_ID, auth_key)
64
+ if isinstance(auth_key, str) and auth_key:
65
+ assert auth_key not in str(caught.value)
66
+
67
+
68
+ @pytest.mark.parametrize(
69
+ "auth_key",
70
+ [KEY, " " + KEY + " ", KEY[:-3] + "x==", bytes(range(16)).hex()],
71
+ )
72
+ def test_supported_key_formats(auth_key):
73
+ tile = Tile(TILE_ID, auth_key)
74
+ assert tile.auth_key == auth_key
75
+ reference = Tile(TILE_ID, KEY)
76
+ result = TileResolver([tile]).resolve(payload_for(reference, 1))
77
+ assert result == TileInfo(tile, 1, 2, 0)
78
+
79
+
80
+ def test_multiple_tiles_return_registered_objects_and_metadata(tiles):
81
+ keys, wallet = tiles
82
+ resolver = TileResolver(tiles)
83
+ assert resolver.tiles == tiles
84
+ keys_info = resolver.resolve(payload_for(keys, 1093, flags=255))
85
+ wallet_info = resolver.resolve(payload_for(wallet, 256, flags=7))
86
+ assert keys_info == TileInfo(keys, 1093, 2, 255)
87
+ assert wallet_info == TileInfo(wallet, 256, 2, 7)
88
+ assert keys_info.tile is keys
89
+ assert wallet_info.tile is wallet
90
+
91
+
92
+ def test_results_are_immutable_snapshots(tiles):
93
+ tile = tiles[0]
94
+ resolver = TileResolver([tile])
95
+ info = resolver.resolve(payload_for(tile, 1))
96
+ resolver.resolve(payload_for(tile, 2))
97
+ assert info.counter == 1
98
+ with pytest.raises(FrozenInstanceError):
99
+ info.counter = 5
100
+
101
+
102
+ def test_tiles_are_immutable(tiles):
103
+ tile = tiles[0]
104
+ with pytest.raises(FrozenInstanceError):
105
+ tile.auth_key = OTHER_KEY
106
+ with pytest.raises(FrozenInstanceError):
107
+ tile.tile_id = OTHER_ID
108
+
109
+
110
+ def test_auth_key_is_hidden_from_repr(tiles):
111
+ tile = tiles[0]
112
+ assert KEY not in repr(tile)
113
+ assert KEY not in repr(TileInfo(tile, 1, 2, 0))
114
+
115
+
116
+ @pytest.mark.parametrize("counter", [0, 1, 255, 256, 8639, 8640])
117
+ def test_counter_boundaries(tiles, counter):
118
+ tile = tiles[0]
119
+ result = TileResolver([tile]).resolve(payload_for(tile, counter))
120
+ if counter == 8640:
121
+ assert result is None
122
+ else:
123
+ assert result.counter == counter
124
+
125
+
126
+ @pytest.mark.parametrize("factory", [bytes, bytearray, memoryview])
127
+ def test_bytes_like_input_and_trailing_data(tiles, factory):
128
+ tile = tiles[0]
129
+ payload = factory(payload_for(tile, 1) + b"extra")
130
+ result = TileResolver([tile]).resolve(payload)
131
+ assert result == TileInfo(tile, 1, 2, 0)
132
+
133
+
134
+ @pytest.mark.parametrize(
135
+ "payload",
136
+ [
137
+ b"",
138
+ b"\x02",
139
+ b"\x02\xff1234567",
140
+ b"\x01\x0012345678",
141
+ b"\x02\x00unknown!",
142
+ ],
143
+ )
144
+ def test_malformed_unsupported_and_unknown_payloads(tiles, payload):
145
+ assert TileResolver(tiles).resolve(payload) is None
146
+
147
+
148
+ @pytest.mark.parametrize("payload", [None, "0200", 123, [2, 0]])
149
+ def test_non_bytes_input_raises_type_error(payload):
150
+ with pytest.raises(TypeError, match="Payload must be"):
151
+ TileResolver().resolve(payload)
152
+
153
+
154
+ def test_duplicate_ids(tiles):
155
+ resolver = TileResolver(tiles)
156
+ with pytest.raises(ValueError, match="already registered"):
157
+ resolver.add(Tile(OTHER_ID, KEY))
158
+ assert resolver.tiles == tiles
159
+ with pytest.raises(TypeError, match="Expected a Tile"):
160
+ resolver.add(TILE_ID)
161
+ with pytest.raises(ValueError, match="already registered"):
162
+ TileResolver([tiles[0], tiles[0]])
163
+
164
+
165
+ def test_remove_and_replace_key(tiles):
166
+ tile, other = tiles
167
+ resolver = TileResolver(tiles)
168
+ old_payload = payload_for(tile, 1)
169
+ resolver.remove(TILE_ID)
170
+ assert resolver.resolve(old_payload) is None
171
+ assert resolver.resolve(payload_for(other, 1)).tile is other
172
+ replacement = Tile(TILE_ID, OTHER_KEY)
173
+ resolver.add(replacement)
174
+ assert resolver.resolve(old_payload) is None
175
+ assert resolver.resolve(payload_for(replacement, 1)).tile is replacement
176
+ resolver.remove(OTHER_ID)
177
+ resolver.remove(TILE_ID)
178
+ assert resolver.tiles == ()
179
+ assert resolver.resolve(payload_for(replacement, 1)) is None
180
+ with pytest.raises(KeyError):
181
+ resolver.remove(TILE_ID)
182
+ with pytest.raises(KeyError):
183
+ resolver.remove("invalid")
184
+
185
+
186
+ def test_collisions_fail_closed_and_removal_restores_unique_match(monkeypatch):
187
+ def shared_candidates(tile):
188
+ counter = 1 if tile.tile_id == TILE_ID else 2
189
+ return {b"sharedid": counter}
190
+
191
+ monkeypatch.setattr(
192
+ implementation, "_generate_private_ids", shared_candidates
193
+ )
194
+ keys = Tile(TILE_ID, KEY)
195
+ wallet = Tile(OTHER_ID, OTHER_KEY)
196
+ resolver = TileResolver([keys])
197
+ payload = b"\x02\xffsharedid"
198
+ assert resolver.resolve(payload) == TileInfo(keys, 1, 2, 255)
199
+ resolver.add(wallet)
200
+ assert resolver.resolve(payload) is None
201
+ resolver.remove(TILE_ID)
202
+ assert resolver.resolve(payload) == TileInfo(wallet, 2, 2, 255)
203
+ resolver.remove(OTHER_ID)
204
+ assert resolver.resolve(payload) is None
205
+
206
+
207
+ @pytest.mark.parametrize("survivor", [0, 1, 2])
208
+ def test_three_way_collision_removal_and_reregistration(
209
+ monkeypatch, survivor
210
+ ):
211
+ registered = (
212
+ Tile(TILE_ID, KEY),
213
+ Tile(OTHER_ID, OTHER_KEY),
214
+ Tile("1122334455667788", KEY),
215
+ )
216
+
217
+ def candidates(tile):
218
+ return {
219
+ b"sharedid": registered.index(tile),
220
+ bytes.fromhex(tile.tile_id): 10,
221
+ }
222
+
223
+ monkeypatch.setattr(implementation, "_generate_private_ids", candidates)
224
+ resolver = TileResolver(registered)
225
+ shared_payload = b"\x02\x00sharedid"
226
+ assert resolver.resolve(shared_payload) is None
227
+ removed = [tile for i, tile in enumerate(registered) if i != survivor]
228
+ resolver.remove(removed[0].tile_id)
229
+ assert resolver.resolve(shared_payload) is None
230
+ resolver.remove(removed[1].tile_id)
231
+ expected = TileInfo(registered[survivor], survivor, 2, 0)
232
+ assert resolver.resolve(shared_payload) == expected
233
+ for tile in removed:
234
+ unique_payload = b"\x02\x00" + bytes.fromhex(tile.tile_id)
235
+ assert resolver.resolve(unique_payload) is None
236
+ resolver.add(removed[0])
237
+ assert resolver.resolve(shared_payload) is None
238
+ resolver.remove(removed[0].tile_id)
239
+ assert resolver.resolve(shared_payload) == expected
240
+ resolver.remove(registered[survivor].tile_id)
241
+ assert resolver.resolve(shared_payload) is None
242
+ assert resolver.tiles == ()
243
+
244
+
245
+ def test_tile_construction_does_not_prepare_candidates(monkeypatch):
246
+ def fail(tile):
247
+ pytest.fail("Tile construction must not generate private IDs")
248
+
249
+ monkeypatch.setattr(implementation, "_generate_private_ids", fail)
250
+ tile = Tile(TILE_ID, KEY)
251
+ assert tile.tile_id == TILE_ID
252
+
253
+
254
+ def test_resolve_does_not_repeat_preparation(tiles, monkeypatch):
255
+ tile = tiles[0]
256
+ resolver = TileResolver([tile])
257
+
258
+ def fail(tile):
259
+ pytest.fail("Resolving should use prepared IDs")
260
+
261
+ monkeypatch.setattr(implementation, "_generate_private_ids", fail)
262
+ assert resolver.resolve(payload_for(tile, 1)) == TileInfo(tile, 1, 2, 0)
263
+
264
+
265
+ def test_preparation_failure_leaves_registration_unchanged(tiles, monkeypatch):
266
+ tile, other = tiles
267
+ resolver = TileResolver([tile])
268
+
269
+ def fail(tile):
270
+ raise RuntimeError("Preparation failed")
271
+
272
+ monkeypatch.setattr(implementation, "_generate_private_ids", fail)
273
+ with pytest.raises(RuntimeError, match="Preparation failed"):
274
+ resolver.add(other)
275
+ assert resolver.tiles == (tile,)
276
+ assert resolver.resolve(payload_for(tile, 1)).tile is tile
277
+ assert resolver.resolve(payload_for(other, 1)) is None