offline-protocol-sdk 0.28.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- offline_protocol_sdk/__init__.py +22 -0
- offline_protocol_sdk/_callback_reentrancy.py +64 -0
- offline_protocol_sdk/address_declaration.py +207 -0
- offline_protocol_sdk/ble_manager.py +595 -0
- offline_protocol_sdk/ble_peripheral.py +673 -0
- offline_protocol_sdk/dnssd_bridge.py +614 -0
- offline_protocol_sdk/gateway_attach_policy.py +437 -0
- offline_protocol_sdk/gateway_manager.py +1217 -0
- offline_protocol_sdk/gateway_verdict_tracker.py +97 -0
- offline_protocol_sdk/internet_manager.py +1444 -0
- offline_protocol_sdk/legacy_store_adoption.py +184 -0
- offline_protocol_sdk/local_api/__init__.py +34 -0
- offline_protocol_sdk/local_api/authz.py +180 -0
- offline_protocol_sdk/local_api/cli.py +171 -0
- offline_protocol_sdk/local_api/codec.py +210 -0
- offline_protocol_sdk/local_api/dispatch.py +537 -0
- offline_protocol_sdk/local_api/mux.py +239 -0
- offline_protocol_sdk/local_api/server.py +546 -0
- offline_protocol_sdk/local_api/session.py +86 -0
- offline_protocol_sdk/local_api/table.py +849 -0
- offline_protocol_sdk/offline_protocol.py +13508 -0
- offline_protocol_sdk/peer_stream_manager.py +1303 -0
- offline_protocol_sdk/presence_watch_policy.py +102 -0
- offline_protocol_sdk/protocol_manager.py +1108 -0
- offline_protocol_sdk/relay_answer_prefixes.py +61 -0
- offline_protocol_sdk/secure_storage.py +551 -0
- offline_protocol_sdk/services.py +195 -0
- offline_protocol_sdk/state_storage.py +452 -0
- offline_protocol_sdk/storage_namespace.py +33 -0
- offline_protocol_sdk/transport_manager.py +138 -0
- offline_protocol_sdk/uniffi.dll +0 -0
- offline_protocol_sdk-0.28.0.dist-info/METADATA +519 -0
- offline_protocol_sdk-0.28.0.dist-info/RECORD +40 -0
- offline_protocol_sdk-0.28.0.dist-info/WHEEL +5 -0
- offline_protocol_sdk-0.28.0.dist-info/entry_points.txt +2 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/EXPORT.md +68 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE +661 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE-COMMERCIAL.md +89 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +6645 -0
- offline_protocol_sdk-0.28.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Which synthesized relay frames must reach the core unattributed.
|
|
2
|
+
|
|
3
|
+
A port of ``RelayAnswerPrefixes.swift`` and ``RelayAnswerPrefixes.kt``.
|
|
4
|
+
|
|
5
|
+
These are the prefixes the **relay server** originates. The bridge
|
|
6
|
+
synthesizes a frame from a WebSocket answer rather than receiving one from a
|
|
7
|
+
peer, so no key exists to sign it. The core exempts exactly these from its
|
|
8
|
+
control-frame signature gate (``RELAY_ANSWER_PREFIXES`` in
|
|
9
|
+
``crates/offline-protocol/src/protocol/prefixes.rs``), and the four copies
|
|
10
|
+
must agree: the core, the Swift bridge, the Kotlin bridge and this module.
|
|
11
|
+
|
|
12
|
+
Why attribution breaks them: the core's exemption is narrower than the
|
|
13
|
+
prefix. It also requires the frame to carry **no transport peer identity**,
|
|
14
|
+
which is what a locally synthesized answer looks like. Passing a non-empty
|
|
15
|
+
``sender_id`` to ``internet_message_received`` sets that identity, so the
|
|
16
|
+
frame stops looking synthesized and is dropped as unsigned. The caller sees a
|
|
17
|
+
successful inject and the answer never takes effect. That narrowness is doing
|
|
18
|
+
real work and must not be widened to close this: without it, any peer able to
|
|
19
|
+
address us through the relay could inject unsigned group state.
|
|
20
|
+
|
|
21
|
+
``__GROUP_MSG__`` is **not** here. It is a data-plane prefix, never
|
|
22
|
+
signature-gated (MLS authenticates it afterwards), so it keeps its
|
|
23
|
+
attribution and remains the reachability signal for a relayed sender.
|
|
24
|
+
|
|
25
|
+
``test_relay_answer_prefixes.py`` pins the set as literals (contract C5 in
|
|
26
|
+
``docs/bridges/README.md``). A test that recomputed it from this constant
|
|
27
|
+
would agree with any edit, which is the failure it exists to catch.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
RELAY_ANSWER_PREFIXES: frozenset[str] = frozenset(
|
|
33
|
+
{
|
|
34
|
+
"__GROUP_CREATED__",
|
|
35
|
+
"__GROUP_MEMBER_ADDED__",
|
|
36
|
+
"__GROUP_MEMBER_REMOVED__",
|
|
37
|
+
"__GROUP_INFO__",
|
|
38
|
+
"__USER_GROUPS__",
|
|
39
|
+
"__GROUP_ERROR__",
|
|
40
|
+
}
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def is_relay_answer(prefix: str) -> bool:
|
|
45
|
+
"""Whether ``prefix`` names a relay answer that must be injected unattributed.
|
|
46
|
+
|
|
47
|
+
Matched whole, not as a prefix of a prefix: whether a content string that
|
|
48
|
+
starts with an exempt prefix is admitted is decided in the core, against
|
|
49
|
+
the frame's transport and attribution.
|
|
50
|
+
"""
|
|
51
|
+
return prefix in RELAY_ANSWER_PREFIXES
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def attributable_actor(prefix: str, actor: str | None) -> str | None:
|
|
55
|
+
"""The actor a synthesized frame may carry: ``None`` for a relay answer.
|
|
56
|
+
|
|
57
|
+
Enforced here rather than trusted to each call site. The rule comes from
|
|
58
|
+
a constant in the Rust core, and a new answer injected with an actor is
|
|
59
|
+
dropped as unsigned with no error anywhere.
|
|
60
|
+
"""
|
|
61
|
+
return None if is_relay_answer(prefix) else actor
|
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""Cross-platform secure storage for MLS key material.
|
|
2
|
+
|
|
3
|
+
Uses the `keyring` library which delegates to platform-native credential stores:
|
|
4
|
+
- macOS: Keychain
|
|
5
|
+
- Linux: Secret Service (GNOME Keyring / KWallet)
|
|
6
|
+
- Windows: Windows Credential Locker
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import threading
|
|
15
|
+
|
|
16
|
+
import keyring
|
|
17
|
+
import keyring.backends.chainer
|
|
18
|
+
|
|
19
|
+
from . import legacy_store_adoption
|
|
20
|
+
from .offline_protocol import MlsStorageError, MlsStorageProvider
|
|
21
|
+
from .storage_namespace import require_account_storage_namespace
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
#: keyring backends that cannot hold a secret: every call fails, or nothing is kept.
|
|
26
|
+
_INSECURE_KEYRING_MODULES = frozenset({"keyring.backends.fail", "keyring.backends.null"})
|
|
27
|
+
|
|
28
|
+
# Base service name used for keyring entries
|
|
29
|
+
_DEFAULT_SERVICE = "offline-protocol-mls-v2"
|
|
30
|
+
|
|
31
|
+
# Service the pre-namespace store used, adopted on upgrade so an existing
|
|
32
|
+
# install keeps its MLS identity (see ``legacy_store_adoption``).
|
|
33
|
+
_LEGACY_SERVICE = "offline-protocol-mls"
|
|
34
|
+
|
|
35
|
+
# Prefix for index entries that track key IDs per key_type
|
|
36
|
+
_INDEX_PREFIX = "index:"
|
|
37
|
+
|
|
38
|
+
#: Value written for a tombstone. Only its *presence* is the signal — nothing
|
|
39
|
+
#: reads the bytes back — so it stays one byte rather than restating the key.
|
|
40
|
+
_TOMBSTONE_VALUE = b"\x01"
|
|
41
|
+
|
|
42
|
+
#: Serialises legacy-store adoption across *every* provider in the process.
|
|
43
|
+
#:
|
|
44
|
+
#: Deliberately module-level rather than the per-instance ``self._lock``: two
|
|
45
|
+
#: accounts adopting concurrently are two ``SecureStorage`` objects, so an
|
|
46
|
+
#: instance lock cannot order them by construction. See
|
|
47
|
+
#: :meth:`SecureStorage._resolve_legacy_adoption`.
|
|
48
|
+
_ADOPTION_LOCK = threading.Lock()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SecureStorage(MlsStorageProvider):
|
|
52
|
+
"""MlsStorageProvider backed by platform-native credential storage.
|
|
53
|
+
|
|
54
|
+
Thread-safe: all mutating operations are serialised with a lock to keep
|
|
55
|
+
the per-key_type index consistent (same approach as Android's
|
|
56
|
+
``MlsSecureStorage.kt``).
|
|
57
|
+
|
|
58
|
+
Important: keep a reference to this object alive for the entire lifetime
|
|
59
|
+
of the ``OfflineProtocol`` instance — if it is garbage-collected the
|
|
60
|
+
callback pointers on the Rust side become dangling.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
service: str = _DEFAULT_SERVICE,
|
|
66
|
+
*,
|
|
67
|
+
namespace: str | None = None,
|
|
68
|
+
adopt_legacy_store: bool = True,
|
|
69
|
+
) -> None:
|
|
70
|
+
if namespace is not None:
|
|
71
|
+
require_account_storage_namespace(namespace)
|
|
72
|
+
self._service = f"{service}:{namespace}" if namespace is not None else service
|
|
73
|
+
self._lock = threading.RLock()
|
|
74
|
+
|
|
75
|
+
# The legacy store predates namespacing and predates the "-v2" suffix,
|
|
76
|
+
# so it is only ever the default service under its old name.
|
|
77
|
+
self._legacy_service = (
|
|
78
|
+
_LEGACY_SERVICE
|
|
79
|
+
if adopt_legacy_store and service == _DEFAULT_SERVICE and namespace is not None
|
|
80
|
+
else None
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# Adoption records its claim under the account namespace, so a store
|
|
84
|
+
# built without one cannot participate — and on the default service
|
|
85
|
+
# that means an upgraded install silently mints a fresh MLS identity,
|
|
86
|
+
# abandoning every session, group, and TOFU pin it had. Say so: every
|
|
87
|
+
# other platform surfaces the analogous case as an error diagnostic.
|
|
88
|
+
# ``ProtocolManager`` supplies the namespace; this fires for callers
|
|
89
|
+
# that construct their own provider.
|
|
90
|
+
if adopt_legacy_store and service == _DEFAULT_SERVICE and namespace is None:
|
|
91
|
+
logger.warning(
|
|
92
|
+
"SecureStorage built without an account namespace: the "
|
|
93
|
+
"pre-namespace store cannot be adopted, so an upgraded install "
|
|
94
|
+
"starts from a fresh MLS identity and cannot decrypt its old "
|
|
95
|
+
"sessions. Its pre-split delivery state is unreachable too — "
|
|
96
|
+
"the SDK's protocol-state adoption sweep reads it through this "
|
|
97
|
+
"provider — so the install also comes up with an empty outbox "
|
|
98
|
+
"and an empty block list. Pass "
|
|
99
|
+
"namespace=account_storage_namespace(app_id, user_id), or let "
|
|
100
|
+
"ProtocolManager build the provider."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Warn if keyring resolved to a failing, null or plaintext backend: MLS
|
|
104
|
+
# key material would not be stored, or not stored securely. keyring's
|
|
105
|
+
# failing and null backends are both classes named plain ``Keyring``
|
|
106
|
+
# (in ``keyring.backends.fail`` and ``keyring.backends.null``), so the
|
|
107
|
+
# module is checked as well as the class name; the failing one is what a
|
|
108
|
+
# host without a secret service gets. When two or more backends are
|
|
109
|
+
# viable, keyring hands back a ``ChainerBackend`` instead, and writes go
|
|
110
|
+
# to the first backend it chains, so that is the backend judged. (A host
|
|
111
|
+
# whose only viable backend is ``keyrings.alt``'s plaintext file gets
|
|
112
|
+
# that backend directly, not a chain; the unwrap is for a chain that
|
|
113
|
+
# happens to rank an insecure backend first.)
|
|
114
|
+
try:
|
|
115
|
+
backend = keyring.get_keyring()
|
|
116
|
+
# A chain with nothing in it stores nothing, like the null backend.
|
|
117
|
+
empty_chain = False
|
|
118
|
+
if isinstance(backend, keyring.backends.chainer.ChainerBackend):
|
|
119
|
+
chained = backend.backends
|
|
120
|
+
empty_chain = not chained
|
|
121
|
+
if chained:
|
|
122
|
+
backend = chained[0]
|
|
123
|
+
backend_cls = type(backend)
|
|
124
|
+
backend_name = f"{backend_cls.__module__}.{backend_cls.__name__}"
|
|
125
|
+
if (
|
|
126
|
+
empty_chain
|
|
127
|
+
or backend_cls.__module__ in _INSECURE_KEYRING_MODULES
|
|
128
|
+
# keyring's own failing and null backends are caught by module
|
|
129
|
+
# above; the name markers catch third-party backends.
|
|
130
|
+
or "Fail" in backend_cls.__name__
|
|
131
|
+
or "Null" in backend_cls.__name__
|
|
132
|
+
or "PlaintextKeyring" in backend_cls.__name__
|
|
133
|
+
):
|
|
134
|
+
logger.warning(
|
|
135
|
+
"keyring backend is '%s': MLS keys will NOT be stored "
|
|
136
|
+
"securely. Install a platform secret service (e.g. "
|
|
137
|
+
"gnome-keyring, kwallet), or on a headless host pass "
|
|
138
|
+
"store_key or store_key_env to ProtocolManager to use the "
|
|
139
|
+
"built-in file stores.",
|
|
140
|
+
backend_name,
|
|
141
|
+
)
|
|
142
|
+
except Exception:
|
|
143
|
+
logger.debug("Could not inspect keyring backend", exc_info=True)
|
|
144
|
+
|
|
145
|
+
#: Outcome of the one-time legacy-store adoption, for the caller to
|
|
146
|
+
#: surface. A ``"conflict"`` in particular must not pass silently: this
|
|
147
|
+
#: account is starting from a fresh identity.
|
|
148
|
+
self.legacy_adoption = (
|
|
149
|
+
self._resolve_legacy_adoption(namespace)
|
|
150
|
+
if self._legacy_service is not None and namespace is not None
|
|
151
|
+
else legacy_store_adoption.NONE
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# -- MlsStorageProvider interface ----------------------------------------
|
|
155
|
+
|
|
156
|
+
def store(self, key_type: str, key_id: str, data: list[int]) -> None:
|
|
157
|
+
with self._lock:
|
|
158
|
+
self._store(self._service, key_type, key_id, bytes(data))
|
|
159
|
+
|
|
160
|
+
def load(self, key_type: str, key_id: str) -> list[int] | None:
|
|
161
|
+
"""Load one entry, falling through to the adopted legacy store on a miss.
|
|
162
|
+
|
|
163
|
+
Each primitive below takes ``self._lock``, but this *compound*
|
|
164
|
+
read-then-promote is not atomic against :meth:`delete`, and deliberately
|
|
165
|
+
so. Interleaved, they would resurrect key material: this method could
|
|
166
|
+
observe a miss in the namespaced store, read the legacy value, and then
|
|
167
|
+
promote it after a concurrent delete had already removed both copies —
|
|
168
|
+
defeating the very guarantee :meth:`delete` documents.
|
|
169
|
+
|
|
170
|
+
That is unreachable because the SDK is the only caller and serialises
|
|
171
|
+
every storage operation behind its own mutex: ``OfflineProtocol``'s
|
|
172
|
+
methods take ``&mut self`` and the UniFFI wrapper holds them under one
|
|
173
|
+
lock, so no two provider calls overlap. Widening the lock to cover the
|
|
174
|
+
whole compound operation would mean holding it across a keyring read on
|
|
175
|
+
every miss, which is the common path during an upgrade. If a second
|
|
176
|
+
caller is ever given this provider, that trade has to be revisited.
|
|
177
|
+
|
|
178
|
+
A tombstoned key reads as absent without consulting the legacy store at
|
|
179
|
+
all: its copy there outlived a delete, and promoting it would resurrect
|
|
180
|
+
key material the caller was told was gone.
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
if legacy_store_adoption.is_reserved_entry(key_type):
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
current = self._read(self._service, key_type, key_id)
|
|
187
|
+
if current is not None:
|
|
188
|
+
return list(current)
|
|
189
|
+
|
|
190
|
+
legacy = self._read_through_service(key_type)
|
|
191
|
+
if legacy is None:
|
|
192
|
+
return None
|
|
193
|
+
tombstone = self._tombstone_state(key_type, key_id)
|
|
194
|
+
if tombstone.suppresses_read_through:
|
|
195
|
+
if tombstone.allows_removal_retry:
|
|
196
|
+
# Opportunistic heal: the removal that failed may succeed now,
|
|
197
|
+
# which is the only thing that retires a tombstone. Gated on a
|
|
198
|
+
# *confirmed* tombstone — a read that merely failed must not
|
|
199
|
+
# delete a copy that may still be inheritable.
|
|
200
|
+
self._retry_tombstoned_removal(legacy, key_type, key_id)
|
|
201
|
+
return None
|
|
202
|
+
inherited = self._read(legacy, key_type, key_id)
|
|
203
|
+
if inherited is None:
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
# Best-effort promotion: a failed copy still returns the value, it just
|
|
207
|
+
# costs another read-through next launch.
|
|
208
|
+
with self._lock:
|
|
209
|
+
try:
|
|
210
|
+
self._store(self._service, key_type, key_id, inherited)
|
|
211
|
+
except Exception:
|
|
212
|
+
logger.warning(
|
|
213
|
+
"failed to promote inherited entry for %s", key_type, exc_info=True
|
|
214
|
+
)
|
|
215
|
+
return list(inherited)
|
|
216
|
+
|
|
217
|
+
def delete(self, key_type: str, key_id: str) -> None:
|
|
218
|
+
"""Delete one entry from the namespaced store and the legacy one.
|
|
219
|
+
|
|
220
|
+
A delete that left the legacy copy in place would let read-through
|
|
221
|
+
resurrect key material the caller believes is gone. When that removal
|
|
222
|
+
fails, the key is tombstoned rather than reported: see
|
|
223
|
+
``legacy_store_adoption.TOMBSTONE_KEY_TYPE`` for why this cannot be
|
|
224
|
+
signalled by raising. The delete has still done what it promised —
|
|
225
|
+
nothing will hand that key back — so it returns successfully.
|
|
226
|
+
|
|
227
|
+
Only a *double* fault raises: a legacy copy that will not delete and a
|
|
228
|
+
namespaced store that will not record the tombstone leaves no way to
|
|
229
|
+
keep the promise, and a store failing both is failing everything else
|
|
230
|
+
too.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
with self._lock:
|
|
234
|
+
self._remove(self._service, key_type, key_id)
|
|
235
|
+
legacy = self._read_through_service(key_type)
|
|
236
|
+
if legacy is None:
|
|
237
|
+
return
|
|
238
|
+
try:
|
|
239
|
+
self._remove(legacy, key_type, key_id)
|
|
240
|
+
except Exception as exc:
|
|
241
|
+
logger.warning(
|
|
242
|
+
"failed to delete inherited entry for %s; tombstoning it so "
|
|
243
|
+
"read-through cannot resurrect it",
|
|
244
|
+
key_type,
|
|
245
|
+
exc_info=True,
|
|
246
|
+
)
|
|
247
|
+
self._tombstone(key_type, key_id, exc)
|
|
248
|
+
return
|
|
249
|
+
self._clear_tombstone(key_type, key_id)
|
|
250
|
+
|
|
251
|
+
def list_keys(self, key_type: str) -> list[str]:
|
|
252
|
+
"""Return all key IDs stored under *key_type*.
|
|
253
|
+
|
|
254
|
+
``keyring`` does not natively support listing, so we maintain a
|
|
255
|
+
JSON-encoded index entry per key_type — the same strategy used by
|
|
256
|
+
the Android ``MlsSecureStorage`` (index prefix approach). The adopted
|
|
257
|
+
legacy store's index is unioned in, so a not-yet-promoted entry is
|
|
258
|
+
still discoverable — except where a tombstone says that entry is a
|
|
259
|
+
corpse, which must not be advertised as a key that can be loaded.
|
|
260
|
+
"""
|
|
261
|
+
if legacy_store_adoption.is_reserved_entry(key_type):
|
|
262
|
+
return []
|
|
263
|
+
with self._lock:
|
|
264
|
+
try:
|
|
265
|
+
keys = list(self._index_get(self._service, key_type))
|
|
266
|
+
legacy = self._read_through_service(key_type)
|
|
267
|
+
if legacy is not None:
|
|
268
|
+
for key in self._index_get(legacy, key_type):
|
|
269
|
+
if key in keys:
|
|
270
|
+
continue
|
|
271
|
+
if self._tombstone_state(
|
|
272
|
+
key_type, key
|
|
273
|
+
).suppresses_read_through:
|
|
274
|
+
continue
|
|
275
|
+
keys.append(key)
|
|
276
|
+
return keys
|
|
277
|
+
except Exception as exc:
|
|
278
|
+
raise MlsStorageError.LoadFailed(
|
|
279
|
+
f"keyring list_keys failed: {exc}"
|
|
280
|
+
) from exc
|
|
281
|
+
|
|
282
|
+
# -- tombstones ----------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def _tombstone(self, key_type: str, key_id: str, cause: Exception) -> None:
|
|
285
|
+
"""Record that a legacy copy survived its deletion.
|
|
286
|
+
|
|
287
|
+
*cause* is the removal failure this stands in for, folded into the
|
|
288
|
+
raised message so a double fault names both halves.
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
try:
|
|
292
|
+
self._store(
|
|
293
|
+
self._service,
|
|
294
|
+
legacy_store_adoption.TOMBSTONE_KEY_TYPE,
|
|
295
|
+
legacy_store_adoption.tombstone_key_id(key_type, key_id),
|
|
296
|
+
_TOMBSTONE_VALUE,
|
|
297
|
+
)
|
|
298
|
+
except Exception as exc:
|
|
299
|
+
raise MlsStorageError.DeleteFailed(
|
|
300
|
+
f"keyring delete left an inherited copy of {key_type} in place "
|
|
301
|
+
f"({cause}) and could not tombstone it: {exc}"
|
|
302
|
+
) from exc
|
|
303
|
+
|
|
304
|
+
def _tombstone_state(
|
|
305
|
+
self, key_type: str, key_id: str
|
|
306
|
+
) -> legacy_store_adoption.TombstoneState:
|
|
307
|
+
"""What the namespaced store says about this key's legacy copy.
|
|
308
|
+
|
|
309
|
+
A read that raises is ``UNREADABLE``, which fails closed as far as
|
|
310
|
+
*reading* goes: read-through cannot be proven safe, and suppressing a
|
|
311
|
+
legitimate inherited entry costs an identity rotation while resurrecting
|
|
312
|
+
a consumed key costs forward secrecy. It deliberately stops short of
|
|
313
|
+
authorising the removal retry — see
|
|
314
|
+
:class:`legacy_store_adoption.TombstoneState`. Near-unreachable in
|
|
315
|
+
practice: the namespaced read in :meth:`load` runs first against the
|
|
316
|
+
same store and would have raised.
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
try:
|
|
320
|
+
recorded = (
|
|
321
|
+
self._read(
|
|
322
|
+
self._service,
|
|
323
|
+
legacy_store_adoption.TOMBSTONE_KEY_TYPE,
|
|
324
|
+
legacy_store_adoption.tombstone_key_id(key_type, key_id),
|
|
325
|
+
)
|
|
326
|
+
is not None
|
|
327
|
+
)
|
|
328
|
+
except Exception:
|
|
329
|
+
logger.warning(
|
|
330
|
+
"could not read the tombstone for %s; suppressing read-through "
|
|
331
|
+
"without retiring the legacy copy",
|
|
332
|
+
key_type,
|
|
333
|
+
exc_info=True,
|
|
334
|
+
)
|
|
335
|
+
return legacy_store_adoption.TombstoneState.UNREADABLE
|
|
336
|
+
return (
|
|
337
|
+
legacy_store_adoption.TombstoneState.RECORDED
|
|
338
|
+
if recorded
|
|
339
|
+
else legacy_store_adoption.TombstoneState.ABSENT
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
def _retry_tombstoned_removal(
|
|
343
|
+
self, legacy: str, key_type: str, key_id: str
|
|
344
|
+
) -> None:
|
|
345
|
+
"""Best-effort retry of the legacy removal a tombstone stands in for."""
|
|
346
|
+
|
|
347
|
+
with self._lock:
|
|
348
|
+
try:
|
|
349
|
+
self._remove(legacy, key_type, key_id)
|
|
350
|
+
except Exception:
|
|
351
|
+
return
|
|
352
|
+
self._clear_tombstone(key_type, key_id)
|
|
353
|
+
|
|
354
|
+
def _clear_tombstone(self, key_type: str, key_id: str) -> None:
|
|
355
|
+
"""Retire a tombstone once the legacy copy is genuinely gone.
|
|
356
|
+
|
|
357
|
+
Best effort: a tombstone that outlives its corpse only costs the
|
|
358
|
+
inherited entry it suppresses, and there is nothing left to resurrect.
|
|
359
|
+
"""
|
|
360
|
+
|
|
361
|
+
try:
|
|
362
|
+
self._remove(
|
|
363
|
+
self._service,
|
|
364
|
+
legacy_store_adoption.TOMBSTONE_KEY_TYPE,
|
|
365
|
+
legacy_store_adoption.tombstone_key_id(key_type, key_id),
|
|
366
|
+
)
|
|
367
|
+
except Exception:
|
|
368
|
+
logger.debug(
|
|
369
|
+
"failed to clear the tombstone for %s", key_type, exc_info=True
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
# -- legacy adoption -----------------------------------------------------
|
|
373
|
+
|
|
374
|
+
def _resolve_legacy_adoption(self, namespace: str):
|
|
375
|
+
"""Resolve — and, when the legacy store is unclaimed, record — this
|
|
376
|
+
account's right to inherit it.
|
|
377
|
+
|
|
378
|
+
The whole probe → claim → read-back sequence runs under
|
|
379
|
+
``_ADOPTION_LOCK``, because reading it back is not on its own enough to
|
|
380
|
+
make inheritance exclusive. The read back closes a write that silently
|
|
381
|
+
failed, and a second account claiming between our probe and our write.
|
|
382
|
+
It does not close two accounts interleaving like this::
|
|
383
|
+
|
|
384
|
+
A._read_claim() -> None B._read_claim() -> None
|
|
385
|
+
A._store(nsA)
|
|
386
|
+
A._read_claim() -> nsA => adopt
|
|
387
|
+
B._store(nsB)
|
|
388
|
+
B._read_claim() -> nsB => adopt
|
|
389
|
+
|
|
390
|
+
Both adopt, both promote the same MLS signing identity, and each ends
|
|
391
|
+
up holding the other's sessions and group state — the outcome the claim
|
|
392
|
+
exists to prevent, arriving silently. The invariant is "at most one
|
|
393
|
+
account holds a verified claim", and an unsynchronised
|
|
394
|
+
read-modify-write does not provide it. The lock is module-level for the
|
|
395
|
+
same reason: two accounts on one device are two providers, so the
|
|
396
|
+
per-instance ``self._lock`` cannot order them.
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
assert self._legacy_service is not None
|
|
400
|
+
with _ADOPTION_LOCK:
|
|
401
|
+
return self._resolve_legacy_adoption_locked(namespace)
|
|
402
|
+
|
|
403
|
+
def _resolve_legacy_adoption_locked(self, namespace: str):
|
|
404
|
+
decision = legacy_store_adoption.decide(self._read_claim(), namespace)
|
|
405
|
+
|
|
406
|
+
if decision.kind != "adopt":
|
|
407
|
+
if decision.kind == "conflict":
|
|
408
|
+
logger.error(
|
|
409
|
+
"legacy secure store already belongs to another account; this "
|
|
410
|
+
"account starts from a fresh MLS identity and cannot decrypt "
|
|
411
|
+
"its old sessions."
|
|
412
|
+
)
|
|
413
|
+
return decision
|
|
414
|
+
|
|
415
|
+
# Read the claim back rather than assuming the write landed: a write
|
|
416
|
+
# that failed silently leaves the store looking unclaimed to the next
|
|
417
|
+
# account, which would then adopt the same MLS identity. See
|
|
418
|
+
# ``legacy_store_adoption.confirm_claim``.
|
|
419
|
+
try:
|
|
420
|
+
self._store(
|
|
421
|
+
self._legacy_service,
|
|
422
|
+
legacy_store_adoption.CLAIM_KEY_TYPE,
|
|
423
|
+
legacy_store_adoption.CLAIM_KEY_ID,
|
|
424
|
+
namespace.encode("utf-8"),
|
|
425
|
+
)
|
|
426
|
+
except Exception:
|
|
427
|
+
logger.warning("failed to claim the legacy secure store", exc_info=True)
|
|
428
|
+
confirmed = legacy_store_adoption.CLAIM_UNVERIFIED
|
|
429
|
+
else:
|
|
430
|
+
confirmed = legacy_store_adoption.confirm_claim(self._read_claim(), namespace)
|
|
431
|
+
|
|
432
|
+
if confirmed.kind == "adopt":
|
|
433
|
+
logger.info("adopting the pre-namespace secure store for this account")
|
|
434
|
+
elif confirmed.kind == "claim_unverified":
|
|
435
|
+
logger.error(
|
|
436
|
+
"could not record this account's claim on the legacy secure "
|
|
437
|
+
"store, so it was not adopted: another account could otherwise "
|
|
438
|
+
"inherit the same MLS identity. This account starts from a "
|
|
439
|
+
"fresh identity."
|
|
440
|
+
)
|
|
441
|
+
elif confirmed.kind == "conflict":
|
|
442
|
+
logger.error(
|
|
443
|
+
"legacy secure store was claimed by another account "
|
|
444
|
+
"concurrently; this account starts from a fresh MLS identity."
|
|
445
|
+
)
|
|
446
|
+
return confirmed
|
|
447
|
+
|
|
448
|
+
def _read_claim(self) -> str | None:
|
|
449
|
+
"""The claim recorded in the legacy store, or None when absent or
|
|
450
|
+
unreadable.
|
|
451
|
+
|
|
452
|
+
A failed read is deliberately not distinguished from an absent claim on
|
|
453
|
+
the way *in* (both mean "looks unclaimed") but is on the way back *out*,
|
|
454
|
+
where it means the claim is unproven.
|
|
455
|
+
"""
|
|
456
|
+
|
|
457
|
+
assert self._legacy_service is not None
|
|
458
|
+
try:
|
|
459
|
+
raw = self._read(
|
|
460
|
+
self._legacy_service,
|
|
461
|
+
legacy_store_adoption.CLAIM_KEY_TYPE,
|
|
462
|
+
legacy_store_adoption.CLAIM_KEY_ID,
|
|
463
|
+
)
|
|
464
|
+
except Exception:
|
|
465
|
+
logger.warning(
|
|
466
|
+
"legacy secure store claim could not be read", exc_info=True
|
|
467
|
+
)
|
|
468
|
+
return None
|
|
469
|
+
return raw.decode("utf-8", errors="replace") if raw is not None else None
|
|
470
|
+
|
|
471
|
+
def _read_through_service(self, key_type: str) -> str | None:
|
|
472
|
+
"""The legacy service to consult for *key_type*, or None when
|
|
473
|
+
read-through is off (no legacy store, another account claimed it, or
|
|
474
|
+
this account could not prove its own claim)."""
|
|
475
|
+
|
|
476
|
+
if self._legacy_service is None:
|
|
477
|
+
return None
|
|
478
|
+
if not self.legacy_adoption.allows_read_through:
|
|
479
|
+
return None
|
|
480
|
+
if legacy_store_adoption.is_reserved_entry(key_type):
|
|
481
|
+
return None
|
|
482
|
+
return self._legacy_service
|
|
483
|
+
|
|
484
|
+
# -- keyring primitives --------------------------------------------------
|
|
485
|
+
|
|
486
|
+
def _store(self, service: str, key_type: str, key_id: str, data: bytes) -> None:
|
|
487
|
+
try:
|
|
488
|
+
keyring.set_password(
|
|
489
|
+
service, _make_key(key_type, key_id), base64.b64encode(data).decode("ascii")
|
|
490
|
+
)
|
|
491
|
+
self._index_add(service, key_type, key_id)
|
|
492
|
+
except Exception as exc:
|
|
493
|
+
raise MlsStorageError.StoreFailed(f"keyring store failed: {exc}") from exc
|
|
494
|
+
|
|
495
|
+
def _read(self, service: str, key_type: str, key_id: str) -> bytes | None:
|
|
496
|
+
try:
|
|
497
|
+
encoded = keyring.get_password(service, _make_key(key_type, key_id))
|
|
498
|
+
if encoded is None:
|
|
499
|
+
return None
|
|
500
|
+
return base64.b64decode(encoded)
|
|
501
|
+
except Exception as exc:
|
|
502
|
+
raise MlsStorageError.LoadFailed(f"keyring load failed: {exc}") from exc
|
|
503
|
+
|
|
504
|
+
def _remove(self, service: str, key_type: str, key_id: str) -> None:
|
|
505
|
+
try:
|
|
506
|
+
keyring.delete_password(service, _make_key(key_type, key_id))
|
|
507
|
+
except keyring.errors.PasswordDeleteError:
|
|
508
|
+
pass # already gone — not an error (matches iOS Keychain behaviour)
|
|
509
|
+
except Exception as exc:
|
|
510
|
+
raise MlsStorageError.DeleteFailed(f"keyring delete failed: {exc}") from exc
|
|
511
|
+
|
|
512
|
+
self._index_remove(service, key_type, key_id)
|
|
513
|
+
|
|
514
|
+
# -- index helpers -------------------------------------------------------
|
|
515
|
+
|
|
516
|
+
def _index_key(self, key_type: str) -> str:
|
|
517
|
+
return f"{_INDEX_PREFIX}{key_type}"
|
|
518
|
+
|
|
519
|
+
def _index_get(self, service: str, key_type: str) -> list[str]:
|
|
520
|
+
raw = keyring.get_password(service, self._index_key(key_type))
|
|
521
|
+
if raw is None:
|
|
522
|
+
return []
|
|
523
|
+
return json.loads(raw)
|
|
524
|
+
|
|
525
|
+
def _index_add(self, service: str, key_type: str, key_id: str) -> None:
|
|
526
|
+
ids = set(self._index_get(service, key_type))
|
|
527
|
+
ids.add(key_id)
|
|
528
|
+
keyring.set_password(
|
|
529
|
+
service,
|
|
530
|
+
self._index_key(key_type),
|
|
531
|
+
json.dumps(sorted(ids)),
|
|
532
|
+
)
|
|
533
|
+
|
|
534
|
+
def _index_remove(self, service: str, key_type: str, key_id: str) -> None:
|
|
535
|
+
ids = set(self._index_get(service, key_type))
|
|
536
|
+
ids.discard(key_id)
|
|
537
|
+
if ids:
|
|
538
|
+
keyring.set_password(
|
|
539
|
+
service,
|
|
540
|
+
self._index_key(key_type),
|
|
541
|
+
json.dumps(sorted(ids)),
|
|
542
|
+
)
|
|
543
|
+
else:
|
|
544
|
+
try:
|
|
545
|
+
keyring.delete_password(service, self._index_key(key_type))
|
|
546
|
+
except keyring.errors.PasswordDeleteError:
|
|
547
|
+
pass
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _make_key(key_type: str, key_id: str) -> str:
|
|
551
|
+
return f"{key_type}:{key_id}"
|