Files
romm/backend/models/user.py
alexcastgonz 81b617459b fix(db): bump client token and device last-used timestamps without a prior read (#5384)
* fix(db): bump client token and device last-used timestamps without a prior read

update_last_used() and update_last_seen_debounced() read the row with
session.get() and then updated it in the same transaction. When two requests
with the same Client API Token ran concurrently and both passed the debounce
check, the second UPDATE hit MariaDB error 1020 (Record has changed since last
read), so a read-only GET returned HTTP 500. Make each a single conditional
UPDATE that only touches the row when the debounce window has passed.

Fixes #5379

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(db): code-review fixes for last-used race tests

Reuse the executed_statements fixture, scope race listeners to
sync_engine, add the device race test, drop an unused fixture, and
apply trunk fmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(db): simplify pass on last-used race fix

Share the race hook as tests/db_race_stubs.run_before_first, look tokens
up by id in tests, trim duplicated docstrings, and state the handler
comment as current behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(db): humanizer pass on last-used handler comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(db): run MariaDB and MySQL sessions at READ COMMITTED

MariaDB 11.6+ turns on innodb_snapshot_isolation, so at REPEATABLE READ any
transaction that reads a row and then writes it fails with error 1020
("Record has changed since last read") when another transaction committed
to that row in between. READ COMMITTED, PostgreSQL's default, takes a fresh
snapshot per statement and removes the whole class of failures.

A server logging binlog_format=STATEMENT refuses InnoDB writes below
REPEATABLE READ, so its sessions keep the default and log a warning once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(auth): skip last-used and last-active writes inside the debounce window

Client-token auth bumped the token, the device and the user on every
request, the user with an undebounced UPDATE plus a re-SELECT. The token's
loaded last_used_at now gates the token and device bumps, and
set_last_active checks the loaded last_active and bumps through a
debounced conditional UPDATE, so a request inside the window writes
nothing and takes no row lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-29 12:23:31 -04:00

194 lines
7.7 KiB
Python

from __future__ import annotations
import enum
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Final
from sqlalchemy import TIMESTAMP, Boolean, Enum, ForeignKey, Index, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from starlette.authentication import SimpleUser
from config import OIDC_ENABLED
from handler.auth.constants import Scope
from models.base import BaseModel
from models.permission import PermissionGroup
from utils.database import CustomJSON, ExactString
from utils.datetime import older_than
if TYPE_CHECKING:
from models.assets import MemoryCard, Save, Screenshot, State
from models.client_token import ClientToken
from models.collection import Collection, SmartCollection
from models.device import Device
from models.music import MusicPlaylist
from models.play_session import PlaySession
from models.rom import RomNote, RomUser
class Role(enum.StrEnum):
# Two kinds only: admins bypass all permission checks; everyone else is a
# `user` whose access comes entirely from their permission group + overrides.
# (The old viewer/editor split was folded into groups.)
USER = "user"
ADMIN = "admin"
@classmethod
def coerce(cls, value: str | None) -> Role:
"""Map any role string to the two-value set. Only an exact ``admin``
becomes ADMIN; everything else (``user``, the legacy ``viewer`` /
``editor`` from in-flight invites, unknown, empty) collapses to USER."""
return cls.ADMIN if (value or "").strip().lower() == "admin" else cls.USER
TEXT_FIELD_LENGTH = 255
# Id of the synthetic, unauthenticated visitor KIOSK_MODE hands out. Negative so
# it can never collide with an auto-increment row.
KIOSK_USER_ID: Final = -1
class User(BaseModel, SimpleUser):
__tablename__ = "users"
__table_args__ = (
Index("ix_users_oidc_identity", "oidc_issuer", "oidc_sub", unique=True),
{"extend_existing": True},
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
username: Mapped[str] = mapped_column(
String(length=TEXT_FIELD_LENGTH), unique=True, index=True
)
hashed_password: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH)
)
email: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), unique=True, index=True
)
# The provider's `iss` and `sub` claims: a stable identity that survives an
# email change. Exact, since a `sub` is case-sensitive.
oidc_issuer: Mapped[str | None] = mapped_column(ExactString(TEXT_FIELD_LENGTH))
oidc_sub: Mapped[str | None] = mapped_column(ExactString(TEXT_FIELD_LENGTH))
enabled: Mapped[bool] = mapped_column(default=True)
# VARCHAR-backed (native_enum=False) storing the lowercase value, so the
# vocabulary stays portable across SQLite/MariaDB/Postgres.
role: Mapped[Role] = mapped_column(
Enum(
Role,
native_enum=False,
length=20,
values_callable=lambda e: [m.value for m in e],
),
default=Role.USER,
)
# The granular permission group this user belongs to. NULL falls back to the
# server-wide default group in the resolver. Admins bypass groups entirely.
permission_group_id: Mapped[int | None] = mapped_column(
ForeignKey("permission_groups.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
# Per-user replacements for the group's age limit settings; NULL inherits.
age_limit: Mapped[int | None] = mapped_column(Integer(), nullable=True)
hide_unrated_roms: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
avatar_path: Mapped[str] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=""
)
last_login: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True))
last_active: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True))
ra_username: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=""
)
ra_progression: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)
ui_settings: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)
saves: Mapped[list[Save]] = relationship(lazy="raise", back_populates="user")
states: Mapped[list[State]] = relationship(lazy="raise", back_populates="user")
memory_cards: Mapped[list[MemoryCard]] = relationship(
lazy="raise", back_populates="user"
)
screenshots: Mapped[list[Screenshot]] = relationship(
lazy="raise", back_populates="user"
)
rom_users: Mapped[list[RomUser]] = relationship(lazy="raise", back_populates="user")
notes: Mapped[list[RomNote]] = relationship(lazy="raise", back_populates="user")
collections: Mapped[list[Collection]] = relationship(
lazy="raise", back_populates="user"
)
smart_collections: Mapped[list["SmartCollection"]] = relationship(
lazy="raise", back_populates="user"
)
music_playlists: Mapped[list["MusicPlaylist"]] = relationship(
lazy="raise", back_populates="user"
)
devices: Mapped[list["Device"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
client_tokens: Mapped[list["ClientToken"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
play_sessions: Mapped[list["PlaySession"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
# Loaded explicitly by the permission resolver; lazy="raise" keeps it off
# every other user query so the schema-wide query shape is unchanged.
permission_group: Mapped[PermissionGroup | None] = relationship(lazy="raise")
@classmethod
def kiosk_mode_user(cls) -> User:
now = datetime.now(timezone.utc)
return cls(
id=KIOSK_USER_ID,
username="kiosk",
role=Role.USER,
enabled=True,
avatar_path="",
last_active=now,
last_login=now,
created_at=now,
updated_at=now,
)
@property
def is_kiosk_guest(self) -> bool:
"""The shared anonymous visitor, not a real account."""
return self.id == KIOSK_USER_ID
@property
def oauth_scopes(self) -> list[Scope]:
# Derived from the granular permission model (groups + overrides),
# projected onto the legacy coarse scopes. Resolved per access via its
# own session; admins short-circuit without touching the DB.
# Local import: breaks the models.user <-> handler.auth.permissions cycle.
from handler.auth.permissions import compute_oauth_scopes
return compute_oauth_scopes(self)
@property
def has_password(self) -> bool:
"""Whether the account can sign in with a password: OIDC-provisioned
accounts hold a random placeholder instead of a bcrypt hash."""
return bool(self.hashed_password and self.hashed_password.startswith("$2"))
@property
def email_managed_by_oidc(self) -> bool:
"""Whether the provider owns the email: it overwrites a linked account's
at every sign-in, and finds an unlinked password-less account by it."""
return OIDC_ENABLED and (self.oidc_sub is not None or not self.has_password)
@property
def fs_safe_folder_name(self) -> str:
# Uses the ID to avoid issues with username changes
return f"User:{self.id}".encode().hex()
def set_last_active(self) -> None:
from handler.database import db_user_handler
from handler.database.users_handler import LAST_ACTIVE_DEBOUNCE
if older_than(self.last_active, LAST_ACTIVE_DEBOUNCE):
db_user_handler.update_last_active(self.id)