Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_identity.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_identity.py · 30.0 KB · 953 lines
1"""File-backed identity sessions for DBBASIC permission checks."""
2
3from __future__ import annotations
4
5import csv
6import hashlib
7import hmac
8import json
9import re
10import secrets
11import threading
12from dataclasses import dataclass, replace
13from datetime import datetime, timedelta, timezone
14from pathlib import Path
15from typing import Any, Iterable, Mapping
16
17import object_ids
18import object_permissions
19from object_versions import DEFAULT_DATA_DIR
20
21IDENTITY_DIR = "identity"
22SESSIONS_FILE = "sessions.tsv"
23ACCOUNTS_FILE = "accounts.tsv"
24USERS_FILE = "users.tsv"
25DEFAULT_SESSION_TTL_SECONDS = 24 * 60 * 60
26MAX_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
27ACTIVE_STATUS = "active"
28DISABLED_STATUS = "disabled"
29# A self-registered user who has not yet confirmed their email address. Like
30# "disabled", it is not active: no login, no session (every gate checks
31# is_active()). object_signup moves it to "active" when the emailed link is used.
32PENDING_STATUS = "pending"
33ALLOWED_STATUSES = frozenset({ACTIVE_STATUS, DISABLED_STATUS, PENDING_STATUS})
34ACCOUNT_FIELDS = (
35 "account_id",
36 "name",
37 "status",
38 "subscriptions",
39 "created_at",
40 "updated_at",
41)
42USER_FIELDS = (
43 "user_id",
44 "account_id",
45 "email",
46 "display_name",
47 "status",
48 "roles",
49 "subscriptions",
50 "created_at",
51 "updated_at",
52)
53SESSION_FIELDS = (
54 "session_id",
55 "token_hash",
56 "user_id",
57 "account_id",
58 "roles",
59 "subscriptions",
60 "label",
61 "created_at",
62 "expires_at",
63 "revoked_at",
64)
65
66_LEGACY_SESSION_ID_RE = re.compile(r"^sess_[A-Za-z0-9_-]{12,96}$")
67_IDENTITY_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@-]{0,127}$")
68_FILE_LOCKS: dict[Path, threading.Lock] = {}
69_FILE_LOCKS_LOCK = threading.Lock()
70
71
72class SessionNotFoundError(LookupError):
73 """Raised when a session id does not exist."""
74
75
76class AccountNotFoundError(LookupError):
77 """Raised when an account id does not exist."""
78
79
80class UserNotFoundError(LookupError):
81 """Raised when a user id does not exist."""
82
83
84class InvalidSessionPayloadError(ValueError):
85 """Raised when a session payload is not usable."""
86
87
88class InvalidIdentityPayloadError(ValueError):
89 """Raised when a user or account payload is not usable."""
90
91
92@dataclass(frozen=True)
93class IdentityAccount:
94 """A local account/tenant identity."""
95
96 account_id: str
97 name: str
98 status: str
99 subscriptions: tuple[str, ...]
100 created_at: str
101 updated_at: str
102
103 def public_payload(self) -> dict[str, Any]:
104 return {
105 "account_id": self.account_id,
106 "name": self.name,
107 "status": self.status,
108 "subscriptions": list(self.subscriptions),
109 "created_at": self.created_at,
110 "updated_at": self.updated_at,
111 }
112
113 def is_active(self) -> bool:
114 return self.status == ACTIVE_STATUS
115
116
117@dataclass(frozen=True)
118class IdentityUser:
119 """A local user identity used to mint permission subjects."""
120
121 user_id: str
122 account_id: str | None
123 email: str | None
124 display_name: str
125 status: str
126 roles: tuple[str, ...]
127 subscriptions: tuple[str, ...]
128 created_at: str
129 updated_at: str
130
131 def public_payload(self) -> dict[str, Any]:
132 return {
133 "user_id": self.user_id,
134 "account_id": self.account_id,
135 "email": self.email,
136 "display_name": self.display_name,
137 "status": self.status,
138 "roles": list(self.roles),
139 "subscriptions": list(self.subscriptions),
140 "created_at": self.created_at,
141 "updated_at": self.updated_at,
142 }
143
144 def is_active(self) -> bool:
145 return self.status == ACTIVE_STATUS
146
147
148@dataclass(frozen=True)
149class IdentitySession:
150 """A stored identity session without its raw token."""
151
152 session_id: str
153 token_hash: str
154 user_id: str
155 account_id: str | None
156 roles: tuple[str, ...]
157 subscriptions: tuple[str, ...]
158 label: str
159 created_at: str
160 expires_at: str
161 revoked_at: str | None = None
162
163 def is_active(self, now: datetime | None = None) -> bool:
164 if self.revoked_at:
165 return False
166 expires_at = _parse_timestamp(self.expires_at)
167 return expires_at > (now or _now())
168
169 def subject(self) -> object_permissions.PermissionSubject:
170 return object_permissions.PermissionSubject(
171 user_id=self.user_id,
172 account_id=self.account_id,
173 roles=self.roles,
174 subscriptions=self.subscriptions,
175 )
176
177 def public_payload(self) -> dict[str, Any]:
178 return {
179 "session_id": self.session_id,
180 "user_id": self.user_id,
181 "account_id": self.account_id,
182 "roles": list(self.roles),
183 "subscriptions": list(self.subscriptions),
184 "label": self.label,
185 "created_at": self.created_at,
186 "expires_at": self.expires_at,
187 "revoked_at": self.revoked_at,
188 "active": self.is_active(),
189 }
190
191
192def sessions_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
193 """Return the validated session TSV path."""
194 return _identity_path(SESSIONS_FILE, base_dir=base_dir)
195
196
197def accounts_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
198 """Return the validated account TSV path."""
199 return _identity_path(ACCOUNTS_FILE, base_dir=base_dir)
200
201
202def users_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
203 """Return the validated user TSV path."""
204 return _identity_path(USERS_FILE, base_dir=base_dir)
205
206
207def create_account(
208 payload: Mapping[str, Any],
209 *,
210 base_dir: Path | str = DEFAULT_DATA_DIR,
211 now: datetime | None = None,
212) -> dict[str, Any]:
213 """Create an account and return its public payload."""
214 created_at = _format_timestamp(now or _now())
215 account = IdentityAccount(
216 account_id=_identity_id(payload.get("account_id"), "account_id", prefix="acct"),
217 name=_optional_text(payload.get("name"), "name") or "",
218 status=_status(payload.get("status")),
219 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subscriptions"),
220 created_at=created_at,
221 updated_at=created_at,
222 )
223
224 path = accounts_path(base_dir)
225 with _file_lock(path):
226 accounts = _read_accounts(path)
227 if any(existing.account_id == account.account_id for existing in accounts):
228 raise InvalidIdentityPayloadError(f"Account already exists: {account.account_id}")
229 accounts.append(account)
230 _write_accounts(path, accounts)
231
232 return account.public_payload()
233
234
235def list_accounts(
236 *,
237 base_dir: Path | str = DEFAULT_DATA_DIR,
238) -> list[dict[str, Any]]:
239 """Return all accounts."""
240 return [account.public_payload() for account in _read_accounts(accounts_path(base_dir))]
241
242
243def get_account(
244 account_id: str,
245 *,
246 base_dir: Path | str = DEFAULT_DATA_DIR,
247) -> dict[str, Any]:
248 """Return one account payload."""
249 return _find_account(account_id, base_dir=base_dir).public_payload()
250
251
252def create_user(
253 payload: Mapping[str, Any],
254 *,
255 base_dir: Path | str = DEFAULT_DATA_DIR,
256 now: datetime | None = None,
257) -> dict[str, Any]:
258 """Create a user and return its public payload."""
259 account_id = _optional_identity_id(payload.get("account_id"), "account_id")
260 if account_id is not None:
261 _find_account(account_id, base_dir=base_dir)
262
263 created_at = _format_timestamp(now or _now())
264 user = IdentityUser(
265 user_id=_identity_id(payload.get("user_id"), "user_id", prefix="usr"),
266 account_id=account_id,
267 email=_optional_text(payload.get("email"), "email"),
268 display_name=_optional_text(payload.get("display_name"), "display_name") or "",
269 status=_status(payload.get("status")),
270 roles=_string_tuple(payload.get("roles", ()), "roles"),
271 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subscriptions"),
272 created_at=created_at,
273 updated_at=created_at,
274 )
275
276 path = users_path(base_dir)
277 with _file_lock(path):
278 users = _read_users(path)
279 if any(existing.user_id == user.user_id for existing in users):
280 raise InvalidIdentityPayloadError(f"User already exists: {user.user_id}")
281 users.append(user)
282 _write_users(path, users)
283
284 return user.public_payload()
285
286
287def list_users(
288 *,
289 account_id: str | None = None,
290 base_dir: Path | str = DEFAULT_DATA_DIR,
291) -> list[dict[str, Any]]:
292 """Return all users, optionally scoped to one account."""
293 normalized_account_id = _optional_identity_id(account_id, "account_id")
294 users = _read_users(users_path(base_dir))
295 if normalized_account_id is not None:
296 users = [user for user in users if user.account_id == normalized_account_id]
297 return [user.public_payload() for user in users]
298
299
300def get_user(
301 user_id: str,
302 *,
303 base_dir: Path | str = DEFAULT_DATA_DIR,
304) -> dict[str, Any]:
305 """Return one user payload."""
306 return _find_user(user_id, base_dir=base_dir).public_payload()
307
308
309def find_users_by_email(
310 email: str,
311 *,
312 base_dir: Path | str = DEFAULT_DATA_DIR,
313) -> list[dict[str, Any]]:
314 """Return every user whose email matches, ignoring case (any status)."""
315 wanted = (email or "").strip().casefold()
316 if not wanted:
317 return []
318 return [
319 user.public_payload()
320 for user in _read_users(users_path(base_dir))
321 if (user.email or "").strip().casefold() == wanted
322 ]
323
324
325def set_user_status(
326 user_id: str,
327 status: str,
328 *,
329 display_name: str | None = None,
330 base_dir: Path | str = DEFAULT_DATA_DIR,
331 now: datetime | None = None,
332) -> dict[str, Any]:
333 """Change one user's status (and, when given, display name) and return its public payload."""
334 new_status = _status(status)
335 path = users_path(base_dir)
336 updated_at = _format_timestamp(now or _now())
337 with _file_lock(path):
338 users = _read_users(path)
339 found: IdentityUser | None = None
340 for index, user in enumerate(users):
341 if user.user_id == user_id:
342 found = replace(user, status=new_status, updated_at=updated_at)
343 if display_name is not None:
344 found = replace(found, display_name=display_name)
345 users[index] = found
346 break
347 if found is None:
348 raise UserNotFoundError(f"User not found: {user_id}")
349 _write_users(path, users)
350 return found.public_payload()
351
352
353def create_session(
354 payload: Mapping[str, Any],
355 *,
356 base_dir: Path | str = DEFAULT_DATA_DIR,
357 now: datetime | None = None,
358 require_known_user: bool = False,
359) -> dict[str, Any]:
360 """Create a session and return its public payload plus the one-time token."""
361 created_at = now or _now()
362 token = secrets.token_urlsafe(32)
363 user_id = _required_text(payload.get("user_id"), "user_id")
364 user = _lookup_user(user_id, base_dir=base_dir)
365 account = _session_account(payload, user, base_dir=base_dir)
366
367 if user is None and require_known_user:
368 raise UserNotFoundError(f"User not found: {user_id}")
369 if user is not None and not user.is_active():
370 raise InvalidSessionPayloadError(f"User is not active: {user_id}")
371 if account is not None and not account.is_active():
372 raise InvalidSessionPayloadError(f"Account is not active: {account.account_id}")
373
374 default_roles = user.roles if user is not None else ()
375 default_subscriptions = _merged_strings(
376 user.subscriptions if user is not None else (),
377 account.subscriptions if account is not None else (),
378 )
379
380 session = IdentitySession(
381 session_id=_new_session_id(),
382 token_hash=hash_token(token),
383 user_id=user_id,
384 account_id=_session_account_id(payload, user, account),
385 roles=_string_tuple(payload.get("roles", default_roles), "roles"),
386 subscriptions=_string_tuple(
387 payload.get("subscriptions", default_subscriptions),
388 "subscriptions",
389 ),
390 label=_optional_text(payload.get("label"), "label") or "",
391 created_at=_format_timestamp(created_at),
392 expires_at=_format_timestamp(
393 created_at + timedelta(seconds=_ttl_seconds(payload.get("ttl_seconds")))
394 ),
395 )
396
397 path = sessions_path(base_dir)
398 with _file_lock(path):
399 sessions = _read_sessions(path)
400 sessions.append(session)
401 _write_sessions(path, sessions)
402
403 return {"session": session.public_payload(), "token": token}
404
405
406def list_sessions(
407 *,
408 base_dir: Path | str = DEFAULT_DATA_DIR,
409) -> list[dict[str, Any]]:
410 """Return all sessions without raw tokens or token hashes."""
411 return [session.public_payload() for session in _read_sessions(sessions_path(base_dir))]
412
413
414def get_session(
415 session_id: str,
416 *,
417 base_dir: Path | str = DEFAULT_DATA_DIR,
418) -> dict[str, Any]:
419 """Return one public session payload."""
420 session = _find_session(session_id, base_dir=base_dir)
421 return session.public_payload()
422
423
424def revoke_session(
425 session_id: str,
426 *,
427 base_dir: Path | str = DEFAULT_DATA_DIR,
428 now: datetime | None = None,
429) -> dict[str, Any]:
430 """Mark one session revoked and return its public payload."""
431 if not validate_session_id(session_id):
432 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
433
434 path = sessions_path(base_dir)
435 revoked_at = _format_timestamp(now or _now())
436 with _file_lock(path):
437 sessions = _read_sessions(path)
438 updated: list[IdentitySession] = []
439 found: IdentitySession | None = None
440 for session in sessions:
441 if session.session_id == session_id:
442 found = IdentitySession(
443 session_id=session.session_id,
444 token_hash=session.token_hash,
445 user_id=session.user_id,
446 account_id=session.account_id,
447 roles=session.roles,
448 subscriptions=session.subscriptions,
449 label=session.label,
450 created_at=session.created_at,
451 expires_at=session.expires_at,
452 revoked_at=session.revoked_at or revoked_at,
453 )
454 updated.append(found)
455 else:
456 updated.append(session)
457
458 if found is None:
459 raise SessionNotFoundError(f"Session not found: {session_id}")
460
461 _write_sessions(path, updated)
462 return found.public_payload()
463
464
465def revoke_user_sessions(
466 user_id: str,
467 *,
468 base_dir: Path | str = DEFAULT_DATA_DIR,
469 now: datetime | None = None,
470) -> int:
471 """Revoke every unrevoked session of one user; return how many."""
472 path = sessions_path(base_dir)
473 revoked_at = _format_timestamp(now or _now())
474 count = 0
475 with _file_lock(path):
476 sessions = _read_sessions(path)
477 updated: list[IdentitySession] = []
478 for session in sessions:
479 if session.user_id == user_id and not session.revoked_at:
480 session = replace(session, revoked_at=revoked_at)
481 count += 1
482 updated.append(session)
483 if count:
484 _write_sessions(path, updated)
485 return count
486
487
488def resolve_session_token(
489 token: str | None,
490 *,
491 base_dir: Path | str = DEFAULT_DATA_DIR,
492 now: datetime | None = None,
493) -> IdentitySession | None:
494 """Return the active session matching a raw token, if any."""
495 if not token:
496 return None
497
498 token_hash = hash_token(token)
499 checked_at = now or _now()
500 for session in _read_sessions(sessions_path(base_dir)):
501 if not hmac.compare_digest(session.token_hash, token_hash):
502 continue
503 if session.is_active(checked_at):
504 return session
505 return None
506
507 return None
508
509
510def hash_token(token: str) -> str:
511 """Return the stored hash for a raw session token."""
512 return "sha256:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
513
514
515def validate_session_id(session_id: str) -> bool:
516 """Return True when a session id is route-safe."""
517 if not isinstance(session_id, str):
518 return False
519 return object_ids.is_uuid4(session_id) or bool(_LEGACY_SESSION_ID_RE.fullmatch(session_id))
520
521
522def _find_session(
523 session_id: str,
524 *,
525 base_dir: Path | str = DEFAULT_DATA_DIR,
526) -> IdentitySession:
527 if not validate_session_id(session_id):
528 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
529
530 for session in _read_sessions(sessions_path(base_dir)):
531 if session.session_id == session_id:
532 return session
533
534 raise SessionNotFoundError(f"Session not found: {session_id}")
535
536
537def _find_account(
538 account_id: str,
539 *,
540 base_dir: Path | str = DEFAULT_DATA_DIR,
541) -> IdentityAccount:
542 normalized = _identity_id(account_id, "account_id")
543 for account in _read_accounts(accounts_path(base_dir)):
544 if account.account_id == normalized:
545 return account
546 raise AccountNotFoundError(f"Account not found: {normalized}")
547
548
549def _find_user(
550 user_id: str,
551 *,
552 base_dir: Path | str = DEFAULT_DATA_DIR,
553) -> IdentityUser:
554 normalized = _identity_id(user_id, "user_id")
555 for user in _read_users(users_path(base_dir)):
556 if user.user_id == normalized:
557 return user
558 raise UserNotFoundError(f"User not found: {normalized}")
559
560
561def _lookup_user(
562 user_id: str,
563 *,
564 base_dir: Path | str = DEFAULT_DATA_DIR,
565) -> IdentityUser | None:
566 try:
567 return _find_user(user_id, base_dir=base_dir)
568 except UserNotFoundError:
569 return None
570
571
572def _lookup_account(
573 account_id: str | None,
574 *,
575 base_dir: Path | str = DEFAULT_DATA_DIR,
576) -> IdentityAccount | None:
577 if account_id is None:
578 return None
579 try:
580 return _find_account(account_id, base_dir=base_dir)
581 except AccountNotFoundError:
582 return None
583
584
585def _read_sessions(path: Path) -> list[IdentitySession]:
586 if not path.exists():
587 return []
588
589 sessions: list[IdentitySession] = []
590 with path.open(newline="") as handle:
591 rows = csv.DictReader(handle, delimiter="\t")
592 for row in rows:
593 if not row:
594 continue
595 try:
596 sessions.append(_session_from_row(row))
597 except (InvalidSessionPayloadError, ValueError):
598 continue
599 return sessions
600
601
602def _read_accounts(path: Path) -> list[IdentityAccount]:
603 if not path.exists():
604 return []
605
606 accounts: list[IdentityAccount] = []
607 with path.open(newline="") as handle:
608 rows = csv.DictReader(handle, delimiter="\t")
609 for row in rows:
610 if not row:
611 continue
612 try:
613 accounts.append(_account_from_row(row))
614 except (InvalidIdentityPayloadError, ValueError):
615 continue
616 return accounts
617
618
619def _read_users(path: Path) -> list[IdentityUser]:
620 if not path.exists():
621 return []
622
623 users: list[IdentityUser] = []
624 with path.open(newline="") as handle:
625 rows = csv.DictReader(handle, delimiter="\t")
626 for row in rows:
627 if not row:
628 continue
629 try:
630 users.append(_user_from_row(row))
631 except (InvalidIdentityPayloadError, ValueError):
632 continue
633 return users
634
635
636def _write_sessions(path: Path, sessions: Iterable[IdentitySession]) -> None:
637 path.parent.mkdir(parents=True, exist_ok=True)
638 temp_path = path.with_name(f".{path.name}.tmp")
639 with temp_path.open("w", newline="") as handle:
640 writer = csv.DictWriter(handle, fieldnames=SESSION_FIELDS, delimiter="\t")
641 writer.writeheader()
642 for session in sessions:
643 writer.writerow(_session_to_row(session))
644 temp_path.replace(path)
645
646
647def _write_accounts(path: Path, accounts: Iterable[IdentityAccount]) -> None:
648 path.parent.mkdir(parents=True, exist_ok=True)
649 temp_path = path.with_name(f".{path.name}.tmp")
650 with temp_path.open("w", newline="") as handle:
651 writer = csv.DictWriter(handle, fieldnames=ACCOUNT_FIELDS, delimiter="\t")
652 writer.writeheader()
653 for account in accounts:
654 writer.writerow(_account_to_row(account))
655 temp_path.replace(path)
656
657
658def _write_users(path: Path, users: Iterable[IdentityUser]) -> None:
659 path.parent.mkdir(parents=True, exist_ok=True)
660 temp_path = path.with_name(f".{path.name}.tmp")
661 with temp_path.open("w", newline="") as handle:
662 writer = csv.DictWriter(handle, fieldnames=USER_FIELDS, delimiter="\t")
663 writer.writeheader()
664 for user in users:
665 writer.writerow(_user_to_row(user))
666 temp_path.replace(path)
667
668
669def _account_from_row(row: Mapping[str, str]) -> IdentityAccount:
670 account_id = _identity_id(row.get("account_id"), "account_id")
671 created_at = _required_text(row.get("created_at"), "created_at")
672 updated_at = _required_text(row.get("updated_at"), "updated_at")
673 _parse_timestamp(created_at)
674 _parse_timestamp(updated_at)
675 return IdentityAccount(
676 account_id=account_id,
677 name=str(row.get("name", "")),
678 status=_status(row.get("status")),
679 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
680 created_at=created_at,
681 updated_at=updated_at,
682 )
683
684
685def _user_from_row(row: Mapping[str, str]) -> IdentityUser:
686 user_id = _identity_id(row.get("user_id"), "user_id")
687 created_at = _required_text(row.get("created_at"), "created_at")
688 updated_at = _required_text(row.get("updated_at"), "updated_at")
689 _parse_timestamp(created_at)
690 _parse_timestamp(updated_at)
691 return IdentityUser(
692 user_id=user_id,
693 account_id=_optional_identity_id(row.get("account_id"), "account_id"),
694 email=_empty_to_none(row.get("email")),
695 display_name=str(row.get("display_name", "")),
696 status=_status(row.get("status")),
697 roles=_json_string_tuple(row.get("roles", "[]"), "roles"),
698 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
699 created_at=created_at,
700 updated_at=updated_at,
701 )
702
703
704def _session_from_row(row: Mapping[str, str]) -> IdentitySession:
705 session_id = str(row.get("session_id", ""))
706 if not validate_session_id(session_id):
707 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
708
709 token_hash = _stored_token_hash(row.get("token_hash"))
710 created_at = _required_text(row.get("created_at"), "created_at")
711 expires_at = _required_text(row.get("expires_at"), "expires_at")
712 _parse_timestamp(created_at)
713 _parse_timestamp(expires_at)
714
715 return IdentitySession(
716 session_id=session_id,
717 token_hash=token_hash,
718 user_id=_required_text(row.get("user_id"), "user_id"),
719 account_id=_empty_to_none(row.get("account_id")),
720 roles=_json_string_tuple(row.get("roles", "[]"), "roles"),
721 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
722 label=str(row.get("label", "")),
723 created_at=created_at,
724 expires_at=expires_at,
725 revoked_at=_empty_to_none(row.get("revoked_at")),
726 )
727
728
729def _account_to_row(account: IdentityAccount) -> dict[str, str]:
730 return {
731 "account_id": account.account_id,
732 "name": account.name,
733 "status": account.status,
734 "subscriptions": json.dumps(list(account.subscriptions), separators=(",", ":")),
735 "created_at": account.created_at,
736 "updated_at": account.updated_at,
737 }
738
739
740def _user_to_row(user: IdentityUser) -> dict[str, str]:
741 return {
742 "user_id": user.user_id,
743 "account_id": user.account_id or "",
744 "email": user.email or "",
745 "display_name": user.display_name,
746 "status": user.status,
747 "roles": json.dumps(list(user.roles), separators=(",", ":")),
748 "subscriptions": json.dumps(list(user.subscriptions), separators=(",", ":")),
749 "created_at": user.created_at,
750 "updated_at": user.updated_at,
751 }
752
753
754def _session_to_row(session: IdentitySession) -> dict[str, str]:
755 return {
756 "session_id": session.session_id,
757 "token_hash": session.token_hash,
758 "user_id": session.user_id,
759 "account_id": session.account_id or "",
760 "roles": json.dumps(list(session.roles), separators=(",", ":")),
761 "subscriptions": json.dumps(list(session.subscriptions), separators=(",", ":")),
762 "label": session.label,
763 "created_at": session.created_at,
764 "expires_at": session.expires_at,
765 "revoked_at": session.revoked_at or "",
766 }
767
768
769def _new_session_id() -> str:
770 return object_ids.new_uuid4()
771
772
773def _identity_path(filename: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
774 root = Path(base_dir) / IDENTITY_DIR
775 path = root / filename
776 resolved_root = root.resolve(strict=False)
777 resolved_path = path.resolve(strict=False)
778
779 try:
780 resolved_path.relative_to(resolved_root)
781 except ValueError as exc:
782 raise ValueError("Identity path escapes identity directory") from exc
783
784 return path
785
786
787def _identity_id(value: Any, field: str, *, prefix: str | None = None) -> str:
788 if value is None and prefix is not None:
789 value = object_ids.new_uuid4()
790 text = _required_text(value, field)
791 if not _IDENTITY_ID_RE.fullmatch(text):
792 raise InvalidIdentityPayloadError(f"{field} contains unsafe identifier")
793 return text
794
795
796def _optional_identity_id(value: Any, field: str) -> str | None:
797 text = _optional_text(value, field)
798 if text is None:
799 return None
800 if not _IDENTITY_ID_RE.fullmatch(text):
801 raise InvalidIdentityPayloadError(f"{field} contains unsafe identifier")
802 return text
803
804
805def _status(value: Any) -> str:
806 status = _optional_text(value, "status") or ACTIVE_STATUS
807 if status not in ALLOWED_STATUSES:
808 raise InvalidIdentityPayloadError(f"status must be one of: {', '.join(sorted(ALLOWED_STATUSES))}")
809 return status
810
811
812def _session_account(
813 payload: Mapping[str, Any],
814 user: IdentityUser | None,
815 *,
816 base_dir: Path | str,
817) -> IdentityAccount | None:
818 payload_account_id = _optional_identity_id(payload.get("account_id"), "account_id")
819 if user is not None and payload_account_id and user.account_id != payload_account_id:
820 raise InvalidSessionPayloadError("account_id does not match registered user")
821
822 account_id = payload_account_id or (user.account_id if user is not None else None)
823 if account_id is None:
824 return None
825
826 account = _lookup_account(account_id, base_dir=base_dir)
827 if account is None and user is not None:
828 raise AccountNotFoundError(f"Account not found: {account_id}")
829 return account
830
831
832def _session_account_id(
833 payload: Mapping[str, Any],
834 user: IdentityUser | None,
835 account: IdentityAccount | None,
836) -> str | None:
837 payload_account_id = _optional_identity_id(payload.get("account_id"), "account_id")
838 if payload_account_id is not None:
839 return payload_account_id
840 if account is not None:
841 return account.account_id
842 return user.account_id if user is not None else None
843
844
845def _merged_strings(*groups: Iterable[str]) -> tuple[str, ...]:
846 merged: list[str] = []
847 seen = set()
848 for group in groups:
849 for item in group:
850 if item not in seen:
851 merged.append(item)
852 seen.add(item)
853 return tuple(merged)
854
855
856def _ttl_seconds(value: Any) -> int:
857 if value is None:
858 return DEFAULT_SESSION_TTL_SECONDS
859 if isinstance(value, bool):
860 raise InvalidSessionPayloadError("ttl_seconds must be an integer")
861 try:
862 ttl = int(value)
863 except (TypeError, ValueError) as exc:
864 raise InvalidSessionPayloadError("ttl_seconds must be an integer") from exc
865
866 if ttl <= 0:
867 raise InvalidSessionPayloadError("ttl_seconds must be greater than zero")
868 return min(ttl, MAX_SESSION_TTL_SECONDS)
869
870
871def _required_text(value: Any, field: str) -> str:
872 text = _optional_text(value, field)
873 if text is None:
874 raise InvalidSessionPayloadError(f"{field} is required")
875 return text
876
877
878def _optional_text(value: Any, field: str) -> str | None:
879 if value is None:
880 return None
881 if not isinstance(value, str):
882 raise InvalidSessionPayloadError(f"{field} must be a string")
883 text = value.strip()
884 if not text:
885 return None
886 if len(text) > 256 or any(ord(char) < 32 for char in text):
887 raise InvalidSessionPayloadError(f"{field} contains unsafe text")
888 return text
889
890
891def _string_tuple(value: Any, field: str) -> tuple[str, ...]:
892 if value is None:
893 return ()
894 if isinstance(value, str):
895 values = value.split(",")
896 elif isinstance(value, (list, tuple)):
897 values = value
898 else:
899 raise InvalidSessionPayloadError(f"{field} must be a list of strings")
900
901 output: list[str] = []
902 seen = set()
903 for item in values:
904 text = _required_text(item, field)
905 if text not in seen:
906 output.append(text)
907 seen.add(text)
908 return tuple(output)
909
910
911def _json_string_tuple(value: str, field: str) -> tuple[str, ...]:
912 try:
913 payload = json.loads(value or "[]")
914 except json.JSONDecodeError as exc:
915 raise InvalidSessionPayloadError(f"{field} is invalid JSON") from exc
916 return _string_tuple(payload, field)
917
918
919def _stored_token_hash(value: str | None) -> str:
920 text = (value or "").strip()
921 if not text.startswith("sha256:") or len(text) != len("sha256:") + 64:
922 raise InvalidSessionPayloadError("token_hash is invalid")
923 return text
924
925
926def _empty_to_none(value: str | None) -> str | None:
927 text = (value or "").strip()
928 return text or None
929
930
931def _format_timestamp(value: datetime) -> str:
932 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
933
934
935def _parse_timestamp(value: str) -> datetime:
936 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
937 if parsed.tzinfo is None:
938 raise ValueError("timestamp must include timezone")
939 return parsed
940
941
942def _now() -> datetime:
943 return datetime.now(timezone.utc)
944
945
946def _file_lock(path: Path) -> threading.Lock:
947 resolved = path.resolve(strict=False)
948 with _FILE_LOCKS_LOCK:
949 lock = _FILE_LOCKS.get(resolved)
950 if lock is None:
951 lock = threading.Lock()
952 _FILE_LOCKS[resolved] = lock
953 return lock