Files
romm/backend/tests/handler/database/test_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

75 lines
2.7 KiB
Python

from datetime import datetime, timedelta, timezone
from tests.db_race_stubs import run_before_first
from tests.factories import make_device_token
from handler.database import db_client_token_handler
from models.user import User
from utils.datetime import to_utc
def _last_used_at(token_id: int) -> datetime | None:
token = db_client_token_handler.get_token(token_id)
assert token is not None
return token.last_used_at
class TestUpdateLastUsed:
def test_bumps_when_never_used(self, admin_user: User):
token, _ = make_device_token(admin_user, None)
db_client_token_handler.update_last_used(token.id)
assert _last_used_at(token.id) is not None
def test_bumps_when_last_used_is_old(self, admin_user: User):
old = datetime.now(timezone.utc) - timedelta(minutes=10)
token, _ = make_device_token(admin_user, None, last_used_at=old)
db_client_token_handler.update_last_used(token.id)
refreshed = _last_used_at(token.id)
assert refreshed is not None
# MariaDB returns naive datetimes; normalize to UTC for comparison
assert to_utc(refreshed) > old
def test_skips_when_last_used_within_debounce_window(self, admin_user: User):
recent = datetime.now(timezone.utc) - timedelta(minutes=1)
token, _ = make_device_token(admin_user, None, last_used_at=recent)
db_client_token_handler.update_last_used(token.id)
refreshed = _last_used_at(token.id)
assert refreshed is not None
assert abs((to_utc(refreshed) - recent).total_seconds()) < 1
def test_unknown_token_is_a_no_op(self):
db_client_token_handler.update_last_used(999_999)
def test_does_not_read_the_token_before_updating_it(
self, admin_user: User, executed_statements: list[str]
):
token, _ = make_device_token(admin_user, None)
executed_statements.clear()
db_client_token_handler.update_last_used(token.id)
statements = [s.lstrip().lower() for s in executed_statements]
assert [s for s in statements if s.startswith("select")] == []
assert any(s.startswith("update client_tokens") for s in statements)
def test_survives_a_concurrent_request_committing_the_same_update(
self, admin_user: User
):
"""Guards against MariaDB error 1020, "Record has changed since last read"."""
token, _ = make_device_token(admin_user, None)
with run_before_first(
"update client_tokens",
lambda: db_client_token_handler.update_last_used(token.id),
) as raced:
db_client_token_handler.update_last_used(token.id)
assert raced
assert _last_used_at(token.id) is not None