Files
romm/backend/handler/database/client_tokens_handler.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

167 lines
4.8 KiB
Python

from collections.abc import Iterable, Sequence
from datetime import datetime, timedelta, timezone
from sqlalchemy import delete, func, or_, select, update
from sqlalchemy.orm import Session, joinedload
from decorators.database import INJECTED_SESSION, begin_session
from models.client_token import ClientToken
from .base_handler import DBBaseHandler, affected_rows
LAST_USED_DEBOUNCE = timedelta(minutes=5)
class DBClientTokensHandler(DBBaseHandler):
@begin_session
def add_token(
self,
token: ClientToken,
session: Session = INJECTED_SESSION,
) -> ClientToken:
return session.merge(token)
@begin_session
def get_token_by_hash(
self,
hashed_token: str,
session: Session = INJECTED_SESSION,
) -> ClientToken | None:
return session.scalar(
select(ClientToken).where(ClientToken.hashed_token == hashed_token)
)
@begin_session
def get_tokens_by_user(
self,
user_id: int,
session: Session = INJECTED_SESSION,
) -> Sequence[ClientToken]:
return session.scalars(
select(ClientToken)
.where(ClientToken.user_id == user_id)
.order_by(ClientToken.created_at.desc())
).all()
@begin_session
def get_token_ids_by_users(
self,
user_ids: Iterable[int],
session: Session = None, # type: ignore[assignment]
) -> Sequence[int]:
return session.scalars(
select(ClientToken.id).where(ClientToken.user_id.in_(list(user_ids)))
).all()
@begin_session
def get_token_ids_by_device(
self,
device_id: str,
session: Session = None, # type: ignore[assignment]
) -> Sequence[int]:
return session.scalars(
select(ClientToken.id).where(ClientToken.device_id == device_id)
).all()
@begin_session
def get_all_tokens(
self,
session: Session = INJECTED_SESSION,
) -> Sequence[ClientToken]:
return (
session.scalars(
select(ClientToken)
.options(joinedload(ClientToken.user))
.order_by(ClientToken.created_at.desc())
)
.unique()
.all()
)
@begin_session
def delete_token(
self,
token_id: int,
user_id: int | None = None,
session: Session = INJECTED_SESSION,
) -> int:
stmt = delete(ClientToken).where(ClientToken.id == token_id)
if user_id is not None:
stmt = stmt.where(ClientToken.user_id == user_id)
result = session.execute(stmt.execution_options(synchronize_session="evaluate"))
return affected_rows(result)
@begin_session
def update_last_used(
self,
token_id: int,
session: Session = INJECTED_SESSION,
) -> None:
now = datetime.now(timezone.utc)
# Debounced in the WHERE clause, so concurrent bumps have no earlier read to race.
session.execute(
update(ClientToken)
.where(
ClientToken.id == token_id,
or_(
ClientToken.last_used_at.is_(None),
ClientToken.last_used_at < now - LAST_USED_DEBOUNCE,
),
)
.values(last_used_at=now)
.execution_options(synchronize_session=False)
)
@begin_session
def update_hashed_token(
self,
token_id: int,
new_hash: str,
user_id: int | None = None,
session: Session = INJECTED_SESSION,
) -> ClientToken | None:
stmt = (
update(ClientToken)
.where(ClientToken.id == token_id)
.values(hashed_token=new_hash, last_used_at=None)
.execution_options(synchronize_session="evaluate")
)
if user_id is not None:
stmt = stmt.where(ClientToken.user_id == user_id)
result = session.execute(stmt)
if affected_rows(result) == 0:
return None
return session.get(ClientToken, token_id)
@begin_session
def count_tokens_by_user(
self,
user_id: int,
session: Session = INJECTED_SESSION,
) -> int:
return (
session.scalar(
select(func.count())
.select_from(ClientToken)
.where(ClientToken.user_id == user_id)
)
or 0
)
@begin_session
def get_token(
self,
token_id: int,
user_id: int | None = None,
session: Session = INJECTED_SESSION,
) -> ClientToken | None:
stmt = select(ClientToken).where(ClientToken.id == token_id)
if user_id is not None:
stmt = stmt.where(ClientToken.user_id == user_id)
return session.scalar(stmt)