chickinfry 0.5.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chickinfry/__init__.py +18 -0
- chickinfry/_auth_database.py +765 -0
- chickinfry/_conformance.py +208 -0
- chickinfry/_device.py +1405 -0
- chickinfry/_device_windows.py +250 -0
- chickinfry/_error_details.py +76 -0
- chickinfry/_http_common.py +165 -0
- chickinfry/_input.py +129 -0
- chickinfry/_origin.py +60 -0
- chickinfry/_password.py +38 -0
- chickinfry/_request_logs.py +66 -0
- chickinfry/_request_state.py +32 -0
- chickinfry/_sync_http.py +546 -0
- chickinfry/_sync_network.py +288 -0
- chickinfry/_workerd.py +731 -0
- chickinfry/auth.py +1227 -0
- chickinfry/errors.py +101 -0
- chickinfry/http.py +427 -0
- chickinfry/orm.py +506 -0
- chickinfry/postgres.py +281 -0
- chickinfry/py.typed +0 -0
- chickinfry/realtime.py +522 -0
- chickinfry/server.py +540 -0
- chickinfry/session.py +465 -0
- chickinfry/signup.py +134 -0
- chickinfry/wire.py +23 -0
- chickinfry-0.5.0.dev1.dist-info/METADATA +375 -0
- chickinfry-0.5.0.dev1.dist-info/RECORD +30 -0
- chickinfry-0.5.0.dev1.dist-info/WHEEL +4 -0
- chickinfry-0.5.0.dev1.dist-info/licenses/LICENSE +202 -0
chickinfry/_device.py
ADDED
|
@@ -0,0 +1,1405 @@
|
|
|
1
|
+
"""Private device bridge; generated wiring supplies trusted ownership context."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import stat
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Iterator, Mapping
|
|
9
|
+
from contextlib import ExitStack, contextmanager
|
|
10
|
+
from copy import deepcopy
|
|
11
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from hashlib import sha256
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Literal, cast
|
|
16
|
+
from uuid import uuid4
|
|
17
|
+
|
|
18
|
+
from .errors import ClientError, _local_error, _storage_error
|
|
19
|
+
from .session import (
|
|
20
|
+
MemoryStore,
|
|
21
|
+
SessionCredentials,
|
|
22
|
+
_commit_device_refresh,
|
|
23
|
+
_Failure,
|
|
24
|
+
_read_credentials,
|
|
25
|
+
_validate,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
30
|
+
result: dict[str, object] = {}
|
|
31
|
+
for key, value in pairs:
|
|
32
|
+
if key in result:
|
|
33
|
+
raise ValueError
|
|
34
|
+
result[key] = value
|
|
35
|
+
return result
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Attempt(dict[str, object]):
|
|
39
|
+
"""Validated auth-owned payload; no request bodies or passwords are accepted."""
|
|
40
|
+
|
|
41
|
+
def __repr__(self) -> str:
|
|
42
|
+
return "<signup attempt>"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
_HOST = sys.platform
|
|
46
|
+
_VERSION = 1
|
|
47
|
+
_MAX_BYTES = 8 * 1024
|
|
48
|
+
_MAX_ATTEMPTS = 3
|
|
49
|
+
_MAX_ID = 36
|
|
50
|
+
_MAX_EMAIL = 320
|
|
51
|
+
_MAX_SCREEN = 64
|
|
52
|
+
_MAX_INT = 2**63 - 1
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _time(value: str) -> int:
|
|
56
|
+
parsed = datetime.fromisoformat(value)
|
|
57
|
+
if parsed.tzinfo is None:
|
|
58
|
+
raise ValueError
|
|
59
|
+
delta = parsed - datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
60
|
+
micros = (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
|
|
61
|
+
if not -_MAX_INT - 1 <= micros <= _MAX_INT:
|
|
62
|
+
raise ValueError
|
|
63
|
+
return micros
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _native(credentials: SessionCredentials) -> None:
|
|
67
|
+
_validate(credentials)
|
|
68
|
+
try:
|
|
69
|
+
if max(len(credentials.user_id), len(credentials.session_id)) > _MAX_ID:
|
|
70
|
+
raise ValueError
|
|
71
|
+
_time(credentials.expires_at)
|
|
72
|
+
_time(credentials.refresh_expires_at)
|
|
73
|
+
except (ValueError, OverflowError):
|
|
74
|
+
raise ClientError("failed_precondition") from None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _next_auth_generation(
|
|
78
|
+
state: dict[str, object],
|
|
79
|
+
credentials: SessionCredentials | None,
|
|
80
|
+
*,
|
|
81
|
+
scoped_delete: bool = False,
|
|
82
|
+
floor: int = 0,
|
|
83
|
+
) -> int:
|
|
84
|
+
generation = cast(int, state["auth_generation"])
|
|
85
|
+
previous = state["session"]
|
|
86
|
+
if not scoped_delete and credentials is not None and isinstance(previous, dict):
|
|
87
|
+
if (previous.get("user_id"), previous.get("session_id")) == (
|
|
88
|
+
credentials.user_id,
|
|
89
|
+
credentials.session_id,
|
|
90
|
+
):
|
|
91
|
+
return generation
|
|
92
|
+
return max(generation, floor) + 1
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _location(app: str) -> Path:
|
|
96
|
+
if _HOST == "win32":
|
|
97
|
+
base = os.environ.get("LOCALAPPDATA")
|
|
98
|
+
if not base or not Path(base).is_absolute():
|
|
99
|
+
raise _storage_error("failed_precondition")
|
|
100
|
+
root = Path(base)
|
|
101
|
+
else:
|
|
102
|
+
home = os.environ.get("HOME")
|
|
103
|
+
state = os.environ.get("XDG_STATE_HOME")
|
|
104
|
+
if _HOST != "darwin" and state and Path(state).is_absolute():
|
|
105
|
+
root = Path(state)
|
|
106
|
+
else:
|
|
107
|
+
if not home or not Path(home).is_absolute():
|
|
108
|
+
raise _storage_error("failed_precondition")
|
|
109
|
+
root = (
|
|
110
|
+
Path(home) / "Library" / "Application Support"
|
|
111
|
+
if _HOST == "darwin"
|
|
112
|
+
else Path(home) / ".local" / "state"
|
|
113
|
+
)
|
|
114
|
+
return root / "chickinfry" / sha256(app.encode()).hexdigest()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _check_path(path: Path, *, directory: bool = False) -> None:
|
|
118
|
+
info = path.lstat()
|
|
119
|
+
if getattr(info, "st_file_attributes", 0) & 0x400:
|
|
120
|
+
raise _storage_error("failed_precondition")
|
|
121
|
+
if stat.S_ISLNK(info.st_mode) or not (
|
|
122
|
+
stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)
|
|
123
|
+
):
|
|
124
|
+
raise _storage_error("failed_precondition")
|
|
125
|
+
if _HOST == "win32":
|
|
126
|
+
from ._device_windows import _check_acl
|
|
127
|
+
|
|
128
|
+
_check_acl(path)
|
|
129
|
+
elif info.st_uid != os.getuid() or (
|
|
130
|
+
bool(info.st_mode & 0o022) if directory else stat.S_IMODE(info.st_mode) != 0o600
|
|
131
|
+
):
|
|
132
|
+
raise _storage_error("failed_precondition")
|
|
133
|
+
if not directory and info.st_nlink != 1:
|
|
134
|
+
raise _storage_error("failed_precondition")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _check_acl(descriptor: int) -> None:
|
|
138
|
+
if _HOST != "darwin":
|
|
139
|
+
return
|
|
140
|
+
import ctypes
|
|
141
|
+
import errno
|
|
142
|
+
|
|
143
|
+
libc = ctypes.CDLL("/usr/lib/libSystem.B.dylib", use_errno=True)
|
|
144
|
+
libc.acl_get_fd.argtypes = [ctypes.c_int]
|
|
145
|
+
libc.acl_get_fd.restype = ctypes.c_void_p
|
|
146
|
+
libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]
|
|
147
|
+
libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
|
148
|
+
libc.acl_free.argtypes = [ctypes.c_void_p]
|
|
149
|
+
acl = libc.acl_get_fd(descriptor)
|
|
150
|
+
if not acl:
|
|
151
|
+
if ctypes.get_errno() == errno.ENOENT:
|
|
152
|
+
return
|
|
153
|
+
raise _storage_error("failed_precondition")
|
|
154
|
+
try:
|
|
155
|
+
entry, tag = ctypes.c_void_p(), ctypes.c_int()
|
|
156
|
+
index = 0 # ACL_FIRST_ENTRY; Darwin's ACL_NEXT_ENTRY is -1.
|
|
157
|
+
while libc.acl_get_entry(acl, index, ctypes.byref(entry)) == 0:
|
|
158
|
+
if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0 or tag.value == 1:
|
|
159
|
+
raise _storage_error("failed_precondition")
|
|
160
|
+
index = -1
|
|
161
|
+
if ctypes.get_errno() != errno.EINVAL:
|
|
162
|
+
raise _storage_error("failed_precondition")
|
|
163
|
+
finally:
|
|
164
|
+
libc.acl_free(acl)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _check_directory(descriptor: int, *, ancestor: bool) -> None:
|
|
168
|
+
info = os.fstat(descriptor)
|
|
169
|
+
if not stat.S_ISDIR(info.st_mode) or info.st_uid not in (
|
|
170
|
+
(0, os.getuid()) if ancestor else (os.getuid(),)
|
|
171
|
+
):
|
|
172
|
+
raise _storage_error("failed_precondition")
|
|
173
|
+
if info.st_mode & 0o022 and not (ancestor and info.st_mode & stat.S_ISVTX):
|
|
174
|
+
raise _storage_error("failed_precondition")
|
|
175
|
+
_check_acl(descriptor)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _directory(path: Path) -> int | None:
|
|
179
|
+
if not path.is_absolute() or ".." in path.parts:
|
|
180
|
+
raise _storage_error("failed_precondition")
|
|
181
|
+
if _HOST != "win32":
|
|
182
|
+
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
183
|
+
descriptor = os.open(path.anchor, flags)
|
|
184
|
+
try:
|
|
185
|
+
_check_directory(descriptor, ancestor=True)
|
|
186
|
+
for index, part in enumerate(path.parts[1:]):
|
|
187
|
+
try:
|
|
188
|
+
os.mkdir(part, 0o700, dir_fd=descriptor)
|
|
189
|
+
except FileExistsError:
|
|
190
|
+
pass
|
|
191
|
+
child = os.open(part, flags, dir_fd=descriptor)
|
|
192
|
+
os.close(descriptor)
|
|
193
|
+
descriptor = child
|
|
194
|
+
_check_directory(descriptor, ancestor=index < len(path.parts) - 2)
|
|
195
|
+
return descriptor
|
|
196
|
+
except BaseException:
|
|
197
|
+
os.close(descriptor)
|
|
198
|
+
raise
|
|
199
|
+
for parent in path.parents:
|
|
200
|
+
if parent.is_symlink() or (
|
|
201
|
+
parent.exists() and getattr(parent.lstat(), "st_file_attributes", 0) & 0x400
|
|
202
|
+
):
|
|
203
|
+
raise _storage_error("failed_precondition")
|
|
204
|
+
missing: list[Path] = []
|
|
205
|
+
parent = path
|
|
206
|
+
while not parent.exists():
|
|
207
|
+
missing.append(parent)
|
|
208
|
+
parent = parent.parent
|
|
209
|
+
for folder in reversed(missing):
|
|
210
|
+
try:
|
|
211
|
+
if _HOST == "win32":
|
|
212
|
+
from ._device_windows import _mkdir
|
|
213
|
+
|
|
214
|
+
_mkdir(folder)
|
|
215
|
+
else:
|
|
216
|
+
folder.mkdir(mode=0o700)
|
|
217
|
+
except FileExistsError:
|
|
218
|
+
pass
|
|
219
|
+
_check_path(folder, directory=True)
|
|
220
|
+
_check_path(path, directory=True)
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _open_private(
|
|
225
|
+
path: Path,
|
|
226
|
+
*,
|
|
227
|
+
create: bool = False,
|
|
228
|
+
exclusive: bool = False,
|
|
229
|
+
directory: int | None = None,
|
|
230
|
+
) -> int:
|
|
231
|
+
flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)
|
|
232
|
+
if create:
|
|
233
|
+
if _HOST == "win32":
|
|
234
|
+
from ._device_windows import _create
|
|
235
|
+
|
|
236
|
+
try:
|
|
237
|
+
_create(path)
|
|
238
|
+
except FileExistsError:
|
|
239
|
+
if exclusive:
|
|
240
|
+
raise
|
|
241
|
+
else:
|
|
242
|
+
flags |= os.O_CREAT | (os.O_EXCL if exclusive else 0)
|
|
243
|
+
target = path if directory is None else Path(path.name)
|
|
244
|
+
descriptor = os.open(target, flags, 0o600, dir_fd=directory)
|
|
245
|
+
try:
|
|
246
|
+
if directory is None:
|
|
247
|
+
_check_path(path)
|
|
248
|
+
if _HOST == "win32":
|
|
249
|
+
for parent in path.parents:
|
|
250
|
+
info = parent.lstat()
|
|
251
|
+
if (
|
|
252
|
+
not stat.S_ISDIR(info.st_mode)
|
|
253
|
+
or getattr(info, "st_file_attributes", 0) & 0x400
|
|
254
|
+
):
|
|
255
|
+
raise _storage_error("failed_precondition")
|
|
256
|
+
opened = os.fstat(descriptor)
|
|
257
|
+
if directory is not None and (
|
|
258
|
+
not stat.S_ISREG(opened.st_mode)
|
|
259
|
+
or opened.st_uid != os.getuid()
|
|
260
|
+
or stat.S_IMODE(opened.st_mode) != 0o600
|
|
261
|
+
or opened.st_nlink != 1
|
|
262
|
+
):
|
|
263
|
+
raise _storage_error("failed_precondition")
|
|
264
|
+
_check_acl(descriptor)
|
|
265
|
+
current = os.stat(target, dir_fd=directory, follow_symlinks=False)
|
|
266
|
+
if (opened.st_dev, opened.st_ino) != (current.st_dev, current.st_ino):
|
|
267
|
+
raise _storage_error("failed_precondition")
|
|
268
|
+
return descriptor
|
|
269
|
+
except BaseException:
|
|
270
|
+
os.close(descriptor)
|
|
271
|
+
raise
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@contextmanager
|
|
275
|
+
def _process_lock(descriptor: int) -> Iterator[None]:
|
|
276
|
+
if _HOST == "win32":
|
|
277
|
+
import msvcrt
|
|
278
|
+
|
|
279
|
+
os.lseek(descriptor, 0, os.SEEK_SET)
|
|
280
|
+
getattr(msvcrt, "locking")(descriptor, getattr(msvcrt, "LK_LOCK"), 1)
|
|
281
|
+
try:
|
|
282
|
+
yield
|
|
283
|
+
finally:
|
|
284
|
+
os.lseek(descriptor, 0, os.SEEK_SET)
|
|
285
|
+
getattr(msvcrt, "locking")(descriptor, getattr(msvcrt, "LK_UNLCK"), 1)
|
|
286
|
+
else:
|
|
287
|
+
import fcntl
|
|
288
|
+
|
|
289
|
+
fcntl.flock(descriptor, fcntl.LOCK_EX)
|
|
290
|
+
try:
|
|
291
|
+
yield
|
|
292
|
+
finally:
|
|
293
|
+
fcntl.flock(descriptor, fcntl.LOCK_UN)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _atomic_write(path: Path, data: bytes, *, directory: int | None = None) -> None:
|
|
297
|
+
temporary = path.with_name("." + path.name + "." + uuid4().hex + ".tmp")
|
|
298
|
+
try:
|
|
299
|
+
descriptor = _open_private(
|
|
300
|
+
temporary, create=True, exclusive=True, directory=directory
|
|
301
|
+
)
|
|
302
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
303
|
+
stream.write(data)
|
|
304
|
+
stream.flush()
|
|
305
|
+
os.fsync(stream.fileno())
|
|
306
|
+
try:
|
|
307
|
+
descriptor = _open_private(path, directory=directory)
|
|
308
|
+
except FileNotFoundError:
|
|
309
|
+
pass
|
|
310
|
+
else:
|
|
311
|
+
os.close(descriptor)
|
|
312
|
+
if directory is None:
|
|
313
|
+
os.replace(temporary, path)
|
|
314
|
+
else:
|
|
315
|
+
os.replace(
|
|
316
|
+
temporary.name, path.name, src_dir_fd=directory, dst_dir_fd=directory
|
|
317
|
+
)
|
|
318
|
+
os.fsync(directory)
|
|
319
|
+
os.close(_open_private(path, directory=directory))
|
|
320
|
+
finally:
|
|
321
|
+
try:
|
|
322
|
+
os.unlink(
|
|
323
|
+
temporary if directory is None else temporary.name, dir_fd=directory
|
|
324
|
+
)
|
|
325
|
+
except FileNotFoundError:
|
|
326
|
+
pass
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@dataclass(repr=False)
|
|
330
|
+
class _Record:
|
|
331
|
+
raw: bytes | None
|
|
332
|
+
directory: int | None = None
|
|
333
|
+
lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class _DeviceSessionStore(MemoryStore):
|
|
337
|
+
def __init__(self, origin: str) -> None:
|
|
338
|
+
super().__init__(origin)
|
|
339
|
+
self._auth_generation = 0
|
|
340
|
+
self._peer_blocked = False
|
|
341
|
+
self._call_auth_generations: dict[int, int] = {}
|
|
342
|
+
|
|
343
|
+
def _register(
|
|
344
|
+
self, deadline: float | None = None, *, allow_empty: bool = False
|
|
345
|
+
) -> tuple[SessionCredentials | None, int]:
|
|
346
|
+
with self._locked(deadline):
|
|
347
|
+
previous_auth = self._auth_generation
|
|
348
|
+
had_credentials = self._credentials is not None
|
|
349
|
+
self.credentials()
|
|
350
|
+
if had_credentials and previous_auth != self._auth_generation:
|
|
351
|
+
self._credentials = None
|
|
352
|
+
raise _local_error("unauthenticated", "invalid_session")
|
|
353
|
+
if self._peer_blocked:
|
|
354
|
+
raise _local_error("unauthenticated", "invalid_session")
|
|
355
|
+
snapshot, generation = super()._register(deadline, allow_empty=allow_empty)
|
|
356
|
+
self._call_auth_generations[generation] = self._auth_generation
|
|
357
|
+
return snapshot, generation
|
|
358
|
+
|
|
359
|
+
def _release(self, generation: int) -> None:
|
|
360
|
+
with self._locked():
|
|
361
|
+
super()._release(generation)
|
|
362
|
+
if generation not in self._active:
|
|
363
|
+
self._call_auth_generations.pop(generation, None)
|
|
364
|
+
|
|
365
|
+
def _current(self, snapshot: SessionCredentials | None, generation: int) -> bool:
|
|
366
|
+
self.credentials()
|
|
367
|
+
return super()._current(snapshot, generation)
|
|
368
|
+
|
|
369
|
+
def _new_credentials(self, generation: int) -> SessionCredentials | None:
|
|
370
|
+
self.credentials()
|
|
371
|
+
if (
|
|
372
|
+
self._credentials is None
|
|
373
|
+
or self._call_auth_generations.get(generation) != self._auth_generation
|
|
374
|
+
):
|
|
375
|
+
raise _local_error("unauthenticated", "invalid_session")
|
|
376
|
+
return super()._new_credentials(generation)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class _DeviceStore(_DeviceSessionStore):
|
|
380
|
+
def __init__(
|
|
381
|
+
self,
|
|
382
|
+
origin: str,
|
|
383
|
+
*,
|
|
384
|
+
app: str,
|
|
385
|
+
project: str,
|
|
386
|
+
environment: str,
|
|
387
|
+
path: Path | None = None,
|
|
388
|
+
persist: bool = True,
|
|
389
|
+
) -> None:
|
|
390
|
+
super().__init__(origin)
|
|
391
|
+
if any(
|
|
392
|
+
not isinstance(value, str) or not value
|
|
393
|
+
for value in (app, project, environment)
|
|
394
|
+
):
|
|
395
|
+
raise ClientError("invalid_argument")
|
|
396
|
+
self._scope = json.dumps(
|
|
397
|
+
[app, self._origin, project, environment], separators=(",", ":")
|
|
398
|
+
)
|
|
399
|
+
self._memory_record = None if persist else _Record(None)
|
|
400
|
+
self._directory = path
|
|
401
|
+
self._path: Path | None = None
|
|
402
|
+
self._app = app
|
|
403
|
+
self._storage_blocked = False
|
|
404
|
+
self._location_ready = False
|
|
405
|
+
self._volatile = False
|
|
406
|
+
self._persisted_auth_generation = 0
|
|
407
|
+
self._persisted_session: object = None
|
|
408
|
+
self._refresh_auth_generations: dict[int, int] = {}
|
|
409
|
+
self._auth_in_progress: tuple[int, object] | None = None
|
|
410
|
+
self._retired_screens: set[str] = set()
|
|
411
|
+
self._baseline: dict[str, object] | None = None
|
|
412
|
+
self._pending: dict[str, object] | None = None
|
|
413
|
+
self._candidate: dict[str, object] | None = None
|
|
414
|
+
self._pending_view: dict[str, object] | None = None
|
|
415
|
+
self._discarded = False
|
|
416
|
+
self._peer_blocked = False
|
|
417
|
+
self._auth_request: str | None = None
|
|
418
|
+
self._refresh_request: str | None = None
|
|
419
|
+
self._memory_success = False
|
|
420
|
+
self._auth_high_water = 0
|
|
421
|
+
|
|
422
|
+
@contextmanager
|
|
423
|
+
def _transaction(self, *, block_on_failure: bool = False) -> Iterator[_Record]:
|
|
424
|
+
if self._storage_blocked:
|
|
425
|
+
raise _storage_error("failed_precondition")
|
|
426
|
+
failure: ClientError | None = None
|
|
427
|
+
descriptor = None
|
|
428
|
+
directory = None
|
|
429
|
+
pins = ExitStack()
|
|
430
|
+
try:
|
|
431
|
+
if self._memory_record is not None:
|
|
432
|
+
self._location_ready = True
|
|
433
|
+
with self._memory_record.lock:
|
|
434
|
+
yield self._memory_record
|
|
435
|
+
return
|
|
436
|
+
self._directory = self._directory or _location(self._app)
|
|
437
|
+
if _HOST == "win32":
|
|
438
|
+
from ._device_windows import _pin_directory
|
|
439
|
+
|
|
440
|
+
pins.enter_context(_pin_directory(self._directory))
|
|
441
|
+
directory = _directory(self._directory)
|
|
442
|
+
self._path = self._directory / (
|
|
443
|
+
sha256(self._scope.encode()).hexdigest() + ".json"
|
|
444
|
+
)
|
|
445
|
+
descriptor = _open_private(
|
|
446
|
+
self._path.with_suffix(".lock"), create=True, directory=directory
|
|
447
|
+
)
|
|
448
|
+
self._location_ready = True
|
|
449
|
+
with _process_lock(descriptor):
|
|
450
|
+
raw = None
|
|
451
|
+
try:
|
|
452
|
+
opened = _open_private(self._path, directory=directory)
|
|
453
|
+
except FileNotFoundError:
|
|
454
|
+
pass
|
|
455
|
+
else:
|
|
456
|
+
with os.fdopen(opened, "rb") as stream:
|
|
457
|
+
raw = stream.read(_MAX_BYTES + 1)
|
|
458
|
+
yield _Record(raw, directory)
|
|
459
|
+
except ClientError as error:
|
|
460
|
+
failure = error
|
|
461
|
+
except Exception as error:
|
|
462
|
+
reason = (
|
|
463
|
+
"resource_exhausted"
|
|
464
|
+
if isinstance(error, OSError) and error.errno in (28, 122)
|
|
465
|
+
else "failed_precondition"
|
|
466
|
+
)
|
|
467
|
+
failure = _storage_error(reason)
|
|
468
|
+
finally:
|
|
469
|
+
if descriptor is not None:
|
|
470
|
+
os.close(descriptor)
|
|
471
|
+
if directory is not None:
|
|
472
|
+
os.close(directory)
|
|
473
|
+
pins.close()
|
|
474
|
+
if failure is not None:
|
|
475
|
+
if block_on_failure:
|
|
476
|
+
self._storage_blocked = True
|
|
477
|
+
raise failure from None
|
|
478
|
+
|
|
479
|
+
def _read(self, record: _Record) -> dict[str, object]:
|
|
480
|
+
if record.raw is None:
|
|
481
|
+
return {
|
|
482
|
+
"version": 1,
|
|
483
|
+
"scope": self._scope,
|
|
484
|
+
"generation": 0,
|
|
485
|
+
"auth_generation": 0,
|
|
486
|
+
"session": None,
|
|
487
|
+
"attempts": {},
|
|
488
|
+
"refresh_unknown": False,
|
|
489
|
+
"auth_unknown": False,
|
|
490
|
+
"refresh_request": None,
|
|
491
|
+
"auth_request": None,
|
|
492
|
+
}
|
|
493
|
+
try:
|
|
494
|
+
if len(record.raw) > _MAX_BYTES:
|
|
495
|
+
raise ValueError
|
|
496
|
+
value: object = json.loads(
|
|
497
|
+
record.raw.decode("utf-8"), object_pairs_hook=_object
|
|
498
|
+
)
|
|
499
|
+
if not isinstance(value, dict):
|
|
500
|
+
raise ValueError
|
|
501
|
+
state = cast(dict[str, object], value)
|
|
502
|
+
if type(state.get("version")) is not int:
|
|
503
|
+
raise ValueError
|
|
504
|
+
if state["version"] != _VERSION:
|
|
505
|
+
raise _storage_error("unimplemented")
|
|
506
|
+
state.setdefault("auth_unknown", False)
|
|
507
|
+
state.setdefault("refresh_request", None)
|
|
508
|
+
state.setdefault("auth_request", None)
|
|
509
|
+
if (
|
|
510
|
+
set(state)
|
|
511
|
+
!= {
|
|
512
|
+
"version",
|
|
513
|
+
"scope",
|
|
514
|
+
"generation",
|
|
515
|
+
"auth_generation",
|
|
516
|
+
"session",
|
|
517
|
+
"attempts",
|
|
518
|
+
"refresh_unknown",
|
|
519
|
+
"auth_unknown",
|
|
520
|
+
"refresh_request",
|
|
521
|
+
"auth_request",
|
|
522
|
+
}
|
|
523
|
+
or state["scope"] != self._scope
|
|
524
|
+
or type(state["generation"]) is not int
|
|
525
|
+
or not 0 <= state["generation"] <= _MAX_INT
|
|
526
|
+
or type(state["auth_generation"]) is not int
|
|
527
|
+
or not 0 <= state["auth_generation"] <= _MAX_INT
|
|
528
|
+
or type(state["refresh_unknown"]) is not bool
|
|
529
|
+
or type(state["auth_unknown"]) is not bool
|
|
530
|
+
or not isinstance(state["attempts"], dict)
|
|
531
|
+
):
|
|
532
|
+
raise ValueError
|
|
533
|
+
for kind in ("refresh", "auth"):
|
|
534
|
+
request = state[kind + "_request"]
|
|
535
|
+
if request is not None and (
|
|
536
|
+
not isinstance(request, str)
|
|
537
|
+
or not 0 < len(request) <= _MAX_SCREEN
|
|
538
|
+
or not request.isascii()
|
|
539
|
+
or not state[kind + "_unknown"]
|
|
540
|
+
):
|
|
541
|
+
raise ValueError
|
|
542
|
+
if (state["refresh_unknown"] or state["auth_unknown"]) and state[
|
|
543
|
+
"session"
|
|
544
|
+
] is None:
|
|
545
|
+
raise ValueError
|
|
546
|
+
if state["session"] is not None:
|
|
547
|
+
if not isinstance(state["session"], dict) or set(state["session"]) != {
|
|
548
|
+
"access_token",
|
|
549
|
+
"refresh_token",
|
|
550
|
+
"expires_at",
|
|
551
|
+
"refresh_expires_at",
|
|
552
|
+
"user_id",
|
|
553
|
+
"session_id",
|
|
554
|
+
}:
|
|
555
|
+
raise ValueError
|
|
556
|
+
_native(_read_credentials(state["session"]))
|
|
557
|
+
if len(cast(dict[str, object], state["attempts"])) > _MAX_ATTEMPTS:
|
|
558
|
+
raise ValueError
|
|
559
|
+
for screen, attempt in cast(dict[str, object], state["attempts"]).items():
|
|
560
|
+
self._validate_attempt(screen, attempt)
|
|
561
|
+
return state
|
|
562
|
+
except ClientError as error:
|
|
563
|
+
if error.code == "unimplemented":
|
|
564
|
+
raise
|
|
565
|
+
except (ValueError, TypeError, KeyError, RecursionError):
|
|
566
|
+
pass
|
|
567
|
+
raise _storage_error("data_loss")
|
|
568
|
+
|
|
569
|
+
def _write(self, record: _Record, state: dict[str, object]) -> None:
|
|
570
|
+
raw = json.dumps(
|
|
571
|
+
state, ensure_ascii=True, separators=(",", ":"), allow_nan=False
|
|
572
|
+
).encode("utf-8")
|
|
573
|
+
if len(raw) > _MAX_BYTES or any(
|
|
574
|
+
not 0 <= cast(int, state[key]) <= _MAX_INT
|
|
575
|
+
for key in ("generation", "auth_generation")
|
|
576
|
+
):
|
|
577
|
+
raise _storage_error("resource_exhausted")
|
|
578
|
+
if self._memory_record is None:
|
|
579
|
+
assert self._path is not None
|
|
580
|
+
_atomic_write(self._path, raw, directory=record.directory)
|
|
581
|
+
record.raw = raw
|
|
582
|
+
|
|
583
|
+
def _load(self, state: dict[str, object]) -> None:
|
|
584
|
+
generation = cast(int, state["generation"])
|
|
585
|
+
unknown_auth = state["auth_unknown"] and self._auth_in_progress != (
|
|
586
|
+
state["auth_generation"],
|
|
587
|
+
state["session"],
|
|
588
|
+
)
|
|
589
|
+
credentials = (
|
|
590
|
+
_read_credentials(state["session"])
|
|
591
|
+
if state["session"] is not None and not unknown_auth
|
|
592
|
+
else None
|
|
593
|
+
)
|
|
594
|
+
# Attempt-only changes must preserve a pending delete's expected session.
|
|
595
|
+
if (
|
|
596
|
+
state["auth_generation"] != self._auth_generation
|
|
597
|
+
or credentials != self._credentials
|
|
598
|
+
):
|
|
599
|
+
self._credentials = credentials
|
|
600
|
+
self._generation = generation
|
|
601
|
+
self._auth_generation = cast(int, state["auth_generation"])
|
|
602
|
+
self._auth_high_water = max(self._auth_high_water, self._auth_generation)
|
|
603
|
+
self._blocked_generation = (
|
|
604
|
+
generation if state["refresh_unknown"] or state["auth_unknown"] else None
|
|
605
|
+
)
|
|
606
|
+
if not state["refresh_unknown"] and not state["auth_unknown"]:
|
|
607
|
+
self._peer_blocked = False
|
|
608
|
+
if not self._volatile:
|
|
609
|
+
self._baseline = deepcopy(state)
|
|
610
|
+
|
|
611
|
+
def _commit(self, record: _Record, state: dict[str, object]) -> None:
|
|
612
|
+
self._candidate = deepcopy(state)
|
|
613
|
+
self._write(record, state)
|
|
614
|
+
self._candidate = None
|
|
615
|
+
|
|
616
|
+
def _hold(self, state: dict[str, object]) -> None:
|
|
617
|
+
self._pending = deepcopy(state)
|
|
618
|
+
self._pending_view = None
|
|
619
|
+
self._volatile = True
|
|
620
|
+
if self._baseline is not None:
|
|
621
|
+
self._persisted_auth_generation = cast(
|
|
622
|
+
int, self._baseline["auth_generation"]
|
|
623
|
+
)
|
|
624
|
+
self._persisted_session = deepcopy(self._baseline["session"])
|
|
625
|
+
self._load(state)
|
|
626
|
+
|
|
627
|
+
@staticmethod
|
|
628
|
+
def _recoverable(error: ClientError) -> bool:
|
|
629
|
+
return error._storage_failure and error.code in {
|
|
630
|
+
"failed_precondition",
|
|
631
|
+
"resource_exhausted",
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
@staticmethod
|
|
635
|
+
def _auth_state(state: dict[str, object]) -> tuple[object, ...]:
|
|
636
|
+
return tuple(
|
|
637
|
+
state[key]
|
|
638
|
+
for key in (
|
|
639
|
+
"scope",
|
|
640
|
+
"auth_generation",
|
|
641
|
+
"session",
|
|
642
|
+
"refresh_unknown",
|
|
643
|
+
"refresh_request",
|
|
644
|
+
"auth_unknown",
|
|
645
|
+
"auth_request",
|
|
646
|
+
)
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
def _merge_attempts(
|
|
650
|
+
self,
|
|
651
|
+
base: dict[str, object],
|
|
652
|
+
memory: dict[str, object],
|
|
653
|
+
latest: dict[str, object],
|
|
654
|
+
) -> dict[str, object]:
|
|
655
|
+
before = cast(dict[str, dict[str, object]], base["attempts"])
|
|
656
|
+
local = cast(dict[str, dict[str, object]], memory["attempts"])
|
|
657
|
+
remote = cast(dict[str, dict[str, object]], latest["attempts"])
|
|
658
|
+
merged = deepcopy(remote)
|
|
659
|
+
for screen, old in before.items():
|
|
660
|
+
own = local.get(screen)
|
|
661
|
+
current = merged.get(screen)
|
|
662
|
+
if (own is None or own["attempt"] != old["attempt"]) and (
|
|
663
|
+
current is not None and current["attempt"] == old["attempt"]
|
|
664
|
+
):
|
|
665
|
+
merged.pop(screen)
|
|
666
|
+
for screen, own in local.items():
|
|
667
|
+
original = before.get(screen)
|
|
668
|
+
current = remote.get(screen)
|
|
669
|
+
if original is not None and own["attempt"] == original["attempt"]:
|
|
670
|
+
if current is None or current["attempt"] != original["attempt"]:
|
|
671
|
+
continue
|
|
672
|
+
if own == original:
|
|
673
|
+
continue
|
|
674
|
+
if (
|
|
675
|
+
current is not None
|
|
676
|
+
and current != original
|
|
677
|
+
and (cast(int, own["sequence"]) <= cast(int, current["sequence"]))
|
|
678
|
+
):
|
|
679
|
+
continue
|
|
680
|
+
merged[screen] = deepcopy(own)
|
|
681
|
+
now = _time(datetime.now(timezone.utc).isoformat())
|
|
682
|
+
return {
|
|
683
|
+
screen: value
|
|
684
|
+
for screen, value in merged.items()
|
|
685
|
+
if now - _time(cast(str, value["started_at"])) < 86_400_000_000
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
def _swap(
|
|
689
|
+
self, record: _Record, expected: bytes | None, state: dict[str, object]
|
|
690
|
+
) -> bool:
|
|
691
|
+
if record.raw != expected:
|
|
692
|
+
return False
|
|
693
|
+
self._commit(record, state)
|
|
694
|
+
return True
|
|
695
|
+
|
|
696
|
+
def _rejoin(self, record: _Record, latest: dict[str, object]) -> dict[str, object]:
|
|
697
|
+
base, memory = self._baseline, self._pending
|
|
698
|
+
assert memory is not None
|
|
699
|
+
for _ in range(3):
|
|
700
|
+
raw = record.raw
|
|
701
|
+
applied = self._candidate is not None and (
|
|
702
|
+
latest == self._candidate
|
|
703
|
+
or (
|
|
704
|
+
self._auth_state(latest) == self._auth_state(self._candidate)
|
|
705
|
+
and cast(int, latest["generation"])
|
|
706
|
+
>= cast(int, self._candidate["generation"])
|
|
707
|
+
and base is not None
|
|
708
|
+
and self._auth_state(self._candidate) != self._auth_state(base)
|
|
709
|
+
)
|
|
710
|
+
)
|
|
711
|
+
if (
|
|
712
|
+
base is None
|
|
713
|
+
or (
|
|
714
|
+
latest["auth_generation"] != base["auth_generation"] and not applied
|
|
715
|
+
)
|
|
716
|
+
or (cast(int, latest["generation"]) < cast(int, base["generation"]))
|
|
717
|
+
):
|
|
718
|
+
self._volatile = False
|
|
719
|
+
self._pending = self._candidate = self._pending_view = None
|
|
720
|
+
self._credentials = None
|
|
721
|
+
self._generation = cast(int, latest["generation"])
|
|
722
|
+
self._auth_generation = cast(int, latest["auth_generation"])
|
|
723
|
+
self._auth_high_water = max(
|
|
724
|
+
self._auth_high_water, self._auth_generation
|
|
725
|
+
)
|
|
726
|
+
self._baseline = deepcopy(latest)
|
|
727
|
+
self._retired_screens.clear()
|
|
728
|
+
self._memory_success = False
|
|
729
|
+
self._auth_request = self._refresh_request = None
|
|
730
|
+
self._auth_in_progress = None
|
|
731
|
+
self._peer_blocked = bool(
|
|
732
|
+
latest["refresh_unknown"] or latest["auth_unknown"]
|
|
733
|
+
)
|
|
734
|
+
self._discarded = True
|
|
735
|
+
return latest
|
|
736
|
+
merged = deepcopy(latest)
|
|
737
|
+
own_markers = {
|
|
738
|
+
"refresh": self._refresh_request,
|
|
739
|
+
"auth": self._auth_request,
|
|
740
|
+
}
|
|
741
|
+
install = latest["session"] == base["session"] and all(
|
|
742
|
+
not base[kind + "_unknown"]
|
|
743
|
+
or (
|
|
744
|
+
request is not None
|
|
745
|
+
and base[kind + "_request"] == request
|
|
746
|
+
and latest[kind + "_request"] == request
|
|
747
|
+
and latest[kind + "_unknown"] is True
|
|
748
|
+
)
|
|
749
|
+
for kind, request in own_markers.items()
|
|
750
|
+
if base[kind + "_unknown"] and not memory[kind + "_unknown"]
|
|
751
|
+
)
|
|
752
|
+
if install:
|
|
753
|
+
merged["session"] = deepcopy(memory["session"])
|
|
754
|
+
merged["auth_generation"] = memory["auth_generation"]
|
|
755
|
+
for kind, request in own_markers.items():
|
|
756
|
+
if (
|
|
757
|
+
base[kind + "_unknown"]
|
|
758
|
+
and not memory[kind + "_unknown"]
|
|
759
|
+
and request is not None
|
|
760
|
+
and latest[kind + "_request"] == request
|
|
761
|
+
):
|
|
762
|
+
merged[kind + "_unknown"] = False
|
|
763
|
+
merged[kind + "_request"] = None
|
|
764
|
+
merged["attempts"] = self._merge_attempts(base, memory, latest)
|
|
765
|
+
if merged != latest:
|
|
766
|
+
merged["generation"] = cast(int, latest["generation"]) + 1
|
|
767
|
+
self._pending_view = deepcopy(merged)
|
|
768
|
+
self._peer_blocked = bool(
|
|
769
|
+
merged["refresh_unknown"] or merged["auth_unknown"]
|
|
770
|
+
)
|
|
771
|
+
self._load(merged)
|
|
772
|
+
if len(cast(dict[str, object], merged["attempts"])) > _MAX_ATTEMPTS:
|
|
773
|
+
raise _storage_error("resource_exhausted")
|
|
774
|
+
if merged != latest:
|
|
775
|
+
if not self._swap(record, raw, merged):
|
|
776
|
+
latest = self._read(record)
|
|
777
|
+
continue
|
|
778
|
+
self._volatile = False
|
|
779
|
+
self._pending = self._candidate = self._pending_view = None
|
|
780
|
+
self._retired_screens.clear()
|
|
781
|
+
if not merged["refresh_unknown"]:
|
|
782
|
+
self._refresh_request = None
|
|
783
|
+
if not merged["auth_unknown"]:
|
|
784
|
+
self._auth_request = None
|
|
785
|
+
self._auth_in_progress = None
|
|
786
|
+
return merged
|
|
787
|
+
raise _storage_error("failed_precondition")
|
|
788
|
+
|
|
789
|
+
def _restore(self, record: _Record) -> dict[str, object]:
|
|
790
|
+
state = self._read(record)
|
|
791
|
+
if self._volatile:
|
|
792
|
+
return self._rejoin(record, state)
|
|
793
|
+
if self._baseline is not None and any(
|
|
794
|
+
state[kind + "_unknown"]
|
|
795
|
+
and (
|
|
796
|
+
not self._baseline[kind + "_unknown"]
|
|
797
|
+
or state[kind + "_request"] != self._baseline[kind + "_request"]
|
|
798
|
+
)
|
|
799
|
+
for kind in ("refresh", "auth")
|
|
800
|
+
):
|
|
801
|
+
self._peer_blocked = True
|
|
802
|
+
if (
|
|
803
|
+
self._baseline is None
|
|
804
|
+
and state["auth_unknown"]
|
|
805
|
+
and self._auth_in_progress
|
|
806
|
+
!= (
|
|
807
|
+
state["auth_generation"],
|
|
808
|
+
state["session"],
|
|
809
|
+
)
|
|
810
|
+
):
|
|
811
|
+
cleaned = {
|
|
812
|
+
**state,
|
|
813
|
+
"session": None,
|
|
814
|
+
"auth_unknown": False,
|
|
815
|
+
"refresh_unknown": False,
|
|
816
|
+
"auth_request": None,
|
|
817
|
+
"refresh_request": None,
|
|
818
|
+
"generation": cast(int, state["generation"]) + 1,
|
|
819
|
+
"auth_generation": cast(int, state["auth_generation"]) + 1,
|
|
820
|
+
}
|
|
821
|
+
try:
|
|
822
|
+
self._write(record, cleaned)
|
|
823
|
+
except (ClientError, OSError):
|
|
824
|
+
pass
|
|
825
|
+
else:
|
|
826
|
+
state = cleaned
|
|
827
|
+
self._baseline = deepcopy(state)
|
|
828
|
+
return state
|
|
829
|
+
|
|
830
|
+
def _snapshot(self) -> dict[str, object]:
|
|
831
|
+
return self._view()
|
|
832
|
+
|
|
833
|
+
def _view(self) -> dict[str, object]:
|
|
834
|
+
with self._locked():
|
|
835
|
+
self._check_loop()
|
|
836
|
+
self._discarded = False
|
|
837
|
+
try:
|
|
838
|
+
with self._transaction() as record:
|
|
839
|
+
state = self._restore(record)
|
|
840
|
+
except ClientError as error:
|
|
841
|
+
if (
|
|
842
|
+
self._memory_success
|
|
843
|
+
and self._baseline is not None
|
|
844
|
+
and self._credentials is not None
|
|
845
|
+
and not self._volatile
|
|
846
|
+
and self._recoverable(error)
|
|
847
|
+
):
|
|
848
|
+
self._hold(self._baseline)
|
|
849
|
+
if not self._volatile or not self._recoverable(error):
|
|
850
|
+
raise
|
|
851
|
+
overlay = self._pending_view or self._pending
|
|
852
|
+
assert overlay is not None
|
|
853
|
+
state = deepcopy(overlay)
|
|
854
|
+
if not self._discarded:
|
|
855
|
+
self._load(state)
|
|
856
|
+
return state
|
|
857
|
+
|
|
858
|
+
def credentials(self) -> SessionCredentials | None:
|
|
859
|
+
with self._locked():
|
|
860
|
+
self._check_loop()
|
|
861
|
+
if self._storage_blocked:
|
|
862
|
+
raise _storage_error("failed_precondition")
|
|
863
|
+
self._view()
|
|
864
|
+
return self._credentials
|
|
865
|
+
|
|
866
|
+
def _attach(self, mode: Literal["sync", "async"], origin: str) -> None:
|
|
867
|
+
with self._locked():
|
|
868
|
+
if origin != self._origin:
|
|
869
|
+
raise _local_error("failed_precondition", "origin_mismatch")
|
|
870
|
+
if self._mode is not None and self._mode != mode:
|
|
871
|
+
raise ClientError("failed_precondition")
|
|
872
|
+
if self._mode is None and mode == "sync":
|
|
873
|
+
self._loop = None
|
|
874
|
+
self.credentials()
|
|
875
|
+
super()._attach(mode, origin)
|
|
876
|
+
|
|
877
|
+
def replace(self, credentials: SessionCredentials) -> None:
|
|
878
|
+
_native(credentials)
|
|
879
|
+
with self._locked():
|
|
880
|
+
self._check_loop()
|
|
881
|
+
with self._transaction() as record:
|
|
882
|
+
state = self._read(record)
|
|
883
|
+
state.update(
|
|
884
|
+
auth_generation=_next_auth_generation(
|
|
885
|
+
state, credentials, floor=self._auth_high_water
|
|
886
|
+
),
|
|
887
|
+
session=asdict(credentials),
|
|
888
|
+
generation=cast(int, state["generation"]) + 1,
|
|
889
|
+
refresh_unknown=False,
|
|
890
|
+
auth_unknown=False,
|
|
891
|
+
refresh_request=None,
|
|
892
|
+
auth_request=None,
|
|
893
|
+
)
|
|
894
|
+
self._write(record, state)
|
|
895
|
+
# A run-local overlay can share the committed generation.
|
|
896
|
+
self._credentials = None
|
|
897
|
+
self._load(state)
|
|
898
|
+
self._volatile = False
|
|
899
|
+
self._pending = self._candidate = self._pending_view = None
|
|
900
|
+
self._retired_screens.clear()
|
|
901
|
+
self._memory_success = False
|
|
902
|
+
self._auth_request = self._refresh_request = None
|
|
903
|
+
self._auth_in_progress = None
|
|
904
|
+
self._condition.notify_all()
|
|
905
|
+
|
|
906
|
+
def clear(self, expected: SessionCredentials) -> None:
|
|
907
|
+
with self._locked():
|
|
908
|
+
self._check_loop()
|
|
909
|
+
if expected is not self._credentials:
|
|
910
|
+
return
|
|
911
|
+
auth_generation = (
|
|
912
|
+
self._persisted_auth_generation
|
|
913
|
+
if self._volatile
|
|
914
|
+
else self._auth_generation
|
|
915
|
+
)
|
|
916
|
+
session = self._persisted_session if self._volatile else asdict(expected)
|
|
917
|
+
with self._transaction(block_on_failure=True) as record:
|
|
918
|
+
state = self._read(record)
|
|
919
|
+
if (
|
|
920
|
+
state["auth_generation"] == auth_generation
|
|
921
|
+
and state["session"] == session
|
|
922
|
+
):
|
|
923
|
+
state.update(
|
|
924
|
+
session=None,
|
|
925
|
+
attempts={},
|
|
926
|
+
refresh_unknown=False,
|
|
927
|
+
auth_unknown=False,
|
|
928
|
+
refresh_request=None,
|
|
929
|
+
auth_request=None,
|
|
930
|
+
generation=cast(int, state["generation"]) + 1,
|
|
931
|
+
auth_generation=max(auth_generation, self._auth_high_water) + 1,
|
|
932
|
+
)
|
|
933
|
+
self._write(record, state)
|
|
934
|
+
self._volatile = False
|
|
935
|
+
self._pending = self._candidate = self._pending_view = None
|
|
936
|
+
self._credentials = None
|
|
937
|
+
self._auth_request = self._refresh_request = None
|
|
938
|
+
self._auth_in_progress = None
|
|
939
|
+
self._load(state)
|
|
940
|
+
self._condition.notify_all()
|
|
941
|
+
self._memory_success = False
|
|
942
|
+
|
|
943
|
+
@staticmethod
|
|
944
|
+
def _validate_attempt(screen_id: str, value: object) -> _Attempt:
|
|
945
|
+
if (
|
|
946
|
+
not isinstance(screen_id, str)
|
|
947
|
+
or not screen_id
|
|
948
|
+
or not isinstance(value, dict)
|
|
949
|
+
or set(value) != {"attempt", "email", "started_at", "sequence"}
|
|
950
|
+
):
|
|
951
|
+
raise ClientError("invalid_argument")
|
|
952
|
+
record = cast(dict[str, object], value)
|
|
953
|
+
if (
|
|
954
|
+
any(
|
|
955
|
+
not isinstance(record[key], str) or not record[key]
|
|
956
|
+
for key in ("attempt", "email", "started_at")
|
|
957
|
+
)
|
|
958
|
+
or type(record["sequence"]) is not int
|
|
959
|
+
or record["sequence"] < 0
|
|
960
|
+
):
|
|
961
|
+
raise ClientError("invalid_argument")
|
|
962
|
+
if (
|
|
963
|
+
len(screen_id) > _MAX_SCREEN
|
|
964
|
+
or not screen_id.isascii()
|
|
965
|
+
or len(cast(str, record["attempt"])) > _MAX_ID
|
|
966
|
+
or len(cast(str, record["email"])) > _MAX_EMAIL
|
|
967
|
+
or record["sequence"] > _MAX_INT
|
|
968
|
+
):
|
|
969
|
+
raise ClientError("invalid_argument")
|
|
970
|
+
try:
|
|
971
|
+
_time(cast(str, record["started_at"]))
|
|
972
|
+
except (ValueError, OverflowError):
|
|
973
|
+
raise ClientError("invalid_argument") from None
|
|
974
|
+
return _Attempt(record)
|
|
975
|
+
|
|
976
|
+
def _attempt(self, screen_id: str) -> _Attempt | None:
|
|
977
|
+
with self._locked():
|
|
978
|
+
state = self._snapshot()
|
|
979
|
+
attempts = cast(dict[str, object], state["attempts"])
|
|
980
|
+
value = attempts.get(screen_id)
|
|
981
|
+
return None if value is None else self._validate_attempt(screen_id, value)
|
|
982
|
+
|
|
983
|
+
def _save_attempt(
|
|
984
|
+
self,
|
|
985
|
+
screen_id: str,
|
|
986
|
+
value: Mapping[str, object],
|
|
987
|
+
*,
|
|
988
|
+
expected_generation: int,
|
|
989
|
+
remove_screens: tuple[str, ...] = (),
|
|
990
|
+
expected_auth_generation: int | None = None,
|
|
991
|
+
) -> bool:
|
|
992
|
+
attempt = self._validate_attempt(screen_id, dict(value))
|
|
993
|
+
with self._locked():
|
|
994
|
+
auth_generation = (
|
|
995
|
+
self._auth_generation
|
|
996
|
+
if expected_auth_generation is None
|
|
997
|
+
else expected_auth_generation
|
|
998
|
+
)
|
|
999
|
+
candidate = None
|
|
1000
|
+
try:
|
|
1001
|
+
with self._transaction() as record:
|
|
1002
|
+
self._discarded = False
|
|
1003
|
+
state = self._restore(record)
|
|
1004
|
+
if (
|
|
1005
|
+
self._discarded
|
|
1006
|
+
or state["generation"] != expected_generation
|
|
1007
|
+
or state["auth_generation"] != auth_generation
|
|
1008
|
+
):
|
|
1009
|
+
if not self._discarded:
|
|
1010
|
+
self._load(state)
|
|
1011
|
+
return False
|
|
1012
|
+
attempts = cast(dict[str, object], state["attempts"])
|
|
1013
|
+
for screen in remove_screens:
|
|
1014
|
+
attempts.pop(screen, None)
|
|
1015
|
+
if screen_id not in attempts and len(attempts) >= _MAX_ATTEMPTS:
|
|
1016
|
+
raise _storage_error("resource_exhausted")
|
|
1017
|
+
attempts[screen_id] = attempt
|
|
1018
|
+
state["generation"] = expected_generation + 1
|
|
1019
|
+
candidate = state
|
|
1020
|
+
self._commit(record, state)
|
|
1021
|
+
self._load(state)
|
|
1022
|
+
return True
|
|
1023
|
+
except ClientError as error:
|
|
1024
|
+
if candidate is not None and self._recoverable(error):
|
|
1025
|
+
self._hold(candidate)
|
|
1026
|
+
elif (
|
|
1027
|
+
self._location_ready
|
|
1028
|
+
and self._recoverable(error)
|
|
1029
|
+
and candidate is None
|
|
1030
|
+
):
|
|
1031
|
+
# No verified baseline remains distinct from an empty store.
|
|
1032
|
+
fallback = self._pending or self._baseline
|
|
1033
|
+
if fallback is None:
|
|
1034
|
+
state = {
|
|
1035
|
+
"version": 1,
|
|
1036
|
+
"scope": self._scope,
|
|
1037
|
+
"generation": expected_generation,
|
|
1038
|
+
"auth_generation": auth_generation,
|
|
1039
|
+
"session": None,
|
|
1040
|
+
"attempts": {},
|
|
1041
|
+
"refresh_unknown": False,
|
|
1042
|
+
"auth_unknown": False,
|
|
1043
|
+
"refresh_request": None,
|
|
1044
|
+
"auth_request": None,
|
|
1045
|
+
}
|
|
1046
|
+
else:
|
|
1047
|
+
state = deepcopy(fallback)
|
|
1048
|
+
if (
|
|
1049
|
+
state["generation"] == expected_generation
|
|
1050
|
+
and state["auth_generation"] == auth_generation
|
|
1051
|
+
):
|
|
1052
|
+
attempts = cast(dict[str, object], state["attempts"])
|
|
1053
|
+
for screen in remove_screens:
|
|
1054
|
+
attempts.pop(screen, None)
|
|
1055
|
+
if screen_id in attempts or len(attempts) < _MAX_ATTEMPTS:
|
|
1056
|
+
attempts[screen_id] = attempt
|
|
1057
|
+
state["generation"] = expected_generation + 1
|
|
1058
|
+
self._hold(state)
|
|
1059
|
+
raise
|
|
1060
|
+
|
|
1061
|
+
def _remove_attempts(
|
|
1062
|
+
self,
|
|
1063
|
+
screens: tuple[str, ...],
|
|
1064
|
+
*,
|
|
1065
|
+
expected_generation: int,
|
|
1066
|
+
expected_auth_generation: int,
|
|
1067
|
+
) -> bool:
|
|
1068
|
+
with self._locked(), self._transaction() as record:
|
|
1069
|
+
state = self._restore(record)
|
|
1070
|
+
if (
|
|
1071
|
+
state["generation"] != expected_generation
|
|
1072
|
+
or state["auth_generation"] != expected_auth_generation
|
|
1073
|
+
):
|
|
1074
|
+
self._load(state)
|
|
1075
|
+
return False
|
|
1076
|
+
for screen in screens:
|
|
1077
|
+
cast(dict[str, object], state["attempts"]).pop(screen, None)
|
|
1078
|
+
state["generation"] = expected_generation + 1
|
|
1079
|
+
try:
|
|
1080
|
+
self._commit(record, state)
|
|
1081
|
+
except (ClientError, OSError):
|
|
1082
|
+
self._hold(state)
|
|
1083
|
+
raise
|
|
1084
|
+
self._load(state)
|
|
1085
|
+
return True
|
|
1086
|
+
|
|
1087
|
+
def _transition(
|
|
1088
|
+
self,
|
|
1089
|
+
credentials: SessionCredentials | None,
|
|
1090
|
+
*,
|
|
1091
|
+
expected_generation: int,
|
|
1092
|
+
screens: tuple[str, ...] | None = (),
|
|
1093
|
+
user_id: str | None = None,
|
|
1094
|
+
expected_auth_generation: int | None = None,
|
|
1095
|
+
auth_unknown: bool = False,
|
|
1096
|
+
) -> bool:
|
|
1097
|
+
if credentials is not None:
|
|
1098
|
+
_native(credentials)
|
|
1099
|
+
if user_id != credentials.user_id:
|
|
1100
|
+
raise ClientError("invalid_argument")
|
|
1101
|
+
with self._locked(), self._transaction(block_on_failure=True) as record:
|
|
1102
|
+
self._discarded = False
|
|
1103
|
+
latest = self._read(record) if auth_unknown and self._peer_blocked else None
|
|
1104
|
+
if latest is not None and any(
|
|
1105
|
+
latest[kind + "_unknown"]
|
|
1106
|
+
and (
|
|
1107
|
+
latest[kind + "_request"] is None
|
|
1108
|
+
or latest[kind + "_request"] != owned_request
|
|
1109
|
+
)
|
|
1110
|
+
for kind, owned_request in (
|
|
1111
|
+
("refresh", self._refresh_request),
|
|
1112
|
+
("auth", self._auth_request),
|
|
1113
|
+
)
|
|
1114
|
+
):
|
|
1115
|
+
state = latest
|
|
1116
|
+
persisted_auth = (
|
|
1117
|
+
self._baseline["auth_generation"]
|
|
1118
|
+
if self._volatile and self._baseline is not None
|
|
1119
|
+
else self._auth_generation
|
|
1120
|
+
)
|
|
1121
|
+
if (
|
|
1122
|
+
expected_generation != self._generation
|
|
1123
|
+
or state["auth_generation"] != persisted_auth
|
|
1124
|
+
or (
|
|
1125
|
+
expected_auth_generation is not None
|
|
1126
|
+
and expected_auth_generation != self._auth_generation
|
|
1127
|
+
)
|
|
1128
|
+
):
|
|
1129
|
+
return False
|
|
1130
|
+
if screens is None:
|
|
1131
|
+
raise ClientError("invalid_argument")
|
|
1132
|
+
state["attempts"] = self._merge_attempts(state, state, state)
|
|
1133
|
+
state.update(
|
|
1134
|
+
session=None,
|
|
1135
|
+
refresh_unknown=False,
|
|
1136
|
+
auth_unknown=False,
|
|
1137
|
+
refresh_request=None,
|
|
1138
|
+
auth_request=None,
|
|
1139
|
+
generation=max(
|
|
1140
|
+
cast(int, state["generation"]),
|
|
1141
|
+
self._generation,
|
|
1142
|
+
cast(int, (self._pending or state)["generation"]),
|
|
1143
|
+
)
|
|
1144
|
+
+ 1,
|
|
1145
|
+
auth_generation=max(
|
|
1146
|
+
cast(int, state["auth_generation"]), self._auth_high_water
|
|
1147
|
+
)
|
|
1148
|
+
+ 1,
|
|
1149
|
+
)
|
|
1150
|
+
if not self._swap(record, record.raw, state):
|
|
1151
|
+
return False
|
|
1152
|
+
self._volatile = False
|
|
1153
|
+
self._pending = self._candidate = self._pending_view = None
|
|
1154
|
+
self._retired_screens.clear()
|
|
1155
|
+
self._memory_success = False
|
|
1156
|
+
self._auth_request = self._refresh_request = None
|
|
1157
|
+
self._auth_in_progress = None
|
|
1158
|
+
self._load(state)
|
|
1159
|
+
self._condition.notify_all()
|
|
1160
|
+
return True
|
|
1161
|
+
state = self._restore(record)
|
|
1162
|
+
if (
|
|
1163
|
+
state["generation"] != expected_generation
|
|
1164
|
+
or (
|
|
1165
|
+
expected_auth_generation is not None
|
|
1166
|
+
and state["auth_generation"] != expected_auth_generation
|
|
1167
|
+
)
|
|
1168
|
+
or self._discarded
|
|
1169
|
+
):
|
|
1170
|
+
self._load(state)
|
|
1171
|
+
return False
|
|
1172
|
+
if auth_unknown:
|
|
1173
|
+
if state["session"] is None:
|
|
1174
|
+
self._load(state)
|
|
1175
|
+
return True
|
|
1176
|
+
if (
|
|
1177
|
+
credentials is None
|
|
1178
|
+
or state["session"] != asdict(credentials)
|
|
1179
|
+
or screens != ()
|
|
1180
|
+
):
|
|
1181
|
+
raise ClientError("invalid_argument")
|
|
1182
|
+
if state["auth_unknown"] or state["refresh_unknown"]:
|
|
1183
|
+
raise ClientError("failed_precondition")
|
|
1184
|
+
request = str(uuid4())
|
|
1185
|
+
state.update(
|
|
1186
|
+
auth_unknown=True,
|
|
1187
|
+
auth_request=request,
|
|
1188
|
+
generation=expected_generation + 1,
|
|
1189
|
+
)
|
|
1190
|
+
try:
|
|
1191
|
+
self._write(record, state)
|
|
1192
|
+
except (ClientError, OSError):
|
|
1193
|
+
raise _storage_error("failed_precondition") from None
|
|
1194
|
+
self._auth_in_progress = (
|
|
1195
|
+
cast(int, state["auth_generation"]),
|
|
1196
|
+
state["session"],
|
|
1197
|
+
)
|
|
1198
|
+
self._auth_request = request
|
|
1199
|
+
self._load(state)
|
|
1200
|
+
return True
|
|
1201
|
+
if credentials is not None:
|
|
1202
|
+
for kind, owned_request in (
|
|
1203
|
+
("refresh", self._refresh_request),
|
|
1204
|
+
("auth", self._auth_request),
|
|
1205
|
+
):
|
|
1206
|
+
if (owned_request is not None or state[kind + "_unknown"]) and (
|
|
1207
|
+
owned_request is None
|
|
1208
|
+
or not state[kind + "_unknown"]
|
|
1209
|
+
or state[kind + "_request"] != owned_request
|
|
1210
|
+
):
|
|
1211
|
+
raise ClientError("failed_precondition")
|
|
1212
|
+
attempts = cast(dict[str, object], state["attempts"])
|
|
1213
|
+
if screens is None:
|
|
1214
|
+
attempts.clear()
|
|
1215
|
+
else:
|
|
1216
|
+
for screen in screens:
|
|
1217
|
+
attempts.pop(screen, None)
|
|
1218
|
+
state.update(
|
|
1219
|
+
auth_generation=_next_auth_generation(
|
|
1220
|
+
state,
|
|
1221
|
+
credentials,
|
|
1222
|
+
scoped_delete=screens is None,
|
|
1223
|
+
floor=self._auth_high_water,
|
|
1224
|
+
),
|
|
1225
|
+
session=asdict(credentials) if credentials else None,
|
|
1226
|
+
generation=expected_generation + 1,
|
|
1227
|
+
refresh_unknown=False,
|
|
1228
|
+
auth_unknown=False,
|
|
1229
|
+
refresh_request=None,
|
|
1230
|
+
auth_request=None,
|
|
1231
|
+
)
|
|
1232
|
+
self._commit(record, state)
|
|
1233
|
+
self._auth_in_progress = None
|
|
1234
|
+
self._auth_request = self._refresh_request = None
|
|
1235
|
+
self._load(state)
|
|
1236
|
+
self._condition.notify_all()
|
|
1237
|
+
return True
|
|
1238
|
+
|
|
1239
|
+
def _accept_login(
|
|
1240
|
+
self,
|
|
1241
|
+
credentials: SessionCredentials,
|
|
1242
|
+
*,
|
|
1243
|
+
expected_generation: int,
|
|
1244
|
+
user_id: str,
|
|
1245
|
+
screens: tuple[str, ...] = (),
|
|
1246
|
+
expected_auth_generation: int | None = None,
|
|
1247
|
+
) -> bool:
|
|
1248
|
+
with self._locked():
|
|
1249
|
+
if self._generation != expected_generation:
|
|
1250
|
+
return False
|
|
1251
|
+
persisted_auth_generation = self._auth_generation
|
|
1252
|
+
persisted_session = asdict(self._credentials) if self._credentials else None
|
|
1253
|
+
_native(credentials)
|
|
1254
|
+
if user_id != credentials.user_id:
|
|
1255
|
+
raise ClientError("invalid_argument")
|
|
1256
|
+
try:
|
|
1257
|
+
return self._transition(
|
|
1258
|
+
credentials,
|
|
1259
|
+
expected_generation=expected_generation,
|
|
1260
|
+
user_id=user_id,
|
|
1261
|
+
screens=screens,
|
|
1262
|
+
expected_auth_generation=expected_auth_generation,
|
|
1263
|
+
)
|
|
1264
|
+
except ClientError as error:
|
|
1265
|
+
if (
|
|
1266
|
+
not self._location_ready
|
|
1267
|
+
or not error._storage_failure
|
|
1268
|
+
or error.code
|
|
1269
|
+
not in {
|
|
1270
|
+
"failed_precondition",
|
|
1271
|
+
"resource_exhausted",
|
|
1272
|
+
}
|
|
1273
|
+
):
|
|
1274
|
+
raise
|
|
1275
|
+
with self._locked():
|
|
1276
|
+
if (
|
|
1277
|
+
self._generation != expected_generation
|
|
1278
|
+
or self._auth_generation != persisted_auth_generation
|
|
1279
|
+
):
|
|
1280
|
+
return False
|
|
1281
|
+
self._keep_memory(
|
|
1282
|
+
credentials,
|
|
1283
|
+
persisted_auth_generation=persisted_auth_generation,
|
|
1284
|
+
persisted_session=persisted_session,
|
|
1285
|
+
screens=screens,
|
|
1286
|
+
)
|
|
1287
|
+
return True
|
|
1288
|
+
|
|
1289
|
+
def _keep_memory(
|
|
1290
|
+
self,
|
|
1291
|
+
credentials: SessionCredentials,
|
|
1292
|
+
*,
|
|
1293
|
+
persisted_auth_generation: int,
|
|
1294
|
+
persisted_session: object,
|
|
1295
|
+
screens: tuple[str, ...] = (),
|
|
1296
|
+
) -> None:
|
|
1297
|
+
# STORE-ERRORS E1: only verified server credentials can enter this overlay.
|
|
1298
|
+
with self._locked():
|
|
1299
|
+
state = deepcopy(self._pending or self._baseline)
|
|
1300
|
+
if state is None:
|
|
1301
|
+
state = {
|
|
1302
|
+
"version": 1,
|
|
1303
|
+
"scope": self._scope,
|
|
1304
|
+
"generation": self._generation,
|
|
1305
|
+
"auth_generation": persisted_auth_generation,
|
|
1306
|
+
"session": persisted_session,
|
|
1307
|
+
"attempts": {},
|
|
1308
|
+
"refresh_unknown": False,
|
|
1309
|
+
"auth_unknown": False,
|
|
1310
|
+
"refresh_request": None,
|
|
1311
|
+
"auth_request": None,
|
|
1312
|
+
}
|
|
1313
|
+
state.update(
|
|
1314
|
+
auth_generation=_next_auth_generation(
|
|
1315
|
+
state, credentials, floor=self._auth_high_water
|
|
1316
|
+
),
|
|
1317
|
+
session=asdict(credentials),
|
|
1318
|
+
generation=self._generation + 1,
|
|
1319
|
+
refresh_unknown=False,
|
|
1320
|
+
auth_unknown=False,
|
|
1321
|
+
refresh_request=None,
|
|
1322
|
+
auth_request=None,
|
|
1323
|
+
)
|
|
1324
|
+
for screen in screens:
|
|
1325
|
+
cast(dict[str, object], state["attempts"]).pop(screen, None)
|
|
1326
|
+
self._hold(state)
|
|
1327
|
+
self._memory_success = True
|
|
1328
|
+
self._credentials = replace(credentials)
|
|
1329
|
+
self._storage_blocked = False
|
|
1330
|
+
self._retired_screens.update(screens)
|
|
1331
|
+
self._condition.notify_all()
|
|
1332
|
+
|
|
1333
|
+
def _begin_refresh(self, snapshot: SessionCredentials, generation: int) -> None:
|
|
1334
|
+
with self._locked(), self._transaction() as record:
|
|
1335
|
+
state = self._restore(record)
|
|
1336
|
+
if (
|
|
1337
|
+
state["generation"] != generation
|
|
1338
|
+
or state["refresh_unknown"]
|
|
1339
|
+
or state["auth_unknown"]
|
|
1340
|
+
):
|
|
1341
|
+
self._load(state)
|
|
1342
|
+
raise ClientError("failed_precondition")
|
|
1343
|
+
state["refresh_unknown"] = True
|
|
1344
|
+
request = str(uuid4())
|
|
1345
|
+
state["refresh_request"] = request
|
|
1346
|
+
self._write(record, state)
|
|
1347
|
+
self._load(state)
|
|
1348
|
+
self._refresh_request = request
|
|
1349
|
+
self._refresh_auth_generations[generation] = self._auth_generation
|
|
1350
|
+
|
|
1351
|
+
def _apply_refresh(
|
|
1352
|
+
self,
|
|
1353
|
+
snapshot: SessionCredentials,
|
|
1354
|
+
generation: int,
|
|
1355
|
+
credentials: SessionCredentials | None,
|
|
1356
|
+
failure: _Failure | None,
|
|
1357
|
+
) -> None:
|
|
1358
|
+
auth_generation = self._refresh_auth_generations.pop(generation, None)
|
|
1359
|
+
if failure is None and credentials is not None:
|
|
1360
|
+
_commit_device_refresh(self, snapshot, auth_generation, credentials)
|
|
1361
|
+
elif (
|
|
1362
|
+
failure is not None
|
|
1363
|
+
and failure.valid_error_envelope
|
|
1364
|
+
and failure.status == 401
|
|
1365
|
+
):
|
|
1366
|
+
self.clear(snapshot)
|
|
1367
|
+
# All other outcomes retain the durable consumption-unknown marker.
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
def _persist_settings(persist: bool | Mapping[str, object]) -> bool | dict[str, Path]:
|
|
1371
|
+
if persist is True or persist is False:
|
|
1372
|
+
return persist
|
|
1373
|
+
if (
|
|
1374
|
+
isinstance(persist, Mapping)
|
|
1375
|
+
and set(persist) == {"dir"}
|
|
1376
|
+
and isinstance(persist["dir"], (str, os.PathLike))
|
|
1377
|
+
):
|
|
1378
|
+
try:
|
|
1379
|
+
raw = os.fspath(persist["dir"])
|
|
1380
|
+
if not isinstance(raw, str) or not raw or "\0" in raw:
|
|
1381
|
+
raise ValueError
|
|
1382
|
+
return {"dir": Path(os.path.abspath(raw))}
|
|
1383
|
+
except (OSError, ValueError, TypeError):
|
|
1384
|
+
raise _storage_error("failed_precondition") from None
|
|
1385
|
+
raise ClientError("invalid_argument")
|
|
1386
|
+
|
|
1387
|
+
|
|
1388
|
+
def _device_store(
|
|
1389
|
+
origin: str,
|
|
1390
|
+
*,
|
|
1391
|
+
app: str,
|
|
1392
|
+
project: str,
|
|
1393
|
+
environment: str,
|
|
1394
|
+
persist: bool | Mapping[str, object] = True,
|
|
1395
|
+
) -> _DeviceStore:
|
|
1396
|
+
settings = _persist_settings(persist)
|
|
1397
|
+
path = settings["dir"] if isinstance(settings, dict) else None
|
|
1398
|
+
return _DeviceStore(
|
|
1399
|
+
origin,
|
|
1400
|
+
app=app,
|
|
1401
|
+
project=project,
|
|
1402
|
+
environment=environment,
|
|
1403
|
+
path=path,
|
|
1404
|
+
persist=settings is not False,
|
|
1405
|
+
)
|