Files
romm/backend/handler/auth/hybrid_auth.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

153 lines
5.5 KiB
Python

import asyncio
from datetime import datetime, timezone
from typing import NamedTuple
from fastapi import HTTPException
from fastapi.security.http import HTTPBasic
from starlette.authentication import AuthCredentials, AuthenticationBackend
from starlette.requests import HTTPConnection
from config import KIOSK_MODE
from handler.auth.base_handler import auth_handler, oauth_handler
from handler.database import (
db_client_token_handler,
db_device_handler,
db_user_handler,
)
from handler.database.client_tokens_handler import LAST_USED_DEBOUNCE
from models.client_token import ClientToken
from models.user import User
from utils.datetime import older_than, to_utc
from .constants import CLIENT_TOKEN_PREFIX, READ_SCOPES
class ClientTokenIdentity(NamedTuple):
token: ClientToken
user: User
scopes: list[str]
def resolve_client_token(raw_token: str) -> ClientTokenIdentity | None:
"""The live client token behind a raw one, its enabled owner, and the scopes both hold."""
client_token = db_client_token_handler.get_token_by_hash(
auth_handler.hash_client_token(raw_token)
)
if client_token is None:
return None
if client_token.expires_at and to_utc(client_token.expires_at) < datetime.now(
timezone.utc
):
return None
user = db_user_handler.get_user(client_token.user_id)
if user is None or not user.enabled:
return None
return ClientTokenIdentity(
client_token, user, list(client_token.effective_scopes(user))
)
def _basic_auth_user(username: str, password: str) -> User | None:
"""The enabled user these credentials belong to, marked active."""
user = auth_handler.authenticate_user(username, password)
if user is None or not user.enabled:
return None
user.set_last_active()
return user
class HybridAuthBackend(AuthenticationBackend):
async def authenticate(
self, conn: HTTPConnection
) -> tuple[AuthCredentials, User] | None:
# Check if session key already stored in cache
user = await auth_handler.get_current_active_user_from_session(conn)
if user:
user.set_last_active()
return (AuthCredentials(user.oauth_scopes), user)
# Errors raised here bypass FastAPI's exception handlers and surface as 500s,
# so an unusable credential leaves the request unauthenticated instead
if "Authorization" in conn.headers:
auth_header_parts = conn.headers["Authorization"].split()
if len(auth_header_parts) != 2:
return None
scheme, token = auth_header_parts
# Check if basic auth header is valid
if scheme.lower() == "basic":
try:
credentials = await HTTPBasic().__call__(conn)
except HTTPException:
return None
if not credentials:
return None
# bcrypt takes ~250ms, which would stall every request on the
# event loop; WebDAV clients send Basic auth on each request.
user = await asyncio.to_thread(
_basic_auth_user, credentials.username, credentials.password
)
if user is None:
return None
return (AuthCredentials(user.oauth_scopes), user)
# Check if bearer auth header is valid
if scheme.lower() == "bearer":
if token.startswith(CLIENT_TOKEN_PREFIX):
identity = resolve_client_token(token)
if identity is None:
return None
client_token, user, effective_scopes = identity
# The device rides on the token's debounce, so a request inside
# the window costs no write.
if older_than(client_token.last_used_at, LAST_USED_DEBOUNCE):
db_client_token_handler.update_last_used(client_token.id)
if client_token.device_id:
db_device_handler.update_last_seen_debounced(
client_token.device_id
)
user.set_last_active()
conn.state.client_token_id = client_token.id
conn.state.device_id = client_token.device_id
return (AuthCredentials(effective_scopes), user)
# OAuth JWT bearer tokens
try:
(
user,
claims,
) = await oauth_handler.get_current_active_user_from_bearer_token(
token
)
except HTTPException:
return None
if user is None or claims is None:
return None
# Only access tokens can request resources
if claims.get("type") != "access":
return None
# Only grant access to resources with overlapping scopes
token_scopes = set(list(claims.get("scopes", "").split(" ")))
overlapping_scopes = list(token_scopes & set(user.oauth_scopes))
user.set_last_active()
return (AuthCredentials(overlapping_scopes), user)
# Check if we're in KIOSK_MODE
if KIOSK_MODE:
user = User.kiosk_mode_user()
return (AuthCredentials(READ_SCOPES), user)
return None