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/auth.py
ADDED
|
@@ -0,0 +1,1227 @@
|
|
|
1
|
+
"""The auth core receives create_database(port) from the canonical repository's
|
|
2
|
+
generated private ORM.
|
|
3
|
+
|
|
4
|
+
The generated ORM provides users/sessions/refresh_tokens/identities/invites/
|
|
5
|
+
rate_limits repositories with snake_case row fields and Table metadata. The
|
|
6
|
+
generator owns the schema; this core creates no tables. Hook wiring builds a
|
|
7
|
+
public context through the transaction port, and native wire connections
|
|
8
|
+
reply with Tokens.to_wire() using only the declared methods.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import secrets
|
|
17
|
+
from collections.abc import Awaitable, Callable, Coroutine, Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from datetime import datetime, timedelta, timezone
|
|
20
|
+
from typing import Protocol, TypedDict, TypeVar
|
|
21
|
+
from uuid import UUID
|
|
22
|
+
|
|
23
|
+
from ._password import CPythonScrypt, PasswordKDF, hash_password, verify_password
|
|
24
|
+
from .orm import (
|
|
25
|
+
DatabasePort,
|
|
26
|
+
Filter,
|
|
27
|
+
Order,
|
|
28
|
+
Table,
|
|
29
|
+
and_,
|
|
30
|
+
format_timestamp,
|
|
31
|
+
or_,
|
|
32
|
+
parse_timestamp,
|
|
33
|
+
)
|
|
34
|
+
from .server import OperationError, Session, User
|
|
35
|
+
|
|
36
|
+
R_co = TypeVar("R_co", covariant=True)
|
|
37
|
+
T = TypeVar("T")
|
|
38
|
+
|
|
39
|
+
# ECMAScript trim and \s share this set; Python differs for U+0085 and U+FEFF.
|
|
40
|
+
_EMAIL_WHITESPACE = (
|
|
41
|
+
"\t\n\v\f\r \u00a0\u1680"
|
|
42
|
+
"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
|
|
43
|
+
"\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AuthRepository(Protocol[R_co]):
|
|
48
|
+
@property
|
|
49
|
+
def table(self) -> Table: ...
|
|
50
|
+
async def find_by_id(self, key: Mapping[str, object]) -> R_co | None: ...
|
|
51
|
+
async def find_many(
|
|
52
|
+
self,
|
|
53
|
+
*,
|
|
54
|
+
where: Filter | None = None,
|
|
55
|
+
order_by: Sequence[Order] = (),
|
|
56
|
+
limit: int | None = None,
|
|
57
|
+
offset: int | None = None,
|
|
58
|
+
) -> Sequence[R_co]: ...
|
|
59
|
+
async def insert(self, values: Mapping[str, object]) -> R_co: ...
|
|
60
|
+
async def update(
|
|
61
|
+
self, key: Mapping[str, object], patch: Mapping[str, object]
|
|
62
|
+
) -> R_co: ...
|
|
63
|
+
async def update_if(
|
|
64
|
+
self, key: Mapping[str, object], condition: Filter, patch: Mapping[str, object]
|
|
65
|
+
) -> R_co | None: ...
|
|
66
|
+
async def delete(self, key: Mapping[str, object]) -> R_co | None: ...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class UserRecord(Protocol):
|
|
70
|
+
@property
|
|
71
|
+
def id(self) -> str: ...
|
|
72
|
+
@property
|
|
73
|
+
def email(self) -> str: ...
|
|
74
|
+
@property
|
|
75
|
+
def password_hash(self) -> str | None: ...
|
|
76
|
+
@property
|
|
77
|
+
def disabled_at(self) -> str | None: ...
|
|
78
|
+
@property
|
|
79
|
+
def session_version(self) -> int: ...
|
|
80
|
+
@property
|
|
81
|
+
def created_at(self) -> str: ...
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class SessionRecord(Protocol):
|
|
85
|
+
@property
|
|
86
|
+
def id(self) -> str: ...
|
|
87
|
+
@property
|
|
88
|
+
def user_id(self) -> str: ...
|
|
89
|
+
@property
|
|
90
|
+
def token_hash(self) -> str: ...
|
|
91
|
+
@property
|
|
92
|
+
def user_session_version(self) -> int: ...
|
|
93
|
+
@property
|
|
94
|
+
def transport(self) -> str: ...
|
|
95
|
+
@property
|
|
96
|
+
def expires_at(self) -> str: ...
|
|
97
|
+
@property
|
|
98
|
+
def revoked_at(self) -> str | None: ...
|
|
99
|
+
@property
|
|
100
|
+
def created_at(self) -> str: ...
|
|
101
|
+
@property
|
|
102
|
+
def first_login_at(self) -> str | None: ...
|
|
103
|
+
@property
|
|
104
|
+
def last_renewed_at(self) -> str | None: ...
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class RefreshRecord(Protocol):
|
|
108
|
+
@property
|
|
109
|
+
def id(self) -> str: ...
|
|
110
|
+
@property
|
|
111
|
+
def session_id(self) -> str: ...
|
|
112
|
+
@property
|
|
113
|
+
def expires_at(self) -> str: ...
|
|
114
|
+
@property
|
|
115
|
+
def consumed_at(self) -> str | None: ...
|
|
116
|
+
@property
|
|
117
|
+
def created_at(self) -> str: ...
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class IdentityRecord(Protocol):
|
|
121
|
+
@property
|
|
122
|
+
def user_id(self) -> str: ...
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class InviteRecord(Protocol):
|
|
126
|
+
@property
|
|
127
|
+
def id(self) -> str: ...
|
|
128
|
+
@property
|
|
129
|
+
def email(self) -> str: ...
|
|
130
|
+
@property
|
|
131
|
+
def expires_at(self) -> str: ...
|
|
132
|
+
@property
|
|
133
|
+
def created_at(self) -> str: ...
|
|
134
|
+
@property
|
|
135
|
+
def redeemed_at(self) -> str | None: ...
|
|
136
|
+
@property
|
|
137
|
+
def redeemed_by(self) -> str | None: ...
|
|
138
|
+
@property
|
|
139
|
+
def revoked_at(self) -> str | None: ...
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class RateLimitRecord(Protocol):
|
|
143
|
+
@property
|
|
144
|
+
def action(self) -> str: ...
|
|
145
|
+
@property
|
|
146
|
+
def key_hash(self) -> str: ...
|
|
147
|
+
@property
|
|
148
|
+
def attempt_count(self) -> int: ...
|
|
149
|
+
@property
|
|
150
|
+
def expires_at(self) -> str: ...
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class AuthDatabase(Protocol):
|
|
154
|
+
@property
|
|
155
|
+
def users(self) -> AuthRepository[UserRecord]: ...
|
|
156
|
+
@property
|
|
157
|
+
def sessions(self) -> AuthRepository[SessionRecord]: ...
|
|
158
|
+
@property
|
|
159
|
+
def refresh_tokens(self) -> AuthRepository[RefreshRecord]: ...
|
|
160
|
+
@property
|
|
161
|
+
def identities(self) -> AuthRepository[IdentityRecord]: ...
|
|
162
|
+
@property
|
|
163
|
+
def invites(self) -> AuthRepository[InviteRecord]: ...
|
|
164
|
+
@property
|
|
165
|
+
def rate_limits(self) -> AuthRepository[RateLimitRecord]: ...
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class ClosablePort(DatabasePort, Protocol):
|
|
169
|
+
async def close(self) -> None: ...
|
|
170
|
+
def terminate(self) -> None: ...
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True, slots=True)
|
|
174
|
+
class AuthUser:
|
|
175
|
+
id: str
|
|
176
|
+
email: str
|
|
177
|
+
created_at: str
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(frozen=True, slots=True)
|
|
181
|
+
class _SessionResult:
|
|
182
|
+
session: Session
|
|
183
|
+
expires_at: str
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class TokensWire(TypedDict):
|
|
187
|
+
access_token: str
|
|
188
|
+
refresh_token: str
|
|
189
|
+
expires_at: str
|
|
190
|
+
refresh_expires_at: str
|
|
191
|
+
user_id: str
|
|
192
|
+
session_id: str
|
|
193
|
+
email_verified: bool
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
197
|
+
class Tokens:
|
|
198
|
+
access_token: str
|
|
199
|
+
refresh_token: str
|
|
200
|
+
expires_at: str
|
|
201
|
+
refresh_expires_at: str
|
|
202
|
+
user_id: str
|
|
203
|
+
session_id: str
|
|
204
|
+
|
|
205
|
+
def to_wire(self) -> TokensWire:
|
|
206
|
+
return {
|
|
207
|
+
"access_token": self.access_token,
|
|
208
|
+
"refresh_token": self.refresh_token,
|
|
209
|
+
"expires_at": self.expires_at,
|
|
210
|
+
"refresh_expires_at": self.refresh_expires_at,
|
|
211
|
+
"user_id": self.user_id,
|
|
212
|
+
"session_id": self.session_id,
|
|
213
|
+
# No email_verified_at column; switch to the column's value when it is introduced.
|
|
214
|
+
"email_verified": False,
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@dataclass(frozen=True, slots=True)
|
|
219
|
+
class AuthHooks:
|
|
220
|
+
user_creating: Callable[[DatabasePort, AuthUser], Awaitable[None]] | None = None
|
|
221
|
+
user_created: Callable[[AuthUser], Awaitable[None]] | None = None
|
|
222
|
+
invite_managing: Callable[[DatabasePort, Session, str], Awaitable[None]] | None = (
|
|
223
|
+
None
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass(frozen=True, slots=True)
|
|
228
|
+
class Identity:
|
|
229
|
+
subject: str
|
|
230
|
+
verified_email: str
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class IdentityProvider(Protocol):
|
|
234
|
+
@property
|
|
235
|
+
def id(self) -> str: ...
|
|
236
|
+
async def verify(self, credential: object) -> Identity: ...
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@dataclass(frozen=True, slots=True)
|
|
240
|
+
class CleanupContext:
|
|
241
|
+
create_port: Callable[[], ClosablePort]
|
|
242
|
+
wait_until: Callable[[Coroutine[None, None, None]], None]
|
|
243
|
+
failure: Callable[[str], None] | None = None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def random_token() -> str:
|
|
247
|
+
return base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip("=")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def hash_token(value: str) -> str:
|
|
251
|
+
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _canonical(value: str) -> bool:
|
|
255
|
+
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", value):
|
|
256
|
+
return False
|
|
257
|
+
return (
|
|
258
|
+
base64.urlsafe_b64encode(base64.urlsafe_b64decode(value + "="))
|
|
259
|
+
.decode()
|
|
260
|
+
.rstrip("=")
|
|
261
|
+
== value
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _validate_token(value: str) -> None:
|
|
266
|
+
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", value):
|
|
267
|
+
raise OperationError("invalid_token", 401)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _valid_email_format(email: str) -> bool:
|
|
271
|
+
local, separator, domain = email.partition("@")
|
|
272
|
+
return (
|
|
273
|
+
bool(local and separator)
|
|
274
|
+
and "@" not in domain
|
|
275
|
+
and "." in domain[1:-1]
|
|
276
|
+
and not any(character in _EMAIL_WHITESPACE for character in email)
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def normalize_email(value: str) -> str:
|
|
281
|
+
if not isinstance(value, str):
|
|
282
|
+
raise OperationError("invalid_input", 400)
|
|
283
|
+
email = value.strip(_EMAIL_WHITESPACE).lower()
|
|
284
|
+
if (
|
|
285
|
+
"\0" in email
|
|
286
|
+
or len(email.encode("utf-16-le", "surrogatepass")) // 2 > 320
|
|
287
|
+
or not _valid_email_format(email)
|
|
288
|
+
):
|
|
289
|
+
raise OperationError("invalid_input", 400)
|
|
290
|
+
return email
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def validate_password(value: str) -> None:
|
|
294
|
+
try:
|
|
295
|
+
if (
|
|
296
|
+
not isinstance(value, str)
|
|
297
|
+
or len(value) < 15
|
|
298
|
+
or len(value.encode("utf-8")) > 1024
|
|
299
|
+
):
|
|
300
|
+
raise ValueError
|
|
301
|
+
except (ValueError, UnicodeError):
|
|
302
|
+
raise OperationError("invalid_input", 400) from None
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _filter(
|
|
306
|
+
repo: AuthRepository[object], name: str, operator: str, *values: object
|
|
307
|
+
) -> Filter:
|
|
308
|
+
return Filter(operator, repo.table.columns[name], values)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _unique(error: Exception) -> bool:
|
|
312
|
+
return getattr(error, "sqlstate", None) == "23505"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _invite_id(value: str) -> str:
|
|
316
|
+
if not isinstance(value, str) or not re.fullmatch(
|
|
317
|
+
r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value
|
|
318
|
+
):
|
|
319
|
+
raise OperationError("invalid_input", 400)
|
|
320
|
+
return value.lower()
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class Auth:
|
|
324
|
+
"""Per-request auth core; the factory and hooks share one real DatabasePort."""
|
|
325
|
+
|
|
326
|
+
def __init__(
|
|
327
|
+
self,
|
|
328
|
+
port: DatabasePort,
|
|
329
|
+
create_database: Callable[[DatabasePort], AuthDatabase],
|
|
330
|
+
*,
|
|
331
|
+
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc),
|
|
332
|
+
hooks: AuthHooks = AuthHooks(),
|
|
333
|
+
signup: str = "open",
|
|
334
|
+
project_id: str | None = None,
|
|
335
|
+
providers: Sequence[IdentityProvider] = (),
|
|
336
|
+
cleanup: CleanupContext | None = None,
|
|
337
|
+
idle_timeout_seconds: int = 2592000,
|
|
338
|
+
absolute_lifetime_seconds: int = 0,
|
|
339
|
+
_kdf: PasswordKDF | None = None,
|
|
340
|
+
) -> None:
|
|
341
|
+
if signup not in ("open", "invite-only"):
|
|
342
|
+
raise ValueError("Invalid signup policy.")
|
|
343
|
+
if (
|
|
344
|
+
type(idle_timeout_seconds) is not int
|
|
345
|
+
or not 3600 <= idle_timeout_seconds <= 31536000
|
|
346
|
+
):
|
|
347
|
+
raise ValueError(
|
|
348
|
+
"auth.session.idle_timeout_seconds must be an integer between 3600 and 31536000 seconds"
|
|
349
|
+
)
|
|
350
|
+
if type(absolute_lifetime_seconds) is not int or not (
|
|
351
|
+
absolute_lifetime_seconds == 0
|
|
352
|
+
or 3600 <= absolute_lifetime_seconds <= 31536000
|
|
353
|
+
):
|
|
354
|
+
raise ValueError(
|
|
355
|
+
"auth.session.absolute_lifetime_seconds must be 0 (disabled) or an integer between 3600 and 31536000 seconds"
|
|
356
|
+
)
|
|
357
|
+
self.idle_timeout_seconds = idle_timeout_seconds
|
|
358
|
+
self.absolute_lifetime_seconds = absolute_lifetime_seconds
|
|
359
|
+
self.port, self.create_database = port, create_database
|
|
360
|
+
self.db = create_database(port)
|
|
361
|
+
self.now, self.hooks, self.signup_policy, self.project_id = (
|
|
362
|
+
now,
|
|
363
|
+
hooks,
|
|
364
|
+
signup,
|
|
365
|
+
project_id,
|
|
366
|
+
)
|
|
367
|
+
self.cleanup_context = cleanup
|
|
368
|
+
self._kdf = _kdf if _kdf is not None else CPythonScrypt()
|
|
369
|
+
self.providers: dict[str, IdentityProvider] = {}
|
|
370
|
+
for provider in providers:
|
|
371
|
+
if (
|
|
372
|
+
not re.fullmatch(r"[a-z][a-z0-9_-]{0,62}", provider.id)
|
|
373
|
+
or provider.id == "password"
|
|
374
|
+
or provider.id in self.providers
|
|
375
|
+
):
|
|
376
|
+
raise ValueError("Invalid or duplicate identity provider.")
|
|
377
|
+
self.providers[provider.id] = provider
|
|
378
|
+
|
|
379
|
+
def _timestamp(self, seconds: int = 0) -> str:
|
|
380
|
+
return format_timestamp(self.now() + timedelta(seconds=seconds))
|
|
381
|
+
|
|
382
|
+
async def _issue(self, db: AuthDatabase, user: UserRecord) -> Tokens:
|
|
383
|
+
current = await db.users.update_if(
|
|
384
|
+
{"id": user.id},
|
|
385
|
+
and_(
|
|
386
|
+
_filter(db.users, "disabled_at", "is null"),
|
|
387
|
+
_filter(db.users, "session_version", "=", user.session_version),
|
|
388
|
+
),
|
|
389
|
+
{"session_version": user.session_version},
|
|
390
|
+
)
|
|
391
|
+
if current is None:
|
|
392
|
+
raise OperationError("invalid_credentials", 401)
|
|
393
|
+
access, refresh = random_token(), random_token()
|
|
394
|
+
issued = self.now()
|
|
395
|
+
expiry = format_timestamp(issued + timedelta(seconds=900))
|
|
396
|
+
stamp = format_timestamp(issued)
|
|
397
|
+
family = format_timestamp(self._renewed_expiry(issued, issued))
|
|
398
|
+
session = await db.sessions.insert(
|
|
399
|
+
{
|
|
400
|
+
"user_id": user.id,
|
|
401
|
+
"token_hash": hash_token(access),
|
|
402
|
+
"user_session_version": user.session_version,
|
|
403
|
+
"expires_at": expiry,
|
|
404
|
+
"transport": "native",
|
|
405
|
+
"created_at": stamp,
|
|
406
|
+
"first_login_at": stamp,
|
|
407
|
+
"last_renewed_at": stamp,
|
|
408
|
+
}
|
|
409
|
+
)
|
|
410
|
+
await db.refresh_tokens.insert(
|
|
411
|
+
{
|
|
412
|
+
"session_id": session.id,
|
|
413
|
+
"token_hash": hash_token(refresh),
|
|
414
|
+
"expires_at": family,
|
|
415
|
+
"created_at": stamp,
|
|
416
|
+
}
|
|
417
|
+
)
|
|
418
|
+
return Tokens(access, refresh, expiry, family, user.id, session.id)
|
|
419
|
+
|
|
420
|
+
def _renewed_expiry(self, first: datetime, issued: datetime) -> datetime:
|
|
421
|
+
idle = issued + timedelta(seconds=self.idle_timeout_seconds)
|
|
422
|
+
return (
|
|
423
|
+
min(idle, first + timedelta(seconds=self.absolute_lifetime_seconds))
|
|
424
|
+
if self.absolute_lifetime_seconds
|
|
425
|
+
else idle
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
async def _family_expiry(
|
|
429
|
+
self, db: AuthDatabase, record: SessionRecord
|
|
430
|
+
) -> datetime | None:
|
|
431
|
+
active = await db.refresh_tokens.find_many(
|
|
432
|
+
where=and_(
|
|
433
|
+
_filter(db.refresh_tokens, "session_id", "=", record.id),
|
|
434
|
+
_filter(db.refresh_tokens, "consumed_at", "is null"),
|
|
435
|
+
),
|
|
436
|
+
limit=2,
|
|
437
|
+
)
|
|
438
|
+
if len(active) != 1:
|
|
439
|
+
return None
|
|
440
|
+
renewed = record.last_renewed_at
|
|
441
|
+
if renewed is None:
|
|
442
|
+
latest = await db.refresh_tokens.find_many(
|
|
443
|
+
where=_filter(db.refresh_tokens, "session_id", "=", record.id),
|
|
444
|
+
order_by=(
|
|
445
|
+
Order(db.refresh_tokens.table.columns["created_at"], "desc"),
|
|
446
|
+
),
|
|
447
|
+
limit=1,
|
|
448
|
+
)
|
|
449
|
+
renewed = latest[0].created_at
|
|
450
|
+
first = parse_timestamp(record.first_login_at or record.created_at)
|
|
451
|
+
return min(
|
|
452
|
+
parse_timestamp(active[0].expires_at),
|
|
453
|
+
self._renewed_expiry(first, parse_timestamp(renewed)),
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
async def _lock_user(
|
|
457
|
+
self, db: AuthDatabase, record: SessionRecord
|
|
458
|
+
) -> UserRecord | None:
|
|
459
|
+
return await db.users.update_if(
|
|
460
|
+
{"id": record.user_id},
|
|
461
|
+
and_(
|
|
462
|
+
_filter(db.users, "disabled_at", "is null"),
|
|
463
|
+
_filter(db.users, "session_version", "=", record.user_session_version),
|
|
464
|
+
),
|
|
465
|
+
{"session_version": record.user_session_version},
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
async def _creating(self, port: DatabasePort, user: UserRecord) -> AuthUser:
|
|
469
|
+
public = AuthUser(user.id, user.email, user.created_at)
|
|
470
|
+
if self.hooks.user_creating is not None:
|
|
471
|
+
try:
|
|
472
|
+
await self.hooks.user_creating(port, public)
|
|
473
|
+
except Exception:
|
|
474
|
+
raise OperationError("user_creation_failed", 500) from None
|
|
475
|
+
return public
|
|
476
|
+
|
|
477
|
+
async def _created(self, user: AuthUser) -> None:
|
|
478
|
+
if self.hooks.user_created is not None:
|
|
479
|
+
try:
|
|
480
|
+
await self.hooks.user_created(user)
|
|
481
|
+
except Exception:
|
|
482
|
+
raise OperationError("user_created_effect_failed", 500) from None
|
|
483
|
+
|
|
484
|
+
async def signup(self, email: str, password: str, invite_code: str = "") -> Tokens:
|
|
485
|
+
email = normalize_email(email)
|
|
486
|
+
validate_password(password)
|
|
487
|
+
if not isinstance(invite_code, str):
|
|
488
|
+
raise OperationError("invalid_input", 400)
|
|
489
|
+
await self._rate_limit("signup", email)
|
|
490
|
+
if self.signup_policy == "invite-only":
|
|
491
|
+
await self._check_invite(self.db, email, invite_code)
|
|
492
|
+
password_hash = hash_password(password, self._kdf)
|
|
493
|
+
|
|
494
|
+
async def work(port: DatabasePort) -> tuple[Tokens, AuthUser]:
|
|
495
|
+
db = self.create_database(port)
|
|
496
|
+
invite = await self._lock_invite(db, email, invite_code)
|
|
497
|
+
user = await db.users.insert(
|
|
498
|
+
{"email": email, "password_hash": password_hash}
|
|
499
|
+
)
|
|
500
|
+
if invite is not None:
|
|
501
|
+
await db.invites.update(
|
|
502
|
+
{"id": invite.id},
|
|
503
|
+
{"redeemed_at": self._timestamp(), "redeemed_by": user.id},
|
|
504
|
+
)
|
|
505
|
+
public = await self._creating(port, user)
|
|
506
|
+
return await self._issue(db, user), public
|
|
507
|
+
|
|
508
|
+
try:
|
|
509
|
+
tokens, public = await self.port.transaction(work)
|
|
510
|
+
except Exception as error:
|
|
511
|
+
if _unique(error):
|
|
512
|
+
raise OperationError("account_exists", 409) from None
|
|
513
|
+
raise
|
|
514
|
+
await self._created(public)
|
|
515
|
+
self._schedule_cleanup()
|
|
516
|
+
return tokens
|
|
517
|
+
|
|
518
|
+
async def signin(self, email: str, password: str) -> Tokens:
|
|
519
|
+
email = normalize_email(email)
|
|
520
|
+
validate_password(password)
|
|
521
|
+
await self._rate_limit("signin", email)
|
|
522
|
+
users = await self.db.users.find_many(
|
|
523
|
+
where=_filter(self.db.users, "email", "=", email), limit=1
|
|
524
|
+
)
|
|
525
|
+
user = users[0] if users else None
|
|
526
|
+
matched = verify_password(
|
|
527
|
+
password, user.password_hash if user is not None else None, self._kdf
|
|
528
|
+
)
|
|
529
|
+
if not matched or user is None or user.disabled_at is not None:
|
|
530
|
+
raise OperationError("invalid_credentials", 401)
|
|
531
|
+
|
|
532
|
+
async def issue(port: DatabasePort) -> Tokens:
|
|
533
|
+
return await self._issue(self.create_database(port), user)
|
|
534
|
+
|
|
535
|
+
result = await self.port.transaction(issue)
|
|
536
|
+
self._schedule_cleanup()
|
|
537
|
+
return result
|
|
538
|
+
|
|
539
|
+
async def signin_identity(
|
|
540
|
+
self, provider_id: str, credential: object, invite_code: str = ""
|
|
541
|
+
) -> Tokens:
|
|
542
|
+
if not isinstance(invite_code, str):
|
|
543
|
+
raise OperationError("invalid_input", 400)
|
|
544
|
+
provider = self.providers.get(provider_id)
|
|
545
|
+
if provider is None:
|
|
546
|
+
raise OperationError("unsupported_identity_provider", 400)
|
|
547
|
+
await self._rate_limit("identity_attempt", provider_id, 100, 60)
|
|
548
|
+
try:
|
|
549
|
+
identity = await provider.verify(credential)
|
|
550
|
+
except Exception:
|
|
551
|
+
raise OperationError("invalid_credentials", 401) from None
|
|
552
|
+
email = normalize_email(identity.verified_email)
|
|
553
|
+
if (
|
|
554
|
+
not isinstance(identity.subject, str)
|
|
555
|
+
or not identity.subject
|
|
556
|
+
or len(identity.subject) > 2048
|
|
557
|
+
):
|
|
558
|
+
raise OperationError("invalid_credentials", 401)
|
|
559
|
+
await self._rate_limit("identity", provider_id + ":" + identity.subject)
|
|
560
|
+
key = {"provider": provider_id, "subject": identity.subject}
|
|
561
|
+
if (
|
|
562
|
+
self.signup_policy == "invite-only"
|
|
563
|
+
and await self.db.identities.find_by_id(key) is None
|
|
564
|
+
):
|
|
565
|
+
await self._rate_limit("signup", email)
|
|
566
|
+
await self._check_invite(self.db, email, invite_code)
|
|
567
|
+
|
|
568
|
+
async def work(port: DatabasePort) -> tuple[Tokens, AuthUser | None]:
|
|
569
|
+
db = self.create_database(port)
|
|
570
|
+
stored = await db.identities.find_by_id(key)
|
|
571
|
+
invite = (
|
|
572
|
+
await self._lock_invite(db, email, invite_code)
|
|
573
|
+
if stored is None
|
|
574
|
+
else None
|
|
575
|
+
)
|
|
576
|
+
user = (
|
|
577
|
+
await db.users.find_by_id({"id": stored.user_id})
|
|
578
|
+
if stored is not None
|
|
579
|
+
else await db.users.insert({"email": email, "password_hash": None})
|
|
580
|
+
)
|
|
581
|
+
if user is None or user.disabled_at is not None:
|
|
582
|
+
raise OperationError("invalid_credentials", 401)
|
|
583
|
+
public = None
|
|
584
|
+
if stored is None:
|
|
585
|
+
if invite is not None:
|
|
586
|
+
await db.invites.update(
|
|
587
|
+
{"id": invite.id},
|
|
588
|
+
{"redeemed_at": self._timestamp(), "redeemed_by": user.id},
|
|
589
|
+
)
|
|
590
|
+
await db.identities.insert({**key, "user_id": user.id})
|
|
591
|
+
public = await self._creating(port, user)
|
|
592
|
+
return await self._issue(db, user), public
|
|
593
|
+
|
|
594
|
+
try:
|
|
595
|
+
tokens, public = await self.port.transaction(work)
|
|
596
|
+
except Exception as error:
|
|
597
|
+
if _unique(error):
|
|
598
|
+
raise OperationError("identity_conflict", 409) from None
|
|
599
|
+
raise
|
|
600
|
+
if public is not None:
|
|
601
|
+
await self._created(public)
|
|
602
|
+
self._schedule_cleanup()
|
|
603
|
+
return tokens
|
|
604
|
+
|
|
605
|
+
async def _validate_session(
|
|
606
|
+
self, db: AuthDatabase, record: SessionRecord | None
|
|
607
|
+
) -> _SessionResult:
|
|
608
|
+
if (
|
|
609
|
+
record is None
|
|
610
|
+
or record.transport != "native"
|
|
611
|
+
or record.revoked_at is not None
|
|
612
|
+
):
|
|
613
|
+
raise OperationError("invalid_token", 401)
|
|
614
|
+
user = await self._lock_user(db, record)
|
|
615
|
+
instant = self.now()
|
|
616
|
+
family = await self._family_expiry(db, record)
|
|
617
|
+
if (
|
|
618
|
+
user is None
|
|
619
|
+
or parse_timestamp(record.expires_at) <= instant
|
|
620
|
+
or family is None
|
|
621
|
+
or family <= instant
|
|
622
|
+
):
|
|
623
|
+
raise OperationError("invalid_token", 401)
|
|
624
|
+
return _SessionResult(
|
|
625
|
+
Session(record.id, User(user.id, user.email)),
|
|
626
|
+
format_timestamp(min(parse_timestamp(record.expires_at), family)),
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
async def session(self, access_token: str) -> _SessionResult:
|
|
630
|
+
_validate_token(access_token)
|
|
631
|
+
|
|
632
|
+
async def read(port: DatabasePort) -> _SessionResult:
|
|
633
|
+
db = self.create_database(port)
|
|
634
|
+
record = await self._lock_session(db, access_token)
|
|
635
|
+
return await self._validate_session(db, record)
|
|
636
|
+
|
|
637
|
+
return await self.port.transaction(read)
|
|
638
|
+
|
|
639
|
+
async def _lock_session(
|
|
640
|
+
self, db: AuthDatabase, access: str
|
|
641
|
+
) -> SessionRecord | None:
|
|
642
|
+
rows = await db.sessions.find_many(
|
|
643
|
+
where=_filter(db.sessions, "token_hash", "=", hash_token(access)), limit=1
|
|
644
|
+
)
|
|
645
|
+
if not rows:
|
|
646
|
+
return None
|
|
647
|
+
return await db.sessions.update_if(
|
|
648
|
+
{"id": rows[0].id},
|
|
649
|
+
and_(
|
|
650
|
+
_filter(db.sessions, "token_hash", "=", hash_token(access)),
|
|
651
|
+
_filter(db.sessions, "revoked_at", "is null"),
|
|
652
|
+
_filter(db.sessions, "transport", "=", "native"),
|
|
653
|
+
),
|
|
654
|
+
{"revoked_at": None},
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
async def logout(self, access_token: str) -> None:
|
|
658
|
+
session = (await self.session(access_token)).session
|
|
659
|
+
await self.db.sessions.update_if(
|
|
660
|
+
{"id": session.id},
|
|
661
|
+
_filter(self.db.sessions, "revoked_at", "is null"),
|
|
662
|
+
{"revoked_at": self._timestamp()},
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
async def refresh(self, refresh_token: str) -> Tokens:
|
|
666
|
+
_validate_token(refresh_token)
|
|
667
|
+
rows = await self.db.refresh_tokens.find_many(
|
|
668
|
+
where=_filter(
|
|
669
|
+
self.db.refresh_tokens, "token_hash", "=", hash_token(refresh_token)
|
|
670
|
+
),
|
|
671
|
+
limit=1,
|
|
672
|
+
)
|
|
673
|
+
if not rows:
|
|
674
|
+
raise OperationError("invalid_token", 401)
|
|
675
|
+
stored = rows[0]
|
|
676
|
+
|
|
677
|
+
async def consume(port: DatabasePort) -> Tokens | None:
|
|
678
|
+
db = self.create_database(port)
|
|
679
|
+
session = await db.sessions.update_if(
|
|
680
|
+
{"id": stored.session_id},
|
|
681
|
+
and_(
|
|
682
|
+
_filter(db.sessions, "revoked_at", "is null"),
|
|
683
|
+
_filter(db.sessions, "transport", "=", "native"),
|
|
684
|
+
),
|
|
685
|
+
{"revoked_at": None},
|
|
686
|
+
)
|
|
687
|
+
if session is None or session.transport != "native":
|
|
688
|
+
return None
|
|
689
|
+
current = await db.refresh_tokens.find_by_id({"id": stored.id})
|
|
690
|
+
user = await self._lock_user(db, session)
|
|
691
|
+
instant = self.now()
|
|
692
|
+
stamp = format_timestamp(instant)
|
|
693
|
+
family = await self._family_expiry(db, session)
|
|
694
|
+
if (
|
|
695
|
+
current is None
|
|
696
|
+
or current.consumed_at is not None
|
|
697
|
+
or parse_timestamp(current.expires_at) <= instant
|
|
698
|
+
or user is None
|
|
699
|
+
or family is None
|
|
700
|
+
or family <= instant
|
|
701
|
+
):
|
|
702
|
+
await db.sessions.update({"id": session.id}, {"revoked_at": stamp})
|
|
703
|
+
return None
|
|
704
|
+
consumed = await db.refresh_tokens.update_if(
|
|
705
|
+
{"id": current.id},
|
|
706
|
+
_filter(db.refresh_tokens, "consumed_at", "is null"),
|
|
707
|
+
{"consumed_at": stamp},
|
|
708
|
+
)
|
|
709
|
+
if consumed is None:
|
|
710
|
+
await db.sessions.update({"id": session.id}, {"revoked_at": stamp})
|
|
711
|
+
return None
|
|
712
|
+
access, refresh = random_token(), random_token()
|
|
713
|
+
expiry = format_timestamp(instant + timedelta(seconds=900))
|
|
714
|
+
first = session.first_login_at or session.created_at
|
|
715
|
+
renewed = format_timestamp(
|
|
716
|
+
self._renewed_expiry(parse_timestamp(first), instant)
|
|
717
|
+
)
|
|
718
|
+
await db.sessions.update(
|
|
719
|
+
{"id": session.id},
|
|
720
|
+
{
|
|
721
|
+
"token_hash": hash_token(access),
|
|
722
|
+
"expires_at": expiry,
|
|
723
|
+
"first_login_at": first,
|
|
724
|
+
"last_renewed_at": stamp,
|
|
725
|
+
},
|
|
726
|
+
)
|
|
727
|
+
await db.refresh_tokens.insert(
|
|
728
|
+
{
|
|
729
|
+
"session_id": session.id,
|
|
730
|
+
"token_hash": hash_token(refresh),
|
|
731
|
+
"expires_at": renewed,
|
|
732
|
+
"created_at": stamp,
|
|
733
|
+
}
|
|
734
|
+
)
|
|
735
|
+
return Tokens(access, refresh, expiry, renewed, user.id, session.id)
|
|
736
|
+
|
|
737
|
+
outcome = await self.port.transaction(consume)
|
|
738
|
+
if outcome is None:
|
|
739
|
+
raise OperationError("session_revoked", 401)
|
|
740
|
+
self._schedule_cleanup()
|
|
741
|
+
return outcome
|
|
742
|
+
|
|
743
|
+
async def _check_invite(
|
|
744
|
+
self, db: AuthDatabase, email: str, code: str
|
|
745
|
+
) -> InviteRecord:
|
|
746
|
+
if not code:
|
|
747
|
+
raise OperationError("invite_required", 403)
|
|
748
|
+
if not _canonical(code):
|
|
749
|
+
raise OperationError("invite_invalid", 403)
|
|
750
|
+
rows = await db.invites.find_many(
|
|
751
|
+
where=_filter(db.invites, "code_hash", "=", hash_token(code)), limit=1
|
|
752
|
+
)
|
|
753
|
+
row = rows[0] if rows else None
|
|
754
|
+
if (
|
|
755
|
+
row is None
|
|
756
|
+
or row.email != email
|
|
757
|
+
or row.redeemed_at is not None
|
|
758
|
+
or row.redeemed_by is not None
|
|
759
|
+
or row.revoked_at is not None
|
|
760
|
+
or parse_timestamp(row.expires_at) <= self.now()
|
|
761
|
+
):
|
|
762
|
+
raise OperationError("invite_invalid", 403)
|
|
763
|
+
return row
|
|
764
|
+
|
|
765
|
+
async def _lock_invite(
|
|
766
|
+
self, db: AuthDatabase, email: str, code: str
|
|
767
|
+
) -> InviteRecord | None:
|
|
768
|
+
if self.signup_policy != "invite-only":
|
|
769
|
+
return None
|
|
770
|
+
row = await self._check_invite(db, email, code)
|
|
771
|
+
locked = await db.invites.update_if(
|
|
772
|
+
{"id": row.id},
|
|
773
|
+
and_(
|
|
774
|
+
_filter(db.invites, "code_hash", "=", hash_token(code)),
|
|
775
|
+
_filter(db.invites, "email", "=", email),
|
|
776
|
+
_filter(db.invites, "redeemed_at", "is null"),
|
|
777
|
+
_filter(db.invites, "redeemed_by", "is null"),
|
|
778
|
+
_filter(db.invites, "revoked_at", "is null"),
|
|
779
|
+
_filter(db.invites, "expires_at", "=", row.expires_at),
|
|
780
|
+
_filter(db.invites, "expires_at", ">", self._timestamp()),
|
|
781
|
+
),
|
|
782
|
+
{"expires_at": row.expires_at},
|
|
783
|
+
)
|
|
784
|
+
if locked is None or parse_timestamp(locked.expires_at) <= self.now():
|
|
785
|
+
raise OperationError("invite_invalid", 403)
|
|
786
|
+
return locked
|
|
787
|
+
|
|
788
|
+
async def _rate_limit(
|
|
789
|
+
self, action: str, value: str, maximum: int = 10, window: int = 900
|
|
790
|
+
) -> None:
|
|
791
|
+
key = {"action": action, "key_hash": hash_token(value)}
|
|
792
|
+
for _ in range(4):
|
|
793
|
+
row = await self.db.rate_limits.find_by_id(key)
|
|
794
|
+
expires = self._timestamp(window)
|
|
795
|
+
if row is None:
|
|
796
|
+
try:
|
|
797
|
+
await self.db.rate_limits.insert(
|
|
798
|
+
{**key, "attempt_count": 1, "expires_at": expires}
|
|
799
|
+
)
|
|
800
|
+
return
|
|
801
|
+
except Exception as error:
|
|
802
|
+
if not _unique(error):
|
|
803
|
+
raise
|
|
804
|
+
continue
|
|
805
|
+
expired = parse_timestamp(row.expires_at) <= self.now()
|
|
806
|
+
if not expired and row.attempt_count >= maximum:
|
|
807
|
+
raise OperationError("rate_limited", 429)
|
|
808
|
+
updated = await self.db.rate_limits.update_if(
|
|
809
|
+
key,
|
|
810
|
+
and_(
|
|
811
|
+
_filter(
|
|
812
|
+
self.db.rate_limits, "attempt_count", "=", row.attempt_count
|
|
813
|
+
),
|
|
814
|
+
_filter(self.db.rate_limits, "expires_at", "=", row.expires_at),
|
|
815
|
+
),
|
|
816
|
+
{
|
|
817
|
+
"attempt_count": 1 if expired else row.attempt_count + 1,
|
|
818
|
+
"expires_at": expires if expired else row.expires_at,
|
|
819
|
+
},
|
|
820
|
+
)
|
|
821
|
+
if updated is not None:
|
|
822
|
+
return
|
|
823
|
+
raise OperationError("rate_limited", 429)
|
|
824
|
+
|
|
825
|
+
async def _manage(
|
|
826
|
+
self, access: str, work: Callable[[AuthDatabase, Session], Awaitable[T]]
|
|
827
|
+
) -> T:
|
|
828
|
+
if self.signup_policy != "invite-only":
|
|
829
|
+
raise OperationError("not_found", 404)
|
|
830
|
+
_validate_token(access)
|
|
831
|
+
|
|
832
|
+
async def run(port: DatabasePort) -> T:
|
|
833
|
+
db = self.create_database(port)
|
|
834
|
+
session = await self._lock_session(db, access)
|
|
835
|
+
actor = (await self._validate_session(db, session)).session
|
|
836
|
+
if self.hooks.invite_managing is None:
|
|
837
|
+
raise OperationError("permission_denied", 403)
|
|
838
|
+
if self.project_id is None:
|
|
839
|
+
raise OperationError("service_unavailable", 503)
|
|
840
|
+
try:
|
|
841
|
+
project = _invite_id(self.project_id)
|
|
842
|
+
except OperationError:
|
|
843
|
+
raise OperationError("service_unavailable", 503) from None
|
|
844
|
+
try:
|
|
845
|
+
await self.hooks.invite_managing(port, actor, project)
|
|
846
|
+
except OperationError:
|
|
847
|
+
raise
|
|
848
|
+
except Exception:
|
|
849
|
+
raise OperationError("permission_denied", 403) from None
|
|
850
|
+
return await work(db, actor)
|
|
851
|
+
|
|
852
|
+
result = await self.port.transaction(run)
|
|
853
|
+
self._schedule_cleanup(invites_only=True)
|
|
854
|
+
return result
|
|
855
|
+
|
|
856
|
+
def _summary(self, row: InviteRecord) -> dict[str, str]:
|
|
857
|
+
if (row.redeemed_at is None) != (row.redeemed_by is None) or (
|
|
858
|
+
row.redeemed_at is not None and row.revoked_at is not None
|
|
859
|
+
):
|
|
860
|
+
raise OperationError("operation_failed", 500)
|
|
861
|
+
status = (
|
|
862
|
+
"redeemed"
|
|
863
|
+
if row.redeemed_at is not None
|
|
864
|
+
else "revoked"
|
|
865
|
+
if row.revoked_at is not None
|
|
866
|
+
else "expired"
|
|
867
|
+
if parse_timestamp(row.expires_at) <= self.now()
|
|
868
|
+
else "issued"
|
|
869
|
+
)
|
|
870
|
+
return {
|
|
871
|
+
"id": row.id,
|
|
872
|
+
"email": row.email,
|
|
873
|
+
"status": status,
|
|
874
|
+
"created_at": row.created_at,
|
|
875
|
+
"expires_at": row.expires_at,
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
async def invite_issue(self, access: str, id: str, email: str) -> Mapping[str, str]:
|
|
879
|
+
id, email = _invite_id(id), normalize_email(email)
|
|
880
|
+
|
|
881
|
+
async def issue(db: AuthDatabase, actor: Session) -> Mapping[str, str]:
|
|
882
|
+
if await db.invites.find_by_id({"id": id}) is not None:
|
|
883
|
+
raise OperationError("invite_issue_replayed", 409)
|
|
884
|
+
code = random_token()
|
|
885
|
+
issued = self.now()
|
|
886
|
+
row = await db.invites.insert(
|
|
887
|
+
{
|
|
888
|
+
"id": id,
|
|
889
|
+
"email": email,
|
|
890
|
+
"code_hash": hash_token(code),
|
|
891
|
+
"issued_by": actor.user.id,
|
|
892
|
+
"created_at": format_timestamp(issued),
|
|
893
|
+
"expires_at": format_timestamp(issued + timedelta(days=7)),
|
|
894
|
+
}
|
|
895
|
+
)
|
|
896
|
+
return {**self._summary(row), "code": code}
|
|
897
|
+
|
|
898
|
+
try:
|
|
899
|
+
return await self._manage(access, issue)
|
|
900
|
+
except Exception as error:
|
|
901
|
+
if (
|
|
902
|
+
_unique(error)
|
|
903
|
+
and await self.db.invites.find_by_id({"id": id}) is not None
|
|
904
|
+
):
|
|
905
|
+
raise OperationError("invite_issue_replayed", 409) from None
|
|
906
|
+
raise
|
|
907
|
+
|
|
908
|
+
async def invite_list(self, access: str, cursor: str) -> Mapping[str, object]:
|
|
909
|
+
after: tuple[str, str] | None = None
|
|
910
|
+
if not isinstance(cursor, str):
|
|
911
|
+
raise OperationError("invalid_input", 400)
|
|
912
|
+
if cursor:
|
|
913
|
+
try:
|
|
914
|
+
if len(cursor) > 512 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
|
915
|
+
raise ValueError
|
|
916
|
+
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
|
917
|
+
if base64.urlsafe_b64encode(raw).decode().rstrip("=") != cursor:
|
|
918
|
+
raise ValueError
|
|
919
|
+
value: object = json.loads(raw)
|
|
920
|
+
if (
|
|
921
|
+
not isinstance(value, list)
|
|
922
|
+
or len(value) != 2
|
|
923
|
+
or not isinstance(value[0], str)
|
|
924
|
+
or not isinstance(value[1], str)
|
|
925
|
+
or format_timestamp(parse_timestamp(value[0])) != value[0]
|
|
926
|
+
):
|
|
927
|
+
raise ValueError
|
|
928
|
+
after = value[0], _invite_id(value[1])
|
|
929
|
+
except (ValueError, OperationError):
|
|
930
|
+
raise OperationError("invalid_input", 400) from None
|
|
931
|
+
|
|
932
|
+
async def page(db: AuthDatabase, actor: Session) -> Mapping[str, object]:
|
|
933
|
+
where = (
|
|
934
|
+
None
|
|
935
|
+
if after is None
|
|
936
|
+
else or_(
|
|
937
|
+
_filter(db.invites, "created_at", ">", after[0]),
|
|
938
|
+
and_(
|
|
939
|
+
_filter(db.invites, "created_at", "=", after[0]),
|
|
940
|
+
_filter(db.invites, "id", ">", after[1]),
|
|
941
|
+
),
|
|
942
|
+
)
|
|
943
|
+
)
|
|
944
|
+
rows = await db.invites.find_many(
|
|
945
|
+
where=where,
|
|
946
|
+
order_by=(
|
|
947
|
+
Order(db.invites.table.columns["created_at"], "asc"),
|
|
948
|
+
Order(db.invites.table.columns["id"], "asc"),
|
|
949
|
+
),
|
|
950
|
+
limit=51,
|
|
951
|
+
)
|
|
952
|
+
next_cursor = ""
|
|
953
|
+
if len(rows) > 50:
|
|
954
|
+
last = rows[49]
|
|
955
|
+
raw = json.dumps(
|
|
956
|
+
[last.created_at, last.id], separators=(",", ":")
|
|
957
|
+
).encode()
|
|
958
|
+
next_cursor = base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
|
959
|
+
return {
|
|
960
|
+
"items": [self._summary(row) for row in rows[:50]],
|
|
961
|
+
"next_cursor": next_cursor,
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
return await self._manage(access, page)
|
|
965
|
+
|
|
966
|
+
async def invite_revoke(self, access: str, id: str) -> Mapping[str, str]:
|
|
967
|
+
id = _invite_id(id)
|
|
968
|
+
|
|
969
|
+
async def revoke(db: AuthDatabase, actor: Session) -> Mapping[str, str]:
|
|
970
|
+
candidate = await db.invites.find_by_id({"id": id})
|
|
971
|
+
if candidate is None:
|
|
972
|
+
raise OperationError("not_found", 404)
|
|
973
|
+
row = await db.invites.update_if(
|
|
974
|
+
{"id": id},
|
|
975
|
+
_filter(db.invites, "expires_at", "=", candidate.expires_at),
|
|
976
|
+
{"expires_at": candidate.expires_at},
|
|
977
|
+
)
|
|
978
|
+
if row is None:
|
|
979
|
+
raise OperationError("not_found", 404)
|
|
980
|
+
status = self._summary(row)["status"]
|
|
981
|
+
if status == "redeemed":
|
|
982
|
+
raise OperationError("invite_already_redeemed", 409)
|
|
983
|
+
if status == "issued":
|
|
984
|
+
await db.invites.update({"id": id}, {"revoked_at": self._timestamp()})
|
|
985
|
+
status = "revoked"
|
|
986
|
+
return {"id": id, "status": status}
|
|
987
|
+
|
|
988
|
+
return await self._manage(access, revoke)
|
|
989
|
+
|
|
990
|
+
def _cleanup_failure(self, stage: str) -> None:
|
|
991
|
+
context = self.cleanup_context
|
|
992
|
+
if context is not None and context.failure is not None:
|
|
993
|
+
try:
|
|
994
|
+
context.failure(stage)
|
|
995
|
+
except Exception:
|
|
996
|
+
pass
|
|
997
|
+
|
|
998
|
+
def _schedule_cleanup(self, invites_only: bool = False) -> None:
|
|
999
|
+
context = self.cleanup_context
|
|
1000
|
+
if context is None:
|
|
1001
|
+
return
|
|
1002
|
+
|
|
1003
|
+
async def run() -> None:
|
|
1004
|
+
port: ClosablePort | None = None
|
|
1005
|
+
try:
|
|
1006
|
+
async with asyncio.timeout(5):
|
|
1007
|
+
port = context.create_port()
|
|
1008
|
+
await self._cleanup(port, invites_only)
|
|
1009
|
+
except Exception:
|
|
1010
|
+
self._cleanup_failure("port")
|
|
1011
|
+
finally:
|
|
1012
|
+
if port is not None:
|
|
1013
|
+
try:
|
|
1014
|
+
async with asyncio.timeout(5):
|
|
1015
|
+
await port.close()
|
|
1016
|
+
except BaseException as error:
|
|
1017
|
+
port.terminate()
|
|
1018
|
+
self._cleanup_failure("close")
|
|
1019
|
+
if isinstance(error, asyncio.CancelledError):
|
|
1020
|
+
raise
|
|
1021
|
+
|
|
1022
|
+
work = run()
|
|
1023
|
+
try:
|
|
1024
|
+
context.wait_until(work)
|
|
1025
|
+
except Exception:
|
|
1026
|
+
work.close()
|
|
1027
|
+
self._cleanup_failure("schedule")
|
|
1028
|
+
|
|
1029
|
+
def _cleanup_start(self) -> str:
|
|
1030
|
+
return str(UUID(bytes=secrets.token_bytes(16), version=4))
|
|
1031
|
+
|
|
1032
|
+
async def _cleanup(self, port: DatabasePort, invites_only: bool) -> None:
|
|
1033
|
+
db = self.create_database(port)
|
|
1034
|
+
cutoff = self._timestamp()
|
|
1035
|
+
stage = "refresh"
|
|
1036
|
+
try:
|
|
1037
|
+
if not invites_only:
|
|
1038
|
+
instant = parse_timestamp(cutoff)
|
|
1039
|
+
idle_cutoff = format_timestamp(
|
|
1040
|
+
instant - timedelta(seconds=self.idle_timeout_seconds)
|
|
1041
|
+
)
|
|
1042
|
+
candidates = [
|
|
1043
|
+
_filter(db.sessions, "revoked_at", "is not null"),
|
|
1044
|
+
and_(
|
|
1045
|
+
_filter(db.sessions, "last_renewed_at", "is not null"),
|
|
1046
|
+
_filter(db.sessions, "last_renewed_at", "<=", idle_cutoff),
|
|
1047
|
+
),
|
|
1048
|
+
and_(
|
|
1049
|
+
_filter(db.sessions, "last_renewed_at", "is null"),
|
|
1050
|
+
or_(
|
|
1051
|
+
_filter(db.sessions, "expires_at", "<=", idle_cutoff),
|
|
1052
|
+
_filter(
|
|
1053
|
+
db.sessions,
|
|
1054
|
+
"created_at",
|
|
1055
|
+
"<",
|
|
1056
|
+
format_timestamp(instant - timedelta(days=7)),
|
|
1057
|
+
),
|
|
1058
|
+
),
|
|
1059
|
+
),
|
|
1060
|
+
]
|
|
1061
|
+
if self.absolute_lifetime_seconds:
|
|
1062
|
+
absolute_cutoff = format_timestamp(
|
|
1063
|
+
instant - timedelta(seconds=self.absolute_lifetime_seconds)
|
|
1064
|
+
)
|
|
1065
|
+
candidates.append(
|
|
1066
|
+
or_(
|
|
1067
|
+
_filter(
|
|
1068
|
+
db.sessions, "first_login_at", "<=", absolute_cutoff
|
|
1069
|
+
),
|
|
1070
|
+
and_(
|
|
1071
|
+
_filter(db.sessions, "first_login_at", "is null"),
|
|
1072
|
+
_filter(
|
|
1073
|
+
db.sessions, "created_at", "<=", absolute_cutoff
|
|
1074
|
+
),
|
|
1075
|
+
),
|
|
1076
|
+
)
|
|
1077
|
+
)
|
|
1078
|
+
eligible = and_(
|
|
1079
|
+
_filter(db.sessions, "transport", "=", "native"),
|
|
1080
|
+
or_(*candidates),
|
|
1081
|
+
)
|
|
1082
|
+
start = self._cleanup_start()
|
|
1083
|
+
order = (Order(db.sessions.table.columns["id"], "asc"),)
|
|
1084
|
+
sessions = list(
|
|
1085
|
+
await db.sessions.find_many(
|
|
1086
|
+
where=and_(eligible, _filter(db.sessions, "id", ">=", start)),
|
|
1087
|
+
limit=32,
|
|
1088
|
+
order_by=order,
|
|
1089
|
+
)
|
|
1090
|
+
)
|
|
1091
|
+
if len(sessions) < 32:
|
|
1092
|
+
sessions.extend(
|
|
1093
|
+
await db.sessions.find_many(
|
|
1094
|
+
where=and_(
|
|
1095
|
+
eligible, _filter(db.sessions, "id", "<", start)
|
|
1096
|
+
),
|
|
1097
|
+
limit=32 - len(sessions),
|
|
1098
|
+
order_by=order,
|
|
1099
|
+
)
|
|
1100
|
+
)
|
|
1101
|
+
refresh_attempts = 0
|
|
1102
|
+
for session in sessions:
|
|
1103
|
+
|
|
1104
|
+
async def delete_family(
|
|
1105
|
+
tx_port: DatabasePort, candidate: SessionRecord = session
|
|
1106
|
+
) -> None:
|
|
1107
|
+
nonlocal refresh_attempts
|
|
1108
|
+
tx = self.create_database(tx_port)
|
|
1109
|
+
locked = await tx.sessions.update_if(
|
|
1110
|
+
{"id": candidate.id},
|
|
1111
|
+
_filter(tx.sessions, "transport", "=", "native"),
|
|
1112
|
+
{"transport": "native"},
|
|
1113
|
+
)
|
|
1114
|
+
if locked is None:
|
|
1115
|
+
return
|
|
1116
|
+
checked = self.now()
|
|
1117
|
+
if locked.revoked_at is None:
|
|
1118
|
+
family = await self._family_expiry(tx, locked)
|
|
1119
|
+
if family is None or family > checked:
|
|
1120
|
+
return
|
|
1121
|
+
await tx.sessions.update(
|
|
1122
|
+
{"id": locked.id},
|
|
1123
|
+
{"revoked_at": format_timestamp(checked)},
|
|
1124
|
+
)
|
|
1125
|
+
if refresh_attempts < 32:
|
|
1126
|
+
refresh = await tx.refresh_tokens.find_many(
|
|
1127
|
+
where=_filter(
|
|
1128
|
+
tx.refresh_tokens, "session_id", "=", locked.id
|
|
1129
|
+
),
|
|
1130
|
+
limit=32 - refresh_attempts,
|
|
1131
|
+
order_by=(
|
|
1132
|
+
Order(
|
|
1133
|
+
tx.refresh_tokens.table.columns["created_at"],
|
|
1134
|
+
"asc",
|
|
1135
|
+
),
|
|
1136
|
+
Order(tx.refresh_tokens.table.columns["id"], "asc"),
|
|
1137
|
+
),
|
|
1138
|
+
)
|
|
1139
|
+
for row in refresh:
|
|
1140
|
+
refresh_attempts += 1
|
|
1141
|
+
await tx.refresh_tokens.delete({"id": row.id})
|
|
1142
|
+
if not await tx.refresh_tokens.find_many(
|
|
1143
|
+
where=_filter(
|
|
1144
|
+
tx.refresh_tokens, "session_id", "=", locked.id
|
|
1145
|
+
),
|
|
1146
|
+
limit=1,
|
|
1147
|
+
):
|
|
1148
|
+
await tx.sessions.delete({"id": locked.id})
|
|
1149
|
+
|
|
1150
|
+
await port.transaction(delete_family)
|
|
1151
|
+
stage = "rate_limit"
|
|
1152
|
+
limits = await db.rate_limits.find_many(
|
|
1153
|
+
where=_filter(db.rate_limits, "expires_at", "<=", cutoff),
|
|
1154
|
+
limit=32,
|
|
1155
|
+
order_by=(
|
|
1156
|
+
Order(db.rate_limits.table.columns["expires_at"], "asc"),
|
|
1157
|
+
Order(db.rate_limits.table.columns["action"], "asc"),
|
|
1158
|
+
Order(db.rate_limits.table.columns["key_hash"], "asc"),
|
|
1159
|
+
),
|
|
1160
|
+
)
|
|
1161
|
+
for limit in limits:
|
|
1162
|
+
|
|
1163
|
+
async def delete_limit(
|
|
1164
|
+
tx_port: DatabasePort, candidate: RateLimitRecord = limit
|
|
1165
|
+
) -> None:
|
|
1166
|
+
tx = self.create_database(tx_port)
|
|
1167
|
+
key = {
|
|
1168
|
+
"action": candidate.action,
|
|
1169
|
+
"key_hash": candidate.key_hash,
|
|
1170
|
+
}
|
|
1171
|
+
locked = await tx.rate_limits.update_if(
|
|
1172
|
+
key,
|
|
1173
|
+
and_(
|
|
1174
|
+
_filter(
|
|
1175
|
+
tx.rate_limits,
|
|
1176
|
+
"expires_at",
|
|
1177
|
+
"=",
|
|
1178
|
+
candidate.expires_at,
|
|
1179
|
+
),
|
|
1180
|
+
_filter(
|
|
1181
|
+
tx.rate_limits,
|
|
1182
|
+
"attempt_count",
|
|
1183
|
+
"=",
|
|
1184
|
+
candidate.attempt_count,
|
|
1185
|
+
),
|
|
1186
|
+
_filter(tx.rate_limits, "expires_at", "<=", cutoff),
|
|
1187
|
+
),
|
|
1188
|
+
{"attempt_count": candidate.attempt_count},
|
|
1189
|
+
)
|
|
1190
|
+
if locked is not None:
|
|
1191
|
+
await tx.rate_limits.delete(key)
|
|
1192
|
+
|
|
1193
|
+
await port.transaction(delete_limit)
|
|
1194
|
+
except Exception:
|
|
1195
|
+
self._cleanup_failure(stage)
|
|
1196
|
+
try:
|
|
1197
|
+
cutoff_invite = self._timestamp(-30 * 86400)
|
|
1198
|
+
invites = await db.invites.find_many(
|
|
1199
|
+
where=_filter(db.invites, "expires_at", "<=", cutoff_invite),
|
|
1200
|
+
limit=32,
|
|
1201
|
+
order_by=(
|
|
1202
|
+
Order(db.invites.table.columns["expires_at"], "asc"),
|
|
1203
|
+
Order(db.invites.table.columns["id"], "asc"),
|
|
1204
|
+
),
|
|
1205
|
+
)
|
|
1206
|
+
for invite in invites:
|
|
1207
|
+
|
|
1208
|
+
async def delete_invite(
|
|
1209
|
+
tx_port: DatabasePort, candidate: InviteRecord = invite
|
|
1210
|
+
) -> None:
|
|
1211
|
+
tx = self.create_database(tx_port)
|
|
1212
|
+
locked = await tx.invites.update_if(
|
|
1213
|
+
{"id": candidate.id},
|
|
1214
|
+
and_(
|
|
1215
|
+
_filter(
|
|
1216
|
+
tx.invites, "expires_at", "=", candidate.expires_at
|
|
1217
|
+
),
|
|
1218
|
+
_filter(tx.invites, "expires_at", "<=", cutoff_invite),
|
|
1219
|
+
),
|
|
1220
|
+
{"expires_at": candidate.expires_at},
|
|
1221
|
+
)
|
|
1222
|
+
if locked is not None:
|
|
1223
|
+
await tx.invites.delete({"id": locked.id})
|
|
1224
|
+
|
|
1225
|
+
await port.transaction(delete_invite)
|
|
1226
|
+
except Exception:
|
|
1227
|
+
self._cleanup_failure("invite")
|