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

9 downloads

dbbasic-object-server/object_identity.py
Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_identity.py · 85.1 KB · 2247 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 logging
10import os
11import re
12import secrets
13import threading
14import time
15import unicodedata
16from dataclasses import dataclass, replace
17from datetime import datetime, timedelta, timezone
18from pathlib import Path
19from typing import Any, Iterable, Mapping, NamedTuple
20
21import object_ids
22import object_permissions
23from object_versions import DEFAULT_DATA_DIR
24
25_LOG = logging.getLogger("dbbasic.object_identity")
26
27IDENTITY_DIR = "identity"
28SESSIONS_FILE = "sessions.tsv"
29ACCOUNTS_FILE = "accounts.tsv"
30USERS_FILE = "users.tsv"
31DEFAULT_SESSION_TTL_SECONDS = 24 * 60 * 60
32MAX_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
33ACTIVE_STATUS = "active"
34DISABLED_STATUS = "disabled"
35# A self-registered user who has not yet confirmed their email address. Like
36# "disabled", it is not active: no login, no session (every gate checks
37# is_active()). object_signup moves it to "active" when the emailed link is used.
38PENDING_STATUS = "pending"
39ALLOWED_STATUSES = frozenset({ACTIVE_STATUS, DISABLED_STATUS, PENDING_STATUS})
40
41# What a credential's owner looks like to the resolvers (user_standing).
42#
43# A session or API key names a user id; whether it still authenticates depends
44# on that user's row in users.tsv, read on every request (stat-cached, so a
45# status change made by any process is seen on the next request). This was
46# added after a disabled user's existing API key, a NEW key minted for them,
47# and their existing sessions all kept answering 200: status was checked only
48# when a session was minted, never when a credential was presented.
49#
50# Three answers, not two, because the registry deliberately allows sessions
51# for user ids it has never heard of (admin-minted gateway sessions; see
52# DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS, which callers pass as
53# require_known_user to refuse those too):
54# active - a parseable row whose status is exactly "active"
55# inactive - any other row for that id: disabled, pending, a status this
56# code does not know, an empty one, or a row that fails to parse
57# (fail closed: a hand-edited "suspended" must not read as absent,
58# because absent means "allowed" for ad hoc sessions)
59# absent - no row at all
60STANDING_ACTIVE = "active"
61STANDING_INACTIVE = "inactive"
62STANDING_ABSENT = "absent"
63ACCOUNT_FIELDS = (
64 "account_id",
65 "name",
66 "status",
67 "subscriptions",
68 "created_at",
69 "updated_at",
70)
71USER_FIELDS = (
72 "user_id",
73 "account_id",
74 "email",
75 "display_name",
76 "status",
77 "roles",
78 "subscriptions",
79 "created_at",
80 "updated_at",
81 # The identity source (object_identity_sources, e.g. "http_verify") this
82 # local user is the same person as. Empty -- the default -- means the
83 # row is local only: a remote identity naming this user id is refused,
84 # because the upstream's numeric ids and this registry's ids share the
85 # u_<id>_ namespace, roles and grants. Set by an operator only.
86 "identity_source",
87)
88SESSION_FIELDS = (
89 "session_id",
90 "token_hash",
91 "user_id",
92 "account_id",
93 "roles",
94 "subscriptions",
95 "label",
96 "created_at",
97 "expires_at",
98 "revoked_at",
99 "roles_from",
100)
101# Where a session's roles, subscriptions and account come from on each
102# request (IdentitySession.roles_from; the name predates the last two). A
103# session never carries more than its user currently has: they are read from
104# users.tsv (and the user's account row in accounts.tsv, for its
105# subscriptions) when the session is presented, not only when it is minted.
106# user - minted from a registered user's own row, nothing given
107# explicitly: the session has the user's CURRENT roles, account and
108# subscriptions (the user's own plus their account's, while that
109# account is active), so a change applies on the next request. The
110# user's row going away ends the session.
111# session - minted for a registered user with roles or subscriptions given
112# explicitly (the admin route): the session keeps its stored roles
113# and subscriptions less any the user no longer has, and its
114# account only while the user is still in it. The user's row going
115# away ends the session.
116# "" - a row written before this column existed, or a session minted
117# for a user id with no row (an ad hoc gateway session): while the
118# user has a row, capped like "session"; with no row, the stored
119# values, as before (nothing to compare them with).
120ROLES_FROM_USER = "user"
121ROLES_FROM_SESSION = "session"
122_ROLES_FROM_VALUES = frozenset({"", ROLES_FROM_USER, ROLES_FROM_SESSION})
123
124_LEGACY_SESSION_ID_RE = re.compile(r"^sess_[A-Za-z0-9_-]{12,96}$")
125_IDENTITY_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@-]{0,127}$")
126# What set_account_subscriptions accepts (validate_subscription_names).
127MAX_ACCOUNT_SUBSCRIPTIONS = 64
128MAX_SUBSCRIPTION_NAME_LENGTH = 64
129_SUBSCRIPTION_NAME_RE = re.compile(
130 rf"^[A-Za-z0-9][A-Za-z0-9_.:@+-]{{0,{MAX_SUBSCRIPTION_NAME_LENGTH - 1}}}$"
131)
132_FILE_LOCKS: dict[Path, threading.Lock] = {}
133_FILE_LOCKS_LOCK = threading.Lock()
134
135# Parsed-session cache, one entry per sessions file. Entries are keyed on the
136# file's stat signature and dropped by _write_sessions. See _sessions_snapshot.
137_SESSION_CACHE: dict[str, tuple[tuple[int, int, int, int], "_SessionSnapshot"]] = {}
138_SESSION_CACHE_LOCK = threading.Lock()
139_SESSION_CACHE_GENERATION = 0
140_SESSION_CACHE_MAX_PATHS = 64
141# A file whose mtime is younger than this when we parse it is not cached: a
142# same-size rewrite inside the filesystem's timestamp granularity would be
143# indistinguishable by stat. Comfortably above coarse (4-10 ms) granularities.
144_SESSION_CACHE_RACY_NS = 50_000_000
145
146# The same stat-signature scheme for users.tsv, holding only user_id ->
147# UserRecord, and for accounts.tsv, holding account_id -> AccountRecord (one
148# entry per file path). Every authenticated request asks it (user_standing,
149# resolve_session_token), so it must not re-parse an unchanged file; it must
150# also never answer from a parse of a file that has since changed, here or in
151# another process.
152_STANDING_CACHE: dict[str, tuple[tuple[int, int, int, int], dict[str, Any]]] = {}
153_STANDING_CACHE_LOCK = threading.Lock()
154_STANDING_CACHE_GENERATION = 0
155
156
157class UserRecord(NamedTuple):
158 """What a credential's owner holds now, from users.tsv (see user_record).
159
160 roles and subscriptions are None for a row that does not parse:
161 inactive, and nothing to read them from.
162 """
163
164 active: bool
165 roles: tuple[str, ...] | None
166 account_id: str | None = None
167 subscriptions: tuple[str, ...] | None = None
168 # The identity source the row is linked to (USER_FIELDS), or None.
169 identity_source: str | None = None
170 # Set when the id has several rows that parse and name different
171 # accounts (an empty account_id counts as one): every account named,
172 # sorted, "" for none. account_id is then None, and member_account
173 # refuses the user (ACCOUNT_ROWS_CONFLICTING).
174 conflicting_accounts: tuple[str, ...] = ()
175
176
177class AccountRecord(NamedTuple):
178 """An account's current standing and subscriptions, from accounts.tsv.
179
180 parsed is False for a row that does not parse: inactive, so its users are
181 refused, but their credentials are not ended (it may be a typo being fixed).
182 """
183
184 active: bool
185 subscriptions: tuple[str, ...]
186 parsed: bool = True
187
188
189class SessionNotFoundError(LookupError):
190 """Raised when a session id does not exist."""
191
192
193class AccountNotFoundError(LookupError):
194 """Raised when an account id does not exist."""
195
196
197class UserNotFoundError(LookupError):
198 """Raised when a user id does not exist."""
199
200
201class AccountSessionsNotEndedError(RuntimeError):
202 """The account was disabled but its users' sessions could not be ended.
203
204 Deliberately not an OSError/ValueError: callers treat those as "nothing
205 changed", and here something did. The account IS disabled, so every
206 request from its users is already refused (resolve_session_token reads
207 the account's status on each one); what failed is marking the sessions
208 revoked, which is what keeps them from coming back on re-enable.
209 Disabling again retries it.
210 """
211
212 def __init__(self, account_id: str, cause: BaseException) -> None:
213 super().__init__(
214 f"Account {account_id} was disabled, but its users' existing sessions could not "
215 f"be ended ({cause}). They are refused while the account is disabled; disable it "
216 "again to retry before re-enabling it."
217 )
218 self.account_id = account_id
219
220
221ACCOUNT_ROW_MISSING = "missing"
222ACCOUNT_ROW_UNPARSED = "unparsed"
223ACCOUNT_ROWS_CONFLICTING = "conflicting"
224
225
226class AccountUnusableError(ValueError):
227 """A registered user's row names an account whose row is missing or broken.
228
229 Fail closed: such a user cannot sign in, and their sessions and API keys
230 are refused (member_account). It used to be the opposite for a missing
231 row, which "refused nobody": deleting an account's row, or losing
232 accounts.tsv, left its members signed in as if the account were fine.
233 Nothing is ended or deleted, so restoring the row restores them.
234
235 reason is ACCOUNT_ROW_MISSING (no row for the id, or no accounts.tsv at
236 all), ACCOUNT_ROW_UNPARSED (a row, or one of several rows, for the id
237 that does not parse) or ACCOUNT_ROWS_CONFLICTING (the user has several
238 rows in users.tsv naming different accounts; account_id is then those
239 ids joined with "," and "(none)" for a row naming none). A ValueError
240 so that a caller that does not know it refuses with a 400/401, never a
241 500 or a session.
242 """
243
244 def __init__(self, user_id: str, account_id: str, reason: str) -> None:
245 if reason == ACCOUNT_ROWS_CONFLICTING:
246 message = f"User {user_id} has rows in users.tsv naming different accounts: {account_id}"
247 else:
248 detail = "has no row" if reason == ACCOUNT_ROW_MISSING else "has a row that does not parse"
249 message = f"Account {account_id} of user {user_id} {detail} in accounts.tsv"
250 super().__init__(message)
251 self.user_id = user_id
252 self.account_id = account_id
253 self.reason = reason
254
255
256class InvalidSessionPayloadError(ValueError):
257 """Raised when a session payload is not usable."""
258
259
260class InvalidIdentityPayloadError(ValueError):
261 """Raised when a user or account payload is not usable."""
262
263
264class LeftoverCredentialsError(InvalidIdentityPayloadError):
265 """Credentials are already stored under the user id being created, with no user behind them.
266
267 A password (credentials.tsv), sessions still signed in (sessions.tsv) or
268 API keys (api_keys.tsv), left by a user removed from users.tsv by hand,
269 or by a create that stopped half way. The new user would sign in with
270 that password, and whoever holds those session tokens or keys would be
271 signed in as the new user from the moment its row appears."""
272
273 def __init__(self, user_id: str, *, password: bool, sessions: int, api_keys: int) -> None:
274 found = []
275 if password:
276 found.append("a password")
277 if sessions:
278 found.append(f"{sessions} session(s) still signed in")
279 if api_keys:
280 found.append(f"{api_keys} API key(s)")
281 remedy = (
282 f"remove the old password first (object_identity_cli remove-password --user-id {user_id})"
283 if password and not sessions and not api_keys
284 else f"clear them first (object_identity_cli clear-leftovers --user-id {user_id})"
285 )
286 super().__init__(
287 f"Credentials are already stored for user id {user_id}, which has no user (left from a removed "
288 f"user or an interrupted create): {', '.join(found)}. The new user would inherit them, so nothing "
289 f"was created. Choose another user id, or {remedy}."
290 )
291 self.user_id = user_id
292 self.password = password
293 self.sessions = sessions
294 self.api_keys = api_keys
295
296
297# The name from when only a leftover password was checked.
298LeftoverPasswordError = LeftoverCredentialsError
299
300
301@dataclass(frozen=True)
302class IdentityAccount:
303 """A local account/tenant identity."""
304
305 account_id: str
306 name: str
307 status: str
308 subscriptions: tuple[str, ...]
309 created_at: str
310 updated_at: str
311
312 def public_payload(self) -> dict[str, Any]:
313 return {
314 "account_id": self.account_id,
315 "name": self.name,
316 "status": self.status,
317 "subscriptions": list(self.subscriptions),
318 "created_at": self.created_at,
319 "updated_at": self.updated_at,
320 }
321
322 def is_active(self) -> bool:
323 return self.status == ACTIVE_STATUS
324
325
326@dataclass(frozen=True)
327class IdentityUser:
328 """A local user identity used to mint permission subjects."""
329
330 user_id: str
331 account_id: str | None
332 email: str | None
333 display_name: str
334 status: str
335 roles: tuple[str, ...]
336 subscriptions: tuple[str, ...]
337 created_at: str
338 updated_at: str
339 identity_source: str | None = None
340
341 def public_payload(self) -> dict[str, Any]:
342 return {
343 "user_id": self.user_id,
344 "account_id": self.account_id,
345 "email": self.email,
346 "display_name": self.display_name,
347 "status": self.status,
348 "roles": list(self.roles),
349 "subscriptions": list(self.subscriptions),
350 "created_at": self.created_at,
351 "updated_at": self.updated_at,
352 "identity_source": self.identity_source,
353 }
354
355 def is_active(self) -> bool:
356 return self.status == ACTIVE_STATUS
357
358
359@dataclass(frozen=True)
360class IdentitySession:
361 """A stored identity session without its raw token."""
362
363 session_id: str
364 token_hash: str
365 user_id: str
366 account_id: str | None
367 roles: tuple[str, ...]
368 subscriptions: tuple[str, ...]
369 label: str
370 created_at: str
371 expires_at: str
372 revoked_at: str | None = None
373 roles_from: str = ""
374
375 def is_active(self, now: datetime | None = None) -> bool:
376 if self.revoked_at:
377 return False
378 expires_at = _parse_timestamp(self.expires_at)
379 return expires_at > (now or _now())
380
381 def subject(self) -> object_permissions.PermissionSubject:
382 return object_permissions.PermissionSubject(
383 user_id=self.user_id,
384 account_id=self.account_id,
385 roles=self.roles,
386 subscriptions=self.subscriptions,
387 )
388
389 def public_payload(self) -> dict[str, Any]:
390 return {
391 "session_id": self.session_id,
392 "user_id": self.user_id,
393 "account_id": self.account_id,
394 "roles": list(self.roles),
395 "subscriptions": list(self.subscriptions),
396 "label": self.label,
397 "created_at": self.created_at,
398 "expires_at": self.expires_at,
399 "revoked_at": self.revoked_at,
400 "active": self.is_active(),
401 }
402
403
404def sessions_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
405 """Return the validated session TSV path."""
406 return _identity_path(SESSIONS_FILE, base_dir=base_dir)
407
408
409def accounts_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
410 """Return the validated account TSV path."""
411 return _identity_path(ACCOUNTS_FILE, base_dir=base_dir)
412
413
414def users_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
415 """Return the validated user TSV path."""
416 return _identity_path(USERS_FILE, base_dir=base_dir)
417
418
419def create_account(
420 payload: Mapping[str, Any],
421 *,
422 base_dir: Path | str = DEFAULT_DATA_DIR,
423 now: datetime | None = None,
424) -> dict[str, Any]:
425 """Create an account and return its public payload."""
426 created_at = _format_timestamp(now or _now())
427 account = IdentityAccount(
428 account_id=_identity_id(payload.get("account_id"), "account_id", prefix="acct"),
429 name=_optional_text(payload.get("name"), "name") or "",
430 status=_status(payload.get("status")),
431 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subscriptions"),
432 created_at=created_at,
433 updated_at=created_at,
434 )
435
436 path = accounts_path(base_dir)
437 with _file_lock(path):
438 accounts = _read_accounts(path)
439 if any(existing.account_id == account.account_id for existing in accounts):
440 raise InvalidIdentityPayloadError(f"Account already exists: {account.account_id}")
441 accounts.append(account)
442 _write_accounts(path, accounts)
443
444 return account.public_payload()
445
446
447def list_accounts(
448 *,
449 base_dir: Path | str = DEFAULT_DATA_DIR,
450) -> list[dict[str, Any]]:
451 """Return all accounts."""
452 return [account.public_payload() for account in _read_accounts(accounts_path(base_dir))]
453
454
455def get_account(
456 account_id: str,
457 *,
458 base_dir: Path | str = DEFAULT_DATA_DIR,
459) -> dict[str, Any]:
460 """Return one account payload."""
461 return _find_account(account_id, base_dir=base_dir).public_payload()
462
463
464def set_account_status(
465 account_id: str,
466 status: str,
467 *,
468 base_dir: Path | str = DEFAULT_DATA_DIR,
469 now: datetime | None = None,
470) -> dict[str, Any]:
471 """Disable or re-enable an account; return it and how many sessions ended.
472
473 While an account is not active, every session and API key of its users
474 (users.tsv rows naming it) is refused on each request (resolve_session_token,
475 object_api_keys.resolve_api_key) and none of them can sign in. Leaving
476 "active" also ends (marks revoked) every session of its users, and every
477 session minted naming the account, so re-enabling does not bring them back.
478 API keys are deliberately kept: they are refused while the account is
479 disabled and work again, unchanged, once it is re-enabled -- deleting them
480 would break a customer's integrations for good over a mistaken or
481 temporary disable. A billing lapse is not a disable: remove the account's
482 subscription instead (docs/permissions-model.md).
483
484 The status is written first, then the sessions are ended, so a failure
485 between the two leaves the account disabled with its sessions refused,
486 never enabled with sessions half gone. That failure raises
487 AccountSessionsNotEndedError (not OSError/ValueError: the status did
488 change); disabling again retries. Idempotent.
489 """
490 if not isinstance(status, str) or not status.strip():
491 raise InvalidIdentityPayloadError("status is required")
492 new_status = _status(status)
493 normalized = _identity_id(account_id, "account_id")
494 path = accounts_path(base_dir)
495 updated_at = _format_timestamp(now or _now())
496 with _file_lock(path):
497 fieldnames, rows, matching = _account_rows_for(path, normalized)
498 for row in matching:
499 row["status"] = new_status
500 row["updated_at"] = updated_at
501 found = _parsed_account_row(matching[0], normalized)
502 _write_account_rows(path, fieldnames, rows)
503
504 sessions_revoked = 0
505 if new_status != ACTIVE_STATUS:
506 try:
507 members = {
508 user_id
509 for user_id, record in _user_standings(users_path(base_dir)).items()
510 if record.account_id == normalized
511 }
512 sessions_revoked = _revoke_sessions_where(
513 lambda session: session.user_id in members or session.account_id == normalized,
514 base_dir=base_dir,
515 now=now,
516 )
517 except (OSError, ValueError) as exc:
518 raise AccountSessionsNotEndedError(normalized, exc) from exc
519 return {"account": found.public_payload(), "sessions_revoked": sessions_revoked}
520
521
522def set_account_subscriptions(
523 account_id: str,
524 subscriptions: Any,
525 *,
526 actor: str,
527 actor_method: str,
528 base_dir: Path | str = DEFAULT_DATA_DIR,
529 now: datetime | None = None,
530) -> dict[str, Any]:
531 """Replace an account's subscriptions; return the account, before and after.
532
533 The supported way to change what an account pays for (billing): the
534 whole list is given, not a delta, so a retry is harmless. subscriptions
535 must be a list of names (validate_subscription_names: at most
536 MAX_ACCOUNT_SUBSCRIPTIONS, each a plain name of at most
537 MAX_SUBSCRIPTION_NAME_LENGTH characters, no duplicates); an empty list
538 removes them all, which is how a billing lapse is recorded.
539
540 Nothing is revoked or ended. Sessions read the account's row on every
541 request (resolve_session_token, _current_subscriptions), so the change
542 applies to every signed-in member on their next request. API keys never
543 carry the account's subscriptions (only the user's own), so they are not
544 affected either way.
545
546 Written atomically (temp file and rename, under the accounts lock), as
547 raw rows so a row that does not parse is never dropped; a target row that
548 does not parse is refused ("fix it by hand") and nothing is written. An
549 unchanged list writes nothing. Every call that reaches the store appends
550 one ops `auth` line, event account_subscriptions_set, naming the account,
551 the actor and actor_method, with the list before and after, so any caller
552 (the route, the CLI, a billing integration calling this) is audited.
553 The ops line is best effort: the change has already been made.
554 """
555 actor_text = _required_text(actor, "actor")
556 method_text = _required_text(actor_method, "actor_method")
557 new = validate_subscription_names(subscriptions)
558 normalized = _identity_id(account_id, "account_id")
559 path = accounts_path(base_dir)
560 updated_at = _format_timestamp(now or _now())
561 with _file_lock(path):
562 fieldnames, rows, matching = _account_rows_for(path, normalized)
563 # Every row for the id is rewritten (a duplicate row is read as the
564 # intersection of its rows' subscriptions: _parse_account_records),
565 # so every one must parse; "before" is what the resolvers saw.
566 held = [_parsed_account_row(row, normalized).subscriptions for row in matching]
567 old = tuple(name for name in held[0] if all(name in other for other in held[1:]))
568 changed = any(names != new for names in held)
569 if changed:
570 encoded = json.dumps(list(new), separators=(",", ":"))
571 for row in matching:
572 row["subscriptions"] = encoded
573 row["updated_at"] = updated_at
574 _write_account_rows(path, fieldnames, rows)
575 found = _parsed_account_row(matching[0], normalized)
576 _append_ops_event(
577 "account_subscriptions_set",
578 identifier=normalized,
579 user_id=actor_text,
580 auth_method=method_text,
581 label=f"before={','.join(old) or '-'} after={','.join(new) or '-'}",
582 before=list(old),
583 after=list(new),
584 changed=changed,
585 base_dir=base_dir,
586 )
587 return {
588 "account": found.public_payload(),
589 "before": list(old),
590 "after": list(new),
591 "changed": changed,
592 }
593
594
595def validate_subscription_names(value: Any) -> tuple[str, ...]:
596 """A list of subscription names as set_account_subscriptions accepts it.
597
598 A JSON list (or tuple) of strings, at most MAX_ACCOUNT_SUBSCRIPTIONS of
599 them, each matching _SUBSCRIPTION_NAME_RE (a letter or digit, then
600 letters, digits and _ . : @ + -, at most MAX_SUBSCRIPTION_NAME_LENGTH in
601 all: no spaces, commas or control characters, so a name reads the same
602 in a policy principal, a CSV header and the CLI), with no duplicates.
603 Raises InvalidIdentityPayloadError, naming the first problem.
604 """
605 if not isinstance(value, (list, tuple)):
606 raise InvalidIdentityPayloadError("subscriptions must be a list of names")
607 if len(value) > MAX_ACCOUNT_SUBSCRIPTIONS:
608 raise InvalidIdentityPayloadError(
609 f"subscriptions has {len(value)} names; at most {MAX_ACCOUNT_SUBSCRIPTIONS} are allowed"
610 )
611 seen: set[str] = set()
612 for name in value:
613 if not isinstance(name, str):
614 raise InvalidIdentityPayloadError("subscriptions must be a list of names")
615 if not _SUBSCRIPTION_NAME_RE.fullmatch(name):
616 raise InvalidIdentityPayloadError(
617 "each subscription name must be 1-"
618 f"{MAX_SUBSCRIPTION_NAME_LENGTH} characters: a letter or digit, then letters, "
619 "digits and _ . : @ + -"
620 )
621 if name in seen:
622 raise InvalidIdentityPayloadError(f"subscriptions lists {name} twice")
623 seen.add(name)
624 return tuple(value)
625
626
627def _account_rows_for(
628 path: Path, account_id: str
629) -> tuple[list[str], list[dict[str, Any]], list[dict[str, Any]]]:
630 """(fieldnames, every row, the rows for account_id) of accounts.tsv, raw.
631
632 Edited as raw rows and written back whole (_write_account_rows): a
633 rewrite through _read_accounts would silently drop every row that does
634 not parse. Raises AccountNotFoundError when no row names the id. The
635 caller holds the accounts lock.
636 """
637 fieldnames: list[str] = list(ACCOUNT_FIELDS)
638 rows: list[dict[str, Any]] = []
639 if path.exists():
640 with path.open(newline="") as handle:
641 reader = csv.DictReader(handle, delimiter="\t")
642 fieldnames += [name for name in reader.fieldnames or () if name not in fieldnames]
643 for row in reader:
644 if row:
645 row.pop(None, None)
646 rows.append(row)
647 matching = [
648 row for row in rows
649 if isinstance(row.get("account_id"), str) and row["account_id"].strip() == account_id
650 ]
651 if not matching:
652 raise AccountNotFoundError(f"Account not found: {account_id}")
653 return fieldnames, rows, matching
654
655
656def _parsed_account_row(row: Mapping[str, Any], account_id: str) -> IdentityAccount:
657 try:
658 return _account_from_row(row)
659 except (InvalidIdentityPayloadError, ValueError, TypeError, AttributeError) as exc:
660 raise InvalidIdentityPayloadError(
661 f"The accounts.tsv row for {account_id} does not parse ({exc}); fix it by hand"
662 ) from exc
663
664
665def _append_ops_event(event: str, *, base_dir: Path | str, **details: Any) -> None:
666 """One ops `auth` line from this module, best effort (as object_server's)."""
667 import object_correlation
668 import object_ops_log
669
670 try:
671 object_ops_log.append_event(
672 object_ops_log.AUTH,
673 {"event": event, **details, "correlation_id": object_correlation.current_correlation_id()},
674 base_dir=base_dir,
675 )
676 except (OSError, ValueError):
677 pass
678
679
680def account_record(
681 account_id: str | None,
682 *,
683 base_dir: Path | str = DEFAULT_DATA_DIR,
684) -> AccountRecord | None:
685 """The account's current standing and subscriptions, or None for no id or no row.
686
687 Stat-cached like user_record. Raises OSError when accounts.tsv exists
688 but cannot be read.
689 """
690 if not isinstance(account_id, str) or not account_id.strip():
691 return None
692 return _account_records(accounts_path(base_dir)).get(account_id.strip())
693
694
695def account_refuses(
696 account_id: str | None,
697 *,
698 base_dir: Path | str = DEFAULT_DATA_DIR,
699) -> bool:
700 """True when credentials of a member of this account must be refused:
701 the account has a row and it is not active (or does not parse). An id
702 with no row refuses nothing (see account_record): this is for an account
703 id someone else asserts (a gateway, an identity source). For the
704 account a local user's row names, use member_account, which refuses a
705 missing row too."""
706 record = account_record(account_id, base_dir=base_dir)
707 return record is not None and not record.active
708
709
710LEFTOVER_PASSWORD_REFUSE = "refuse"
711LEFTOVER_PASSWORD_CLEAR = "clear"
712LEFTOVER_PASSWORD_KEEP = "keep"
713_LEFTOVER_PASSWORD_MODES = frozenset({LEFTOVER_PASSWORD_REFUSE, LEFTOVER_PASSWORD_CLEAR, LEFTOVER_PASSWORD_KEEP})
714
715
716def member_account(
717 user_id: str,
718 account_id: str | None,
719 *,
720 base_dir: Path | str = DEFAULT_DATA_DIR,
721) -> AccountRecord | None:
722 """The account a registered user's row names, failing closed.
723
724 None when the row names no account: a single-user install, or a user
725 created before accounts existed (an empty account_id, or a users.tsv
726 with no account_id column), never looks at accounts.tsv. Otherwise the
727 account's AccountRecord, which may be inactive (the caller refuses that,
728 see _refused_by_account). Raises AccountUnusableError when the account
729 has no row (or there is no accounts.tsv) or its row does not parse, and
730 OSError when accounts.tsv cannot be read.
731
732 Also raises AccountUnusableError (ACCOUNT_ROWS_CONFLICTING), whatever
733 account_id says, when the user has several rows in users.tsv naming
734 different accounts: their merged record names no account, and must not
735 pass for a user with none (which would skip every account check).
736 OSError when users.tsv cannot be read.
737 """
738 record = user_record(user_id, base_dir=base_dir)
739 if record is not None and record.conflicting_accounts:
740 raise AccountUnusableError(
741 user_id,
742 ",".join(account or "(none)" for account in record.conflicting_accounts),
743 ACCOUNT_ROWS_CONFLICTING,
744 )
745 if not isinstance(account_id, str) or not account_id.strip():
746 return None
747 record = account_record(account_id, base_dir=base_dir)
748 if record is None:
749 raise AccountUnusableError(user_id, account_id.strip(), ACCOUNT_ROW_MISSING)
750 if not record.parsed:
751 raise AccountUnusableError(user_id, account_id.strip(), ACCOUNT_ROW_UNPARSED)
752 return record
753
754
755def create_user(
756 payload: Mapping[str, Any],
757 *,
758 base_dir: Path | str = DEFAULT_DATA_DIR,
759 now: datetime | None = None,
760 leftover_password: str = LEFTOVER_PASSWORD_REFUSE,
761) -> dict[str, Any]:
762 """Create a user and return its public payload.
763
764 Credentials already stored under the new id -- a password, sessions
765 still signed in, API keys: credentials.tsv, sessions.tsv and
766 api_keys.tsv outlive a user removed by hand, and a create can stop
767 between its writes -- would become the new user's: whoever holds such a
768 token is signed in as the new user once its row exists.
769 ``leftover_password`` says what to do about them: "refuse" (the
770 default) raises LeftoverCredentialsError and creates nothing; "clear"
771 removes the password, ends the sessions and deletes the keys, logs a
772 warning and creates the user, for a caller whose user must start with
773 no credentials anyway (if clearing fails, nothing is created); "keep"
774 is only for a caller that wrote the password itself a moment ago for
775 this very user (first-time setup, create-superuser): the password is
776 kept, but leftover sessions and keys are cleared as for "clear", since
777 that caller wrote neither."""
778 if leftover_password not in _LEFTOVER_PASSWORD_MODES:
779 raise ValueError(f"leftover_password must be one of: {', '.join(sorted(_LEFTOVER_PASSWORD_MODES))}")
780 account_id = _optional_identity_id(payload.get("account_id"), "account_id")
781 if account_id is not None:
782 _find_account(account_id, base_dir=base_dir)
783
784 created_at = _format_timestamp(now or _now())
785 user = IdentityUser(
786 user_id=_identity_id(payload.get("user_id"), "user_id", prefix="usr"),
787 account_id=account_id,
788 email=_optional_text(payload.get("email"), "email"),
789 display_name=_optional_text(payload.get("display_name"), "display_name") or "",
790 status=_status(payload.get("status")),
791 roles=_string_tuple(payload.get("roles", ()), "roles"),
792 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subscriptions"),
793 created_at=created_at,
794 updated_at=created_at,
795 identity_source=_optional_identity_id(payload.get("identity_source"), "identity_source"),
796 )
797
798 path = users_path(base_dir)
799 with _file_lock(path):
800 users = _read_users(path)
801 if any(existing.user_id == user.user_id for existing in users):
802 raise InvalidIdentityPayloadError(f"User already exists: {user.user_id}")
803 _no_leftover_credentials(user.user_id, mode=leftover_password, base_dir=base_dir, now=now)
804 users.append(user)
805 _write_users(path, users)
806
807 return user.public_payload()
808
809
810def leftover_credentials(
811 user_id: str,
812 *,
813 base_dir: Path | str = DEFAULT_DATA_DIR,
814 now: datetime | None = None,
815) -> dict[str, Any]:
816 """What is stored under a user id apart from its users.tsv row.
817
818 {"password": bool, "sessions": int, "api_keys": int}: whether
819 credentials.tsv has a row for it, how many of its sessions are still
820 signed in (not ended, not expired), how many API keys it holds. For an
821 id with no user these are leftovers (see create_user). Raises OSError
822 when one of the files cannot be read: a store that cannot say is not
823 a store with nothing in it.
824 """
825 import object_api_keys # both import this module
826 import object_credentials
827
828 checked_at = now or _now()
829 sessions = sum(
830 1
831 for session in _read_sessions(sessions_path(base_dir))
832 if session.user_id == user_id and session.is_active(checked_at)
833 )
834 return {
835 "password": object_credentials.has_password(user_id, base_dir=base_dir),
836 "sessions": sessions,
837 "api_keys": len(object_api_keys.list_api_keys(user_id, base_dir=base_dir)),
838 }
839
840
841def clear_leftover_credentials(
842 user_id: str,
843 *,
844 base_dir: Path | str = DEFAULT_DATA_DIR,
845 now: datetime | None = None,
846) -> dict[str, Any]:
847 """Remove what is stored under a user id that has no user: the operator's
848 way forward when create_user refuses leftovers.
849
850 Removes the password, ends every session and deletes every API key under
851 the id; returns {"password": bool, "sessions": int, "api_keys": int},
852 what was removed. Raises InvalidIdentityPayloadError when the id has a
853 user (its credentials are its own: use remove-password, sign-out or key
854 revocation), and whatever the stores raise when they cannot be written.
855 """
856 normalized = _identity_id(user_id, "user_id")
857 path = users_path(base_dir)
858 with _file_lock(path):
859 if user_record(normalized, base_dir=base_dir) is not None:
860 raise InvalidIdentityPayloadError(
861 f"User {normalized} exists; its credentials are not leftovers"
862 )
863 return _clear_leftovers(normalized, password=True, base_dir=base_dir, now=now)
864
865
866def _clear_leftovers(user_id: str, *, password: bool, base_dir: Path | str, now: datetime | None) -> dict[str, Any]:
867 import object_api_keys # both import this module
868 import object_credentials
869
870 # Any failure here raises before the caller writes a user, since a new user would take over whatever
871 # is left. Sessions first, so the count is theirs (remove_password would end them too).
872 sessions = revoke_user_sessions(user_id, base_dir=base_dir, now=now)
873 api_keys = object_api_keys.revoke_user_api_keys(user_id, base_dir=base_dir)
874 removed = password and object_credentials.remove_password(user_id, base_dir=base_dir, now=now)
875 return {"password": bool(removed), "sessions": sessions, "api_keys": api_keys}
876
877
878def _no_leftover_credentials(user_id: str, *, mode: str, base_dir: Path | str, now: datetime | None) -> None:
879 """Refuse, or clear, credentials stored under an id that has no user yet (see create_user)."""
880 found = leftover_credentials(user_id, base_dir=base_dir, now=now)
881 keep_password = mode == LEFTOVER_PASSWORD_KEEP
882 if keep_password:
883 found["password"] = False # the caller wrote it for this user a moment ago
884 if not (found["password"] or found["sessions"] or found["api_keys"]):
885 return
886 if mode == LEFTOVER_PASSWORD_REFUSE:
887 raise LeftoverCredentialsError(
888 user_id, password=found["password"], sessions=found["sessions"], api_keys=found["api_keys"]
889 )
890 removed = _clear_leftovers(user_id, password=not keep_password, base_dir=base_dir, now=now)
891 _LOG.warning(
892 "Cleared credentials left under user id %s, which had no user, before creating that user: "
893 "password removed: %s, sessions ended: %d, API keys deleted: %d",
894 user_id, "yes" if removed["password"] else "no", removed["sessions"], removed["api_keys"],
895 )
896
897
898def list_users(
899 *,
900 account_id: str | None = None,
901 base_dir: Path | str = DEFAULT_DATA_DIR,
902) -> list[dict[str, Any]]:
903 """Return all users, optionally scoped to one account."""
904 normalized_account_id = _optional_identity_id(account_id, "account_id")
905 users = _read_users(users_path(base_dir))
906 if normalized_account_id is not None:
907 users = [user for user in users if user.account_id == normalized_account_id]
908 return [user.public_payload() for user in users]
909
910
911def get_user(
912 user_id: str,
913 *,
914 base_dir: Path | str = DEFAULT_DATA_DIR,
915) -> dict[str, Any]:
916 """Return one user payload."""
917 return _find_user(user_id, base_dir=base_dir).public_payload()
918
919
920def find_users_by_email(
921 email: str,
922 *,
923 base_dir: Path | str = DEFAULT_DATA_DIR,
924) -> list[dict[str, Any]]:
925 """Return every user whose email matches, ignoring case (any status)."""
926 wanted = (email or "").strip().casefold()
927 if not wanted:
928 return []
929 return [
930 user.public_payload()
931 for user in _read_users(users_path(base_dir))
932 if (user.email or "").strip().casefold() == wanted
933 ]
934
935
936def email_key(value: Any) -> str:
937 """One address's identity: spaces trimmed, Unicode NFKC normalised and case folded.
938
939 NFKC folds compatibility forms that look the same as plain letters
940 (fullwidth letters such as U+FF41, the "fi" ligature U+FB01, an accented
941 letter written precomposed or combining), and casefold folds case (German
942 sharp s and "ss" too), so every way of writing one
943 address maps to one key. Normalised again after folding, as casefold can
944 undo NFKC. Mixed-script lookalikes (Cyrillic U+0430 for Latin "a") are
945 different characters and keep different keys: telling those apart needs
946 the confusables table, which the standard library does not have."""
947 text = unicodedata.normalize("NFKC", str(value or "")).strip()
948 return unicodedata.normalize("NFKC", text.casefold()).strip()
949
950
951def find_users_by_address(
952 email: str,
953 *,
954 statuses: Iterable[str] | None = None,
955 base_dir: Path | str = DEFAULT_DATA_DIR,
956) -> list[dict[str, Any]]:
957 """The users an address names, for sign-in, signup and reset, optionally only in these statuses.
958
959 Users whose stored address matches ignoring case (find_users_by_email's
960 rule) when there are any; otherwise those whose address has the same
961 email_key. The case-only match comes first so that two users stored before
962 lookalikes were folded together, under addresses that now share a key,
963 each still sign in under their own spelling instead of both being
964 refused as ambiguous."""
965 wanted = (email or "").strip().casefold()
966 key = email_key(email)
967 if not wanted or not key:
968 return []
969 allowed = None if statuses is None else frozenset(statuses)
970 users = [
971 user for user in _read_users(users_path(base_dir))
972 if allowed is None or user.status in allowed
973 ]
974 exact = [user for user in users if (user.email or "").strip().casefold() == wanted]
975 found = exact or [user for user in users if user.email and email_key(user.email) == key]
976 return [user.public_payload() for user in found]
977
978
979def set_user_status(
980 user_id: str,
981 status: str,
982 *,
983 display_name: str | None = None,
984 base_dir: Path | str = DEFAULT_DATA_DIR,
985 now: datetime | None = None,
986) -> dict[str, Any]:
987 """Change one user's status (and, when given, display name) and return its public payload.
988
989 Moving a user to any status but active also revokes every session and API
990 key they hold (change_user_status says why).
991 """
992 return change_user_status(
993 user_id, status, display_name=display_name, base_dir=base_dir, now=now
994 )["user"]
995
996
997def change_user_status(
998 user_id: str,
999 status: str,
1000 *,
1001 display_name: str | None = None,
1002 base_dir: Path | str = DEFAULT_DATA_DIR,
1003 now: datetime | None = None,
1004) -> dict[str, Any]:
1005 """Change one user's status; return the user and what was revoked.
1006
1007 Leaving "active" revokes every session (marked revoked) and deletes every
1008 API key the user holds. Refusing them at resolution time (user_standing)
1009 is what locks the user out, and it does so on its own -- also for a status
1010 edited into users.tsv by hand or by another process. Revocation is for
1011 the day they are re-enabled: without it, re-enabling silently resurrects
1012 every credential they had, including a key on a laptop that left with
1013 them. So re-enabling restores the person, not their old tokens; they sign
1014 in again and mint new keys. Revocation runs after the status write, so
1015 there is no moment where the user is active with credentials half gone.
1016 """
1017 if not isinstance(status, str) or not status.strip():
1018 raise InvalidIdentityPayloadError("status is required")
1019 new_status = _status(status)
1020 found = _update_user(
1021 user_id,
1022 lambda user: replace(
1023 user,
1024 status=new_status,
1025 display_name=user.display_name if display_name is None else display_name,
1026 ),
1027 base_dir=base_dir,
1028 now=now,
1029 )
1030 sessions_revoked = api_keys_revoked = 0
1031 if new_status != ACTIVE_STATUS:
1032 sessions_revoked, api_keys_revoked = _revoke_user_credentials(
1033 found.user_id, base_dir=base_dir, now=now
1034 )
1035 return {
1036 "user": found.public_payload(),
1037 "sessions_revoked": sessions_revoked,
1038 "api_keys_revoked": api_keys_revoked,
1039 }
1040
1041
1042def set_user_roles(
1043 user_id: str,
1044 roles: Any,
1045 *,
1046 base_dir: Path | str = DEFAULT_DATA_DIR,
1047 now: datetime | None = None,
1048) -> dict[str, Any]:
1049 """Replace one user's roles; return the user and how many sessions were revoked.
1050
1051 Sessions and API keys both pick a role change up on the next request
1052 (resolve_session_token and the key path read the user's row). Every
1053 session of this user that was minted holding a role outside the new set
1054 is also revoked, as it was when sessions kept the roles they were minted
1055 with; sessions whose roles all survive are left alone, so granting a role
1056 signs nobody out and applies at once.
1057 """
1058 if not isinstance(roles, (list, tuple)):
1059 raise InvalidIdentityPayloadError("roles must be a list of strings")
1060 new_roles = _string_tuple(list(roles), "roles")
1061 found = _update_user(
1062 user_id, lambda user: replace(user, roles=new_roles), base_dir=base_dir, now=now
1063 )
1064 allowed = set(new_roles)
1065 revoked = _revoke_sessions_where(
1066 lambda session: session.user_id == found.user_id and not set(session.roles) <= allowed,
1067 base_dir=base_dir,
1068 now=now,
1069 )
1070 return {"user": found.public_payload(), "sessions_revoked": revoked}
1071
1072
1073def set_user_identity_source(
1074 user_id: str,
1075 source: str | None,
1076 *,
1077 base_dir: Path | str = DEFAULT_DATA_DIR,
1078 now: datetime | None = None,
1079) -> dict[str, Any]:
1080 """Link a local user to an identity source by name (None or "" unlinks).
1081
1082 Linked, a remote identity from that source naming this user id is
1083 accepted as this user (still subject to the row's status and account);
1084 unlinked, it is refused. Nothing else about the user changes.
1085 """
1086 linked = _optional_identity_id(source, "identity_source")
1087 found = _update_user(
1088 user_id, lambda user: replace(user, identity_source=linked), base_dir=base_dir, now=now
1089 )
1090 return found.public_payload()
1091
1092
1093def offboard_user(
1094 user_id: str,
1095 *,
1096 clear_roles: bool = False,
1097 base_dir: Path | str = DEFAULT_DATA_DIR,
1098 now: datetime | None = None,
1099) -> dict[str, Any]:
1100 """Disable a user and revoke every session and API key, in one step.
1101
1102 With clear_roles the user's roles are emptied in the same users.tsv write,
1103 so a later re-enable starts from no authority rather than from whatever
1104 the person held when they left. Returns the user, the counts, and the
1105 roles that were cleared (for the audit line). Idempotent: offboarding an
1106 already offboarded user revokes nothing and succeeds.
1107
1108 Not touched, deliberately: the password credential (disabled already
1109 refuses password login, and re-enabling should not force a reset), the
1110 user's own provider service keys (their secrets, not credentials to this
1111 server), and roles granted through the permission policy's user_roles map
1112 (policy, not identity -- an operator edits it on purpose).
1113 """
1114 cleared: tuple[str, ...] = ()
1115
1116 def disable(user: IdentityUser) -> IdentityUser:
1117 nonlocal cleared
1118 if clear_roles:
1119 cleared = user.roles
1120 return replace(user, status=DISABLED_STATUS, roles=())
1121 return replace(user, status=DISABLED_STATUS)
1122
1123 found = _update_user(user_id, disable, base_dir=base_dir, now=now)
1124 sessions_revoked, api_keys_revoked = _revoke_user_credentials(
1125 found.user_id, base_dir=base_dir, now=now
1126 )
1127 return {
1128 "user": found.public_payload(),
1129 "sessions_revoked": sessions_revoked,
1130 "api_keys_revoked": api_keys_revoked,
1131 "roles_cleared": list(cleared),
1132 }
1133
1134
1135def user_standing(
1136 user_id: str | None,
1137 *,
1138 base_dir: Path | str = DEFAULT_DATA_DIR,
1139) -> str:
1140 """Return STANDING_ACTIVE, STANDING_INACTIVE or STANDING_ABSENT for a user id.
1141
1142 See the STANDING_* constants. Cheap enough to call on every request: the
1143 parse is cached against users.tsv's stat signature.
1144 """
1145 record = user_record(user_id, base_dir=base_dir)
1146 if record is None:
1147 return STANDING_ABSENT
1148 return STANDING_ACTIVE if record.active else STANDING_INACTIVE
1149
1150
1151def user_record(
1152 user_id: str | None,
1153 *,
1154 base_dir: Path | str = DEFAULT_DATA_DIR,
1155) -> UserRecord | None:
1156 """The user's current standing and roles from users.tsv, or None for no row.
1157
1158 Stat-cached like user_standing (the same cache). Raises OSError when
1159 users.tsv exists but cannot be read.
1160 """
1161 if not isinstance(user_id, str) or not user_id.strip():
1162 return None
1163 return _user_standings(users_path(base_dir)).get(user_id.strip())
1164
1165
1166def users_file_present(base_dir: Path | str = DEFAULT_DATA_DIR) -> bool:
1167 """False when users.tsv is not there at all (or its directory cannot be searched).
1168
1169 A credential bound to a registered user (see ROLES_FROM_*) whose user has
1170 no row is dead -- unless there is no users file to have a row in: that is
1171 a store that cannot be read, not a deleted user, and must not revoke every
1172 session on the box.
1173 """
1174 try:
1175 os.stat(users_path(base_dir))
1176 except OSError:
1177 return False
1178 return True
1179
1180
1181def credential_owner_allowed(
1182 user_id: str | None,
1183 *,
1184 base_dir: Path | str = DEFAULT_DATA_DIR,
1185 require_known_user: bool = False,
1186) -> bool:
1187 """True when a session or API key naming this user may authenticate."""
1188 standing = user_standing(user_id, base_dir=base_dir)
1189 if standing == STANDING_ACTIVE:
1190 return True
1191 return standing == STANDING_ABSENT and not require_known_user
1192
1193
1194def _update_user(
1195 user_id: str,
1196 change: Any,
1197 *,
1198 base_dir: Path | str,
1199 now: datetime | None,
1200) -> IdentityUser:
1201 """Apply `change` to one user row under the users lock and write it back."""
1202 normalized = _identity_id(user_id, "user_id")
1203 path = users_path(base_dir)
1204 updated_at = _format_timestamp(now or _now())
1205 with _file_lock(path):
1206 users = _read_users(path)
1207 found: IdentityUser | None = None
1208 for index, user in enumerate(users):
1209 if user.user_id == normalized:
1210 found = replace(change(user), updated_at=updated_at)
1211 users[index] = found
1212 break
1213 if found is None:
1214 raise UserNotFoundError(f"User not found: {normalized}")
1215 _write_users(path, users)
1216 return found
1217
1218
1219def _revoke_user_credentials(
1220 user_id: str,
1221 *,
1222 base_dir: Path | str,
1223 now: datetime | None,
1224) -> tuple[int, int]:
1225 # Imported here: object_api_keys imports this module for hash_token and
1226 # user_standing.
1227 import object_api_keys
1228
1229 sessions_revoked = revoke_user_sessions(user_id, base_dir=base_dir, now=now)
1230 api_keys_revoked = object_api_keys.revoke_user_api_keys(user_id, base_dir=base_dir)
1231 return sessions_revoked, api_keys_revoked
1232
1233
1234def create_session(
1235 payload: Mapping[str, Any],
1236 *,
1237 base_dir: Path | str = DEFAULT_DATA_DIR,
1238 now: datetime | None = None,
1239 require_known_user: bool = False,
1240) -> dict[str, Any]:
1241 """Create a session and return its public payload plus the one-time token."""
1242 created_at = now or _now()
1243 token = secrets.token_urlsafe(32)
1244 user_id = _required_text(payload.get("user_id"), "user_id")
1245 user = _lookup_user(user_id, base_dir=base_dir)
1246
1247 if user is None and require_known_user:
1248 raise UserNotFoundError(f"User not found: {user_id}")
1249 # The standing check also catches a row that exists but does not parse,
1250 # which _lookup_user reports as no user at all.
1251 if (user is not None and not user.is_active()) or user_standing(
1252 user_id, base_dir=base_dir
1253 ) == STANDING_INACTIVE:
1254 raise InvalidSessionPayloadError(f"User is not active: {user_id}")
1255 # A registered user's account must have a row that parses (fail closed,
1256 # AccountUnusableError) and be active, read as resolve_session_token
1257 # reads it on every request.
1258 member = member_account(user.user_id, user.account_id, base_dir=base_dir) if user is not None else None
1259 if member is not None and not member.active:
1260 raise InvalidSessionPayloadError(f"Account is not active: {user.account_id}")
1261 account = _session_account(payload, user, base_dir=base_dir)
1262 if account is not None and not account.is_active():
1263 raise InvalidSessionPayloadError(f"Account is not active: {account.account_id}")
1264
1265 default_roles = user.roles if user is not None else ()
1266 if user is None:
1267 roles_from = ""
1268 elif "roles" in payload or "subscriptions" in payload:
1269 roles_from = ROLES_FROM_SESSION
1270 else:
1271 roles_from = ROLES_FROM_USER
1272 default_subscriptions = _merged_strings(
1273 user.subscriptions if user is not None else (),
1274 account.subscriptions if account is not None else (),
1275 )
1276
1277 session = IdentitySession(
1278 session_id=_new_session_id(),
1279 token_hash=hash_token(token),
1280 user_id=user_id,
1281 account_id=_session_account_id(payload, user, account),
1282 roles=_string_tuple(payload.get("roles", default_roles), "roles"),
1283 subscriptions=_string_tuple(
1284 payload.get("subscriptions", default_subscriptions),
1285 "subscriptions",
1286 ),
1287 label=_optional_text(payload.get("label"), "label") or "",
1288 created_at=_format_timestamp(created_at),
1289 expires_at=_format_timestamp(
1290 created_at + timedelta(seconds=_ttl_seconds(payload.get("ttl_seconds")))
1291 ),
1292 roles_from=roles_from,
1293 )
1294
1295 path = sessions_path(base_dir)
1296 with _file_lock(path):
1297 sessions = _read_sessions(path)
1298 sessions.append(session)
1299 _write_sessions(path, sessions)
1300
1301 return {"session": session.public_payload(), "token": token}
1302
1303
1304def list_sessions(
1305 *,
1306 base_dir: Path | str = DEFAULT_DATA_DIR,
1307) -> list[dict[str, Any]]:
1308 """Return all sessions without raw tokens or token hashes."""
1309 return [session.public_payload() for session in _read_sessions(sessions_path(base_dir))]
1310
1311
1312def get_session(
1313 session_id: str,
1314 *,
1315 base_dir: Path | str = DEFAULT_DATA_DIR,
1316) -> dict[str, Any]:
1317 """Return one public session payload."""
1318 session = _find_session(session_id, base_dir=base_dir)
1319 return session.public_payload()
1320
1321
1322def revoke_session(
1323 session_id: str,
1324 *,
1325 base_dir: Path | str = DEFAULT_DATA_DIR,
1326 now: datetime | None = None,
1327) -> dict[str, Any]:
1328 """Mark one session revoked and return its public payload."""
1329 if not validate_session_id(session_id):
1330 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
1331
1332 path = sessions_path(base_dir)
1333 revoked_at = _format_timestamp(now or _now())
1334 with _file_lock(path):
1335 sessions = _read_sessions(path)
1336 updated: list[IdentitySession] = []
1337 found: IdentitySession | None = None
1338 for session in sessions:
1339 if session.session_id == session_id:
1340 found = replace(session, revoked_at=session.revoked_at or revoked_at)
1341 updated.append(found)
1342 else:
1343 updated.append(session)
1344
1345 if found is None:
1346 raise SessionNotFoundError(f"Session not found: {session_id}")
1347
1348 _write_sessions(path, updated)
1349 return found.public_payload()
1350
1351
1352def revoke_user_sessions(
1353 user_id: str,
1354 *,
1355 base_dir: Path | str = DEFAULT_DATA_DIR,
1356 now: datetime | None = None,
1357 keep_session_id: str | None = None,
1358) -> int:
1359 """Revoke every unrevoked session of one user; return how many.
1360
1361 keep_session_id spares that one session, and only if it is this user's:
1362 a user changing their own password stays signed in where they are.
1363 """
1364 return _revoke_sessions_where(
1365 lambda session: session.user_id == user_id
1366 and not (keep_session_id and session.session_id == keep_session_id),
1367 base_dir=base_dir,
1368 now=now,
1369 )
1370
1371
1372def _revoke_sessions_where(
1373 predicate: Any,
1374 *,
1375 base_dir: Path | str,
1376 now: datetime | None,
1377) -> int:
1378 path = sessions_path(base_dir)
1379 revoked_at = _format_timestamp(now or _now())
1380 count = 0
1381 with _file_lock(path):
1382 sessions = _read_sessions(path)
1383 updated: list[IdentitySession] = []
1384 for session in sessions:
1385 if not session.revoked_at and predicate(session):
1386 session = replace(session, revoked_at=revoked_at)
1387 count += 1
1388 updated.append(session)
1389 if count:
1390 _write_sessions(path, updated)
1391 return count
1392
1393
1394def resolve_session_token(
1395 token: str | None,
1396 *,
1397 base_dir: Path | str = DEFAULT_DATA_DIR,
1398 now: datetime | None = None,
1399 require_known_user: bool = False,
1400 raise_account_unusable: bool = False,
1401) -> IdentitySession | None:
1402 """Return the active session matching a raw token, if any.
1403
1404 A live session whose user is no longer active (user_standing) is no
1405 session: disabling a user must lock out the sessions they already hold,
1406 not only refuse new ones. With require_known_user, a session naming a
1407 user with no row is refused too.
1408
1409 The roles, account and subscriptions on the returned session are the
1410 user's current ones (see ROLES_FROM_*), read from users.tsv (and
1411 accounts.tsv for the account's subscriptions) through the same stat
1412 cache, so a role or subscription removed, or a move between accounts,
1413 applies on the next request. A session whose user is
1414 disabled, or was registered and no longer has a row, is ended here as
1415 well as refused (marked revoked, like a sign-out), so re-enabling or
1416 re-creating the user does not bring it back. A row that does not parse
1417 refuses the session without ending it: that may be a typo being fixed.
1418 The same holds for the user's account (or, for an ad hoc session with no
1419 user row, the account it was minted naming): while its row in
1420 accounts.tsv is not active the session is refused, and ended unless the
1421 row does not parse (set_account_status). A registered user whose row
1422 names an account with no row at all, or whose account row does not
1423 parse, is refused too (member_account), and nothing is ended; with
1424 raise_account_unusable the caller gets AccountUnusableError instead of
1425 None, to tell the user and the operator why. A user whose row names no
1426 account never reads accounts.tsv. An ad hoc session (no user row)
1427 naming an account with no row is not refused: gateways name accounts
1428 this box need not know.
1429
1430 Raises OSError when users.tsv or accounts.tsv cannot be read, or when
1431 users.tsv is missing and the session is bound to a registered user: the
1432 caller answers 503 under enforcement rather than guessing.
1433 """
1434 if not token:
1435 return None
1436
1437 token_hash = hash_token(token)
1438 checked_at = now or _now()
1439 snapshot = _sessions_snapshot(sessions_path(base_dir))
1440 # First matching row wins; an inactive first match means no session. The
1441 # dict only locates the row; the comparison stays constant-time.
1442 position = snapshot.first_position.get(token_hash)
1443 bad = snapshot.first_non_ascii
1444 if bad is not None and (position is None or position > bad):
1445 # The linear scan this replaces would have raised TypeError at this row.
1446 hmac.compare_digest(snapshot.sessions[bad].token_hash, token_hash)
1447 if position is None:
1448 return None
1449 session = snapshot.sessions[position]
1450 if not hmac.compare_digest(session.token_hash, token_hash):
1451 return None
1452 if not session.is_active(checked_at):
1453 return None
1454 record = user_record(session.user_id, base_dir=base_dir)
1455 if record is None:
1456 if session.roles_from:
1457 # Minted for a registered user who has no row now: deleted.
1458 if not users_file_present(base_dir):
1459 raise FileNotFoundError(f"Identity users file is missing: {users_path(base_dir)}")
1460 _end_session(session, base_dir=base_dir, now=now)
1461 return None
1462 if require_known_user:
1463 return None
1464 # An ad hoc session minted naming an account is that account's too.
1465 account = account_record(session.account_id, base_dir=base_dir)
1466 if _refused_by_account(session, account, base_dir=base_dir, now=now):
1467 return None
1468 return session
1469 if not record.active:
1470 if record.roles is not None:
1471 _end_session(session, base_dir=base_dir, now=now)
1472 return None
1473 try:
1474 account = member_account(session.user_id, record.account_id, base_dir=base_dir)
1475 except AccountUnusableError:
1476 if raise_account_unusable:
1477 raise
1478 return None
1479 if _refused_by_account(session, account, base_dir=base_dir, now=now):
1480 return None
1481 current = record.roles or ()
1482 if session.roles_from == ROLES_FROM_USER:
1483 roles = current
1484 account_id = record.account_id
1485 subscriptions = _current_subscriptions(record, account)
1486 else:
1487 roles = tuple(role for role in session.roles if role in current)
1488 account_id = session.account_id if session.account_id == record.account_id else None
1489 subscriptions = ()
1490 if session.subscriptions:
1491 held = _current_subscriptions(record, account)
1492 subscriptions = tuple(name for name in session.subscriptions if name in held)
1493 if (roles, account_id, subscriptions) != (session.roles, session.account_id, session.subscriptions):
1494 session = replace(session, roles=roles, account_id=account_id, subscriptions=subscriptions)
1495 return session
1496
1497
1498def _refused_by_account(
1499 session: IdentitySession,
1500 account: AccountRecord | None,
1501 *,
1502 base_dir: Path | str,
1503 now: datetime | None,
1504) -> bool:
1505 """True when the session's account is not active: refuse the session.
1506
1507 A disabled account's sessions are ended as well, like a disabled user's,
1508 so a disable written by hand or by another process does not leave them
1509 to come back on re-enable (set_account_status ends them at once). A row
1510 that does not parse refuses without ending, as for users.
1511 """
1512 if account is None or account.active:
1513 return False
1514 if account.parsed:
1515 _end_session(session, base_dir=base_dir, now=now)
1516 return True
1517
1518
1519def _current_subscriptions(record: UserRecord, account: AccountRecord | None) -> tuple[str, ...]:
1520 """The user's own subscriptions plus their account's (account_record of
1521 record.account_id), as create_session merges them, from the rows as they
1522 are now. An account that is missing or not active contributes none."""
1523 own = record.subscriptions or ()
1524 if not record.account_id or account is None or not account.active:
1525 return own
1526 return _merged_strings(own, account.subscriptions)
1527
1528
1529def _end_session(
1530 session: IdentitySession,
1531 *,
1532 base_dir: Path | str,
1533 now: datetime | None,
1534) -> None:
1535 """Mark a session whose user is gone or disabled revoked, best effort.
1536
1537 The refusal does not depend on this write: the user's row refuses the
1538 session on every request anyway. It is what keeps the session from
1539 coming back if the user is re-enabled or re-created.
1540 """
1541 try:
1542 _revoke_sessions_where(
1543 lambda stored: stored.session_id == session.session_id
1544 and stored.token_hash == session.token_hash,
1545 base_dir=base_dir,
1546 now=now,
1547 )
1548 except OSError:
1549 pass
1550
1551
1552def hash_token(token: str) -> str:
1553 """Return the stored hash for a raw session token."""
1554 return "sha256:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
1555
1556
1557def validate_session_id(session_id: str) -> bool:
1558 """Return True when a session id is route-safe."""
1559 if not isinstance(session_id, str):
1560 return False
1561 return object_ids.is_uuid4(session_id) or bool(_LEGACY_SESSION_ID_RE.fullmatch(session_id))
1562
1563
1564def _find_session(
1565 session_id: str,
1566 *,
1567 base_dir: Path | str = DEFAULT_DATA_DIR,
1568) -> IdentitySession:
1569 if not validate_session_id(session_id):
1570 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
1571
1572 for session in _read_sessions(sessions_path(base_dir)):
1573 if session.session_id == session_id:
1574 return session
1575
1576 raise SessionNotFoundError(f"Session not found: {session_id}")
1577
1578
1579def _find_account(
1580 account_id: str,
1581 *,
1582 base_dir: Path | str = DEFAULT_DATA_DIR,
1583) -> IdentityAccount:
1584 normalized = _identity_id(account_id, "account_id")
1585 for account in _read_accounts(accounts_path(base_dir)):
1586 if account.account_id == normalized:
1587 return account
1588 raise AccountNotFoundError(f"Account not found: {normalized}")
1589
1590
1591def _find_user(
1592 user_id: str,
1593 *,
1594 base_dir: Path | str = DEFAULT_DATA_DIR,
1595) -> IdentityUser:
1596 normalized = _identity_id(user_id, "user_id")
1597 for user in _read_users(users_path(base_dir)):
1598 if user.user_id == normalized:
1599 return user
1600 raise UserNotFoundError(f"User not found: {normalized}")
1601
1602
1603def _lookup_user(
1604 user_id: str,
1605 *,
1606 base_dir: Path | str = DEFAULT_DATA_DIR,
1607) -> IdentityUser | None:
1608 try:
1609 return _find_user(user_id, base_dir=base_dir)
1610 except UserNotFoundError:
1611 return None
1612
1613
1614def _lookup_account(
1615 account_id: str | None,
1616 *,
1617 base_dir: Path | str = DEFAULT_DATA_DIR,
1618) -> IdentityAccount | None:
1619 if account_id is None:
1620 return None
1621 try:
1622 return _find_account(account_id, base_dir=base_dir)
1623 except AccountNotFoundError:
1624 return None
1625
1626
1627@dataclass(frozen=True)
1628class _SessionSnapshot:
1629 """Immutable parsed view of one sessions file (never handed to callers)."""
1630
1631 sessions: tuple[IdentitySession, ...]
1632 first_position: dict[str, int]
1633 first_non_ascii: int | None
1634
1635
1636def _read_sessions(path: Path) -> list[IdentitySession]:
1637 """Return a fresh, caller-owned list of the stored sessions."""
1638 return list(_sessions_snapshot(path).sessions)
1639
1640
1641def _sessions_snapshot(path: Path) -> _SessionSnapshot:
1642 """Return the parsed sessions, re-parsing only when the file changed.
1643
1644 Only parsed rows are cached, never the is-active answer, so expiry is
1645 still judged against the caller's clock on every lookup. The stat is
1646 taken before the parse: a write that lands mid-parse leaves a key that no
1647 longer matches, so the next call re-parses. Other processes write this
1648 file too, hence the stat check on every call.
1649 """
1650 global _SESSION_CACHE_GENERATION
1651 cache_key = str(path)
1652 try:
1653 info = os.stat(path)
1654 except OSError:
1655 # Missing or unreadable: defer to the parser's own behaviour.
1656 _drop_session_cache(cache_key)
1657 return _build_snapshot(_parse_sessions_file(path))
1658 signature = (info.st_mtime_ns, info.st_size, info.st_ino, info.st_ctime_ns)
1659 with _SESSION_CACHE_LOCK:
1660 cached = _SESSION_CACHE.get(cache_key)
1661 if cached is not None and cached[0] == signature:
1662 return cached[1]
1663 generation = _SESSION_CACHE_GENERATION
1664 parsed_at = time.time_ns()
1665 snapshot = _build_snapshot(_parse_sessions_file(path))
1666 racy = parsed_at - info.st_mtime_ns < _SESSION_CACHE_RACY_NS
1667 with _SESSION_CACHE_LOCK:
1668 # A concurrent in-module write bumps the generation; do not store a
1669 # snapshot that may predate it.
1670 if generation == _SESSION_CACHE_GENERATION and not racy:
1671 if cache_key not in _SESSION_CACHE and len(_SESSION_CACHE) >= _SESSION_CACHE_MAX_PATHS:
1672 _SESSION_CACHE.clear()
1673 _SESSION_CACHE[cache_key] = (signature, snapshot)
1674 elif cache_key in _SESSION_CACHE:
1675 del _SESSION_CACHE[cache_key]
1676 return snapshot
1677
1678
1679def _drop_session_cache(cache_key: str) -> None:
1680 global _SESSION_CACHE_GENERATION
1681 with _SESSION_CACHE_LOCK:
1682 _SESSION_CACHE_GENERATION += 1
1683 _SESSION_CACHE.pop(cache_key, None)
1684
1685
1686def _build_snapshot(sessions: list[IdentitySession]) -> _SessionSnapshot:
1687 first_position: dict[str, int] = {}
1688 first_non_ascii: int | None = None
1689 for position, session in enumerate(sessions):
1690 first_position.setdefault(session.token_hash, position)
1691 if first_non_ascii is None and not session.token_hash.isascii():
1692 first_non_ascii = position
1693 return _SessionSnapshot(tuple(sessions), first_position, first_non_ascii)
1694
1695
1696def _parse_sessions_file(path: Path) -> list[IdentitySession]:
1697 if not path.exists():
1698 return []
1699
1700 sessions: list[IdentitySession] = []
1701 with path.open(newline="") as handle:
1702 rows = csv.DictReader(handle, delimiter="\t")
1703 for row in rows:
1704 if not row:
1705 continue
1706 try:
1707 sessions.append(_session_from_row(row))
1708 except (InvalidSessionPayloadError, ValueError):
1709 continue
1710 return sessions
1711
1712
1713def _read_accounts(path: Path) -> list[IdentityAccount]:
1714 if not path.exists():
1715 return []
1716
1717 accounts: list[IdentityAccount] = []
1718 with path.open(newline="") as handle:
1719 rows = csv.DictReader(handle, delimiter="\t")
1720 for row in rows:
1721 if not row:
1722 continue
1723 try:
1724 accounts.append(_account_from_row(row))
1725 except (InvalidIdentityPayloadError, ValueError):
1726 continue
1727 return accounts
1728
1729
1730def _read_users(path: Path) -> list[IdentityUser]:
1731 if not path.exists():
1732 return []
1733
1734 users: list[IdentityUser] = []
1735 with path.open(newline="") as handle:
1736 rows = csv.DictReader(handle, delimiter="\t")
1737 for row in rows:
1738 if not row:
1739 continue
1740 try:
1741 users.append(_user_from_row(row))
1742 except (InvalidIdentityPayloadError, ValueError):
1743 continue
1744 return users
1745
1746
1747def _user_standings(path: Path) -> dict[str, UserRecord]:
1748 """user_id -> UserRecord for every row of users.tsv, cached by stat signature."""
1749 return _stat_cached(path, _parse_user_standings)
1750
1751
1752def _account_records(path: Path) -> dict[str, AccountRecord]:
1753 """account_id -> AccountRecord for every row of accounts.tsv, cached the same way."""
1754 return _stat_cached(path, _parse_account_records)
1755
1756
1757def _stat_cached(path: Path, parse: Any) -> dict[str, Any]:
1758 """parse(path), cached by the file's stat signature.
1759
1760 The same scheme as _sessions_snapshot: stat before parse, re-parse when
1761 the signature moves, never cache a file young enough that a same-size
1762 in-place rewrite could share its signature, and drop on our own writes.
1763 """
1764 cache_key = str(path)
1765 try:
1766 info = os.stat(path)
1767 except OSError:
1768 _drop_standing_cache(cache_key)
1769 return parse(path)
1770 signature = (info.st_mtime_ns, info.st_size, info.st_ino, info.st_ctime_ns)
1771 with _STANDING_CACHE_LOCK:
1772 cached = _STANDING_CACHE.get(cache_key)
1773 if cached is not None and cached[0] == signature:
1774 return cached[1]
1775 generation = _STANDING_CACHE_GENERATION
1776 parsed_at = time.time_ns()
1777 standings = parse(path)
1778 racy = parsed_at - info.st_mtime_ns < _SESSION_CACHE_RACY_NS
1779 with _STANDING_CACHE_LOCK:
1780 if generation == _STANDING_CACHE_GENERATION and not racy:
1781 if cache_key not in _STANDING_CACHE and len(_STANDING_CACHE) >= _SESSION_CACHE_MAX_PATHS:
1782 _STANDING_CACHE.clear()
1783 _STANDING_CACHE[cache_key] = (signature, standings)
1784 elif cache_key in _STANDING_CACHE:
1785 del _STANDING_CACHE[cache_key]
1786 return standings
1787
1788
1789def _drop_standing_cache(cache_key: str) -> None:
1790 global _STANDING_CACHE_GENERATION
1791 with _STANDING_CACHE_LOCK:
1792 _STANDING_CACHE_GENERATION += 1
1793 _STANDING_CACHE.pop(cache_key, None)
1794
1795
1796def _parse_user_standings(path: Path) -> dict[str, UserRecord]:
1797 """Read every row that names a user id, including rows _read_users skips.
1798
1799 A row that fails to parse is inactive, not missing, and an id that appears
1800 twice is active only if every one of its rows is, holds only the roles and
1801 subscriptions every one of its rows gives it, and has an account only if
1802 every row names the same one. When rows that parse name different
1803 accounts (or one names none), conflicting_accounts lists them, so that
1804 member_account refuses the user rather than read "no account".
1805 """
1806 if not path.exists():
1807 return {}
1808 standings: dict[str, UserRecord] = {}
1809 accounts_named: dict[str, set[str]] = {}
1810 with path.open(newline="") as handle:
1811 for row in csv.DictReader(handle, delimiter="\t"):
1812 if not row:
1813 continue
1814 raw_id = row.get("user_id")
1815 user_id = raw_id.strip() if isinstance(raw_id, str) else ""
1816 if not user_id:
1817 continue
1818 try:
1819 user = _user_from_row(row)
1820 record = UserRecord(
1821 user.is_active(), user.roles, user.account_id, user.subscriptions,
1822 user.identity_source,
1823 )
1824 accounts_named.setdefault(user_id, set()).add(user.account_id or "")
1825 except (InvalidIdentityPayloadError, ValueError, TypeError, AttributeError):
1826 record = UserRecord(False, None)
1827 earlier = standings.get(user_id)
1828 if earlier is not None:
1829 record = UserRecord(
1830 earlier.active and record.active,
1831 _both(earlier.roles, record.roles),
1832 earlier.account_id if earlier.account_id == record.account_id else None,
1833 _both(earlier.subscriptions, record.subscriptions),
1834 earlier.identity_source
1835 if earlier.identity_source == record.identity_source
1836 else None,
1837 )
1838 standings[user_id] = record
1839 for user_id, named in accounts_named.items():
1840 if len(named) > 1:
1841 standings[user_id] = standings[user_id]._replace(conflicting_accounts=tuple(sorted(named)))
1842 return standings
1843
1844
1845def _both(first: tuple[str, ...] | None, second: tuple[str, ...] | None) -> tuple[str, ...] | None:
1846 """The names two rows for one id both give (None if either did not parse)."""
1847 if first is None or second is None:
1848 return None
1849 return tuple(name for name in first if name in second)
1850
1851
1852def _parse_account_records(path: Path) -> dict[str, AccountRecord]:
1853 """Every row of accounts.tsv that names an account id.
1854
1855 A row that fails to parse is an inactive account with no subscriptions,
1856 and an id that appears twice is active only if every one of its rows is,
1857 with only the subscriptions every one of its rows gives it.
1858 """
1859 if not path.exists():
1860 return {}
1861 records: dict[str, AccountRecord] = {}
1862 with path.open(newline="") as handle:
1863 for row in csv.DictReader(handle, delimiter="\t"):
1864 if not row:
1865 continue
1866 raw_id = row.get("account_id")
1867 account_id = raw_id.strip() if isinstance(raw_id, str) else ""
1868 if not account_id:
1869 continue
1870 try:
1871 account = _account_from_row(row)
1872 record = AccountRecord(account.is_active(), account.subscriptions)
1873 except (InvalidIdentityPayloadError, ValueError, TypeError, AttributeError):
1874 record = AccountRecord(False, (), parsed=False)
1875 earlier = records.get(account_id)
1876 if earlier is not None:
1877 record = AccountRecord(
1878 earlier.active and record.active,
1879 _both(earlier.subscriptions, record.subscriptions) or (),
1880 earlier.parsed and record.parsed,
1881 )
1882 records[account_id] = record
1883 return records
1884
1885
1886def _write_sessions(path: Path, sessions: Iterable[IdentitySession]) -> None:
1887 path.parent.mkdir(parents=True, exist_ok=True)
1888 temp_path = path.with_name(f".{path.name}.tmp")
1889 with temp_path.open("w", newline="") as handle:
1890 writer = csv.DictWriter(handle, fieldnames=SESSION_FIELDS, delimiter="\t")
1891 writer.writeheader()
1892 for session in sessions:
1893 writer.writerow(_session_to_row(session))
1894 try:
1895 temp_path.replace(path)
1896 finally:
1897 # Drop even on failure: never leave a parse of a file we just touched.
1898 _drop_session_cache(str(path))
1899
1900
1901def _write_accounts(path: Path, accounts: Iterable[IdentityAccount]) -> None:
1902 _write_account_rows(path, ACCOUNT_FIELDS, (_account_to_row(account) for account in accounts))
1903
1904
1905def _write_account_rows(
1906 path: Path, fieldnames: Iterable[str], rows: Iterable[Mapping[str, Any]]
1907) -> None:
1908 path.parent.mkdir(parents=True, exist_ok=True)
1909 temp_path = path.with_name(f".{path.name}.tmp")
1910 with temp_path.open("w", newline="") as handle:
1911 writer = csv.DictWriter(handle, fieldnames=list(fieldnames), delimiter="\t")
1912 writer.writeheader()
1913 for row in rows:
1914 writer.writerow(row)
1915 try:
1916 temp_path.replace(path)
1917 finally:
1918 _drop_standing_cache(str(path))
1919
1920
1921def _write_users(path: Path, users: Iterable[IdentityUser]) -> None:
1922 path.parent.mkdir(parents=True, exist_ok=True)
1923 temp_path = path.with_name(f".{path.name}.tmp")
1924 with temp_path.open("w", newline="") as handle:
1925 writer = csv.DictWriter(handle, fieldnames=USER_FIELDS, delimiter="\t")
1926 writer.writeheader()
1927 for user in users:
1928 writer.writerow(_user_to_row(user))
1929 try:
1930 temp_path.replace(path)
1931 finally:
1932 _drop_standing_cache(str(path))
1933
1934
1935def _account_from_row(row: Mapping[str, str]) -> IdentityAccount:
1936 account_id = _identity_id(row.get("account_id"), "account_id")
1937 created_at = _required_text(row.get("created_at"), "created_at")
1938 updated_at = _required_text(row.get("updated_at"), "updated_at")
1939 _parse_timestamp(created_at)
1940 _parse_timestamp(updated_at)
1941 return IdentityAccount(
1942 account_id=account_id,
1943 name=str(row.get("name", "")),
1944 status=_status(row.get("status")),
1945 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
1946 created_at=created_at,
1947 updated_at=updated_at,
1948 )
1949
1950
1951def _user_from_row(row: Mapping[str, str]) -> IdentityUser:
1952 user_id = _identity_id(row.get("user_id"), "user_id")
1953 created_at = _required_text(row.get("created_at"), "created_at")
1954 updated_at = _required_text(row.get("updated_at"), "updated_at")
1955 _parse_timestamp(created_at)
1956 _parse_timestamp(updated_at)
1957 return IdentityUser(
1958 user_id=user_id,
1959 account_id=_optional_identity_id(row.get("account_id"), "account_id"),
1960 email=_empty_to_none(row.get("email")),
1961 display_name=str(row.get("display_name", "")),
1962 status=_stored_status(row.get("status")),
1963 roles=_json_string_tuple(row.get("roles", "[]"), "roles"),
1964 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
1965 created_at=created_at,
1966 updated_at=updated_at,
1967 identity_source=_optional_identity_id(row.get("identity_source"), "identity_source"),
1968 )
1969
1970
1971def _session_from_row(row: Mapping[str, str]) -> IdentitySession:
1972 session_id = str(row.get("session_id", ""))
1973 if not validate_session_id(session_id):
1974 raise InvalidSessionPayloadError(f"Invalid session id: {session_id}")
1975
1976 token_hash = _stored_token_hash(row.get("token_hash"))
1977 created_at = _required_text(row.get("created_at"), "created_at")
1978 expires_at = _required_text(row.get("expires_at"), "expires_at")
1979 _parse_timestamp(created_at)
1980 _parse_timestamp(expires_at)
1981
1982 return IdentitySession(
1983 session_id=session_id,
1984 token_hash=token_hash,
1985 user_id=_required_text(row.get("user_id"), "user_id"),
1986 account_id=_empty_to_none(row.get("account_id")),
1987 roles=_json_string_tuple(row.get("roles", "[]"), "roles"),
1988 subscriptions=_json_string_tuple(row.get("subscriptions", "[]"), "subscriptions"),
1989 label=str(row.get("label", "")),
1990 created_at=created_at,
1991 expires_at=expires_at,
1992 revoked_at=_empty_to_none(row.get("revoked_at")),
1993 roles_from=_stored_roles_from(row.get("roles_from")),
1994 )
1995
1996
1997def _stored_roles_from(value: str | None) -> str:
1998 """A roles_from this code does not know is the strictest binding: capped
1999 by the user's roles, and ended with the user's row."""
2000 text = (value or "").strip()
2001 return text if text in _ROLES_FROM_VALUES else ROLES_FROM_SESSION
2002
2003
2004def _account_to_row(account: IdentityAccount) -> dict[str, str]:
2005 return {
2006 "account_id": account.account_id,
2007 "name": account.name,
2008 "status": account.status,
2009 "subscriptions": json.dumps(list(account.subscriptions), separators=(",", ":")),
2010 "created_at": account.created_at,
2011 "updated_at": account.updated_at,
2012 }
2013
2014
2015def _user_to_row(user: IdentityUser) -> dict[str, str]:
2016 return {
2017 "user_id": user.user_id,
2018 "account_id": user.account_id or "",
2019 "email": user.email or "",
2020 "display_name": user.display_name,
2021 "status": user.status,
2022 "roles": json.dumps(list(user.roles), separators=(",", ":")),
2023 "subscriptions": json.dumps(list(user.subscriptions), separators=(",", ":")),
2024 "created_at": user.created_at,
2025 "updated_at": user.updated_at,
2026 "identity_source": user.identity_source or "",
2027 }
2028
2029
2030def _session_to_row(session: IdentitySession) -> dict[str, str]:
2031 return {
2032 "session_id": session.session_id,
2033 "token_hash": session.token_hash,
2034 "user_id": session.user_id,
2035 "account_id": session.account_id or "",
2036 "roles": json.dumps(list(session.roles), separators=(",", ":")),
2037 "subscriptions": json.dumps(list(session.subscriptions), separators=(",", ":")),
2038 "label": session.label,
2039 "created_at": session.created_at,
2040 "expires_at": session.expires_at,
2041 "revoked_at": session.revoked_at or "",
2042 "roles_from": session.roles_from,
2043 }
2044
2045
2046def _new_session_id() -> str:
2047 return object_ids.new_uuid4()
2048
2049
2050def _identity_path(filename: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
2051 root = Path(base_dir) / IDENTITY_DIR
2052 path = root / filename
2053 resolved_root = root.resolve(strict=False)
2054 resolved_path = path.resolve(strict=False)
2055
2056 try:
2057 resolved_path.relative_to(resolved_root)
2058 except ValueError as exc:
2059 raise ValueError("Identity path escapes identity directory") from exc
2060
2061 return path
2062
2063
2064def _identity_id(value: Any, field: str, *, prefix: str | None = None) -> str:
2065 if value is None and prefix is not None:
2066 value = object_ids.new_uuid4()
2067 text = _required_text(value, field)
2068 if not _IDENTITY_ID_RE.fullmatch(text):
2069 raise InvalidIdentityPayloadError(f"{field} contains unsafe identifier")
2070 return text
2071
2072
2073def _optional_identity_id(value: Any, field: str) -> str | None:
2074 text = _optional_text(value, field)
2075 if text is None:
2076 return None
2077 if not _IDENTITY_ID_RE.fullmatch(text):
2078 raise InvalidIdentityPayloadError(f"{field} contains unsafe identifier")
2079 return text
2080
2081
2082def _status(value: Any) -> str:
2083 status = _optional_text(value, "status") or ACTIVE_STATUS
2084 if status not in ALLOWED_STATUSES:
2085 raise InvalidIdentityPayloadError(f"status must be one of: {', '.join(sorted(ALLOWED_STATUSES))}")
2086 return status
2087
2088
2089def _stored_status(value: Any) -> str:
2090 """A user status as stored, kept verbatim even when this code does not know it.
2091
2092 Writes still go through _status, so only known statuses are ever written
2093 here. On read, a status nobody recognises (a hand edit, a newer version's
2094 "suspended") used to make the row fail to parse and vanish -- and a user
2095 who vanishes reads as "no such user", which ad hoc sessions treat as
2096 allowed. Kept verbatim instead, it lists, shows up in GET /identity/users,
2097 can be corrected through the status route, and is_active() says no. An
2098 empty status is not quietly "active" either.
2099 """
2100 text = value.strip() if isinstance(value, str) else ""
2101 if len(text) > 64 or any(ord(char) < 32 for char in text):
2102 return "invalid"
2103 return text
2104
2105
2106def _session_account(
2107 payload: Mapping[str, Any],
2108 user: IdentityUser | None,
2109 *,
2110 base_dir: Path | str,
2111) -> IdentityAccount | None:
2112 payload_account_id = _optional_identity_id(payload.get("account_id"), "account_id")
2113 if user is not None and payload_account_id and user.account_id != payload_account_id:
2114 raise InvalidSessionPayloadError("account_id does not match registered user")
2115
2116 account_id = payload_account_id or (user.account_id if user is not None else None)
2117 if account_id is None:
2118 return None
2119
2120 account = _lookup_account(account_id, base_dir=base_dir)
2121 if account is None and user is not None:
2122 raise AccountNotFoundError(f"Account not found: {account_id}")
2123 return account
2124
2125
2126def _session_account_id(
2127 payload: Mapping[str, Any],
2128 user: IdentityUser | None,
2129 account: IdentityAccount | None,
2130) -> str | None:
2131 payload_account_id = _optional_identity_id(payload.get("account_id"), "account_id")
2132 if payload_account_id is not None:
2133 return payload_account_id
2134 if account is not None:
2135 return account.account_id
2136 return user.account_id if user is not None else None
2137
2138
2139def _merged_strings(*groups: Iterable[str]) -> tuple[str, ...]:
2140 merged: list[str] = []
2141 seen = set()
2142 for group in groups:
2143 for item in group:
2144 if item not in seen:
2145 merged.append(item)
2146 seen.add(item)
2147 return tuple(merged)
2148
2149
2150def _ttl_seconds(value: Any) -> int:
2151 if value is None:
2152 return DEFAULT_SESSION_TTL_SECONDS
2153 if isinstance(value, bool):
2154 raise InvalidSessionPayloadError("ttl_seconds must be an integer")
2155 try:
2156 ttl = int(value)
2157 except (TypeError, ValueError) as exc:
2158 raise InvalidSessionPayloadError("ttl_seconds must be an integer") from exc
2159
2160 if ttl <= 0:
2161 raise InvalidSessionPayloadError("ttl_seconds must be greater than zero")
2162 return min(ttl, MAX_SESSION_TTL_SECONDS)
2163
2164
2165def _required_text(value: Any, field: str) -> str:
2166 text = _optional_text(value, field)
2167 if text is None:
2168 raise InvalidSessionPayloadError(f"{field} is required")
2169 return text
2170
2171
2172def _optional_text(value: Any, field: str) -> str | None:
2173 if value is None:
2174 return None
2175 if not isinstance(value, str):
2176 raise InvalidSessionPayloadError(f"{field} must be a string")
2177 text = value.strip()
2178 if not text:
2179 return None
2180 if len(text) > 256 or any(ord(char) < 32 for char in text):
2181 raise InvalidSessionPayloadError(f"{field} contains unsafe text")
2182 return text
2183
2184
2185def _string_tuple(value: Any, field: str) -> tuple[str, ...]:
2186 if value is None:
2187 return ()
2188 if isinstance(value, str):
2189 values = value.split(",")
2190 elif isinstance(value, (list, tuple)):
2191 values = value
2192 else:
2193 raise InvalidSessionPayloadError(f"{field} must be a list of strings")
2194
2195 output: list[str] = []
2196 seen = set()
2197 for item in values:
2198 text = _required_text(item, field)
2199 if text not in seen:
2200 output.append(text)
2201 seen.add(text)
2202 return tuple(output)
2203
2204
2205def _json_string_tuple(value: str, field: str) -> tuple[str, ...]:
2206 try:
2207 payload = json.loads(value or "[]")
2208 except json.JSONDecodeError as exc:
2209 raise InvalidSessionPayloadError(f"{field} is invalid JSON") from exc
2210 return _string_tuple(payload, field)
2211
2212
2213def _stored_token_hash(value: str | None) -> str:
2214 text = (value or "").strip()
2215 if not text.startswith("sha256:") or len(text) != len("sha256:") + 64:
2216 raise InvalidSessionPayloadError("token_hash is invalid")
2217 return text
2218
2219
2220def _empty_to_none(value: str | None) -> str | None:
2221 text = (value or "").strip()
2222 return text or None
2223
2224
2225def _format_timestamp(value: datetime) -> str:
2226 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
2227
2228
2229def _parse_timestamp(value: str) -> datetime:
2230 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
2231 if parsed.tzinfo is None:
2232 raise ValueError("timestamp must include timezone")
2233 return parsed
2234
2235
2236def _now() -> datetime:
2237 return datetime.now(timezone.utc)
2238
2239
2240def _file_lock(path: Path) -> threading.Lock:
2241 resolved = path.resolve(strict=False)
2242 with _FILE_LOCKS_LOCK:
2243 lock = _FILE_LOCKS.get(resolved)
2244 if lock is None:
2245 lock = threading.Lock()
2246 _FILE_LOCKS[resolved] = lock
2247 return lock