Files
romm/backend/endpoints/auth.py
Georges-Antoine Assi 37e4ca304d fix: permission, validation and resource-limit hardening (#5496)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:39:30 -05:00

498 lines
16 KiB
Python

import asyncio
from datetime import datetime, timedelta, timezone
from typing import Annotated, Final, Literal, Optional, cast
from urllib.parse import urlencode
from authlib.common.errors import AuthlibBaseError
from fastapi import BackgroundTasks, Body, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from fastapi.security.http import HTTPBasic, HTTPBasicCredentials
from joserfc.errors import JoseError
from config import (
OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS,
OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS,
OIDC_ENABLED,
OIDC_END_SESSION_ENDPOINT,
OIDC_REDIRECT_URI,
OIDC_RP_INITIATED_LOGOUT,
)
from decorators.auth import oauth
from endpoints.forms.identity import OAuth2RequestForm
from endpoints.responses.oauth import OIDCLogoutResponse, TokenResponse
from exceptions.auth_exceptions import (
AuthCredentialsException,
OIDCDisabledException,
OIDCNotConfiguredException,
UserDisabledException,
)
from handler.audit_handler import (
AuditActor,
AuditTarget,
claim_once,
client_ip,
record,
release_claim,
within_budget,
)
from handler.auth.base_handler import auth_handler, oauth_handler, oidc_handler
from handler.database import db_user_handler
from logger.formatter import CYAN
from logger.formatter import highlight as hl
from logger.logger import log
from models.audit_event import AuditAction
from models.user import User
from utils.auth import create_or_find_web_device
from utils.router import APIRouter
from utils.validation import ValidationError, validate_password
router = APIRouter(
tags=["auth"],
)
# Failed sign-ins from one address for one username within this window are one attempt.
LOGIN_FAILURE_WINDOW_SECONDS: Final = 60
# At most this many failed sign-ins are recorded per address each window, so a
# client cycling usernames can't flood the log.
LOGIN_FAILURES_PER_ADDRESS: Final = 20
LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS: Final = 10 * 60
# Repeated reset requests for one user from one address are one request.
PASSWORD_RESET_REQUEST_WINDOW_SECONDS: Final = 10 * 60
LoginMethod = Literal["password", "token", "oidc"]
def _record_login(
request: Request, user: User, method: LoginMethod, device_id: str | None = None
) -> None:
record(
AuditAction.AUTH_LOGIN,
AuditActor.for_user(user, ip_address=client_ip(request), device_id=device_id),
data={"method": method},
)
def _record_login_failure(
request: Request,
username: str | None,
method: LoginMethod,
reason: Literal["credentials", "disabled"],
) -> None:
ip_address = client_ip(request)
key = f"login_failed:{ip_address}:{username}"
if not claim_once(key, LOGIN_FAILURE_WINDOW_SECONDS) or not within_budget(
f"login_failed:{ip_address}",
LOGIN_FAILURES_PER_ADDRESS,
LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS,
):
return
user = db_user_handler.get_user_by_username(username) if username else None
# A name that matches no account may be a password typed in the wrong box,
# so only an account's own name is kept.
if not record(
AuditAction.AUTH_LOGIN_FAILED,
(
AuditActor.for_user(user, ip_address=ip_address)
if user
else AuditActor.anonymous(ip_address)
),
data={
"username": user.username if user else None,
"method": method,
"reason": reason,
},
):
release_claim(key)
def _record_password_reset_request(ip_address: str | None, user: User) -> None:
key = f"password_reset:{ip_address}:{user.id}"
if claim_once(key, PASSWORD_RESET_REQUEST_WINDOW_SECONDS) and not record(
AuditAction.AUTH_PASSWORD_RESET_REQUEST,
AuditActor.anonymous(ip_address),
AuditTarget.of_user(user),
):
release_claim(key)
# Session authentication endpoints
@router.post("/login")
def login(
request: Request,
credentials: HTTPBasicCredentials = Depends(HTTPBasic()), # noqa
) -> None:
"""Session login endpoint
Args:
request (Request): Fastapi Request object
credentials: Defaults to Depends(HTTPBasic()).
Raises:
CredentialsException: Invalid credentials
UserDisabledException: Auth is disabled
"""
user = auth_handler.authenticate_user(credentials.username, credentials.password)
if not user:
_record_login_failure(request, credentials.username, "password", "credentials")
raise AuthCredentialsException
if not user.enabled:
_record_login_failure(request, credentials.username, "password", "disabled")
raise UserDisabledException
request.session["iss"] = "romm:auth"
request.session["sub"] = user.username
# Auto-create or find the web browser device
device = create_or_find_web_device(request, user)
request.session["device_id"] = device.id
# Update last login and active times
now = datetime.now(timezone.utc)
db_user_handler.update_user(user.id, {"last_login": now, "last_active": now})
_record_login(request, user, "password", device.id)
@router.post("/logout", status_code=status.HTTP_200_OK)
async def logout(request: Request) -> Optional[OIDCLogoutResponse]:
"""Session logout endpoint
Args:
request (Request): Fastapi Request object
Returns:
Optional[dict]: When OIDC RP-Initiated Logout is enabled and the session
contains an OIDC id_token, returns a dict with the OIDC end-session URL
so the client can redirect the browser to log out of the OIDC provider.
"""
id_token = request.session.get("oidc_id_token")
request.session.clear()
if OIDC_RP_INITIATED_LOGOUT and id_token:
end_session_endpoint = OIDC_END_SESSION_ENDPOINT
if not end_session_endpoint and oauth.openid:
try:
metadata = await oauth.openid.load_server_metadata()
end_session_endpoint = metadata.get("end_session_endpoint", "")
except Exception:
log.warning(
"Failed to load OIDC server metadata for RP-Initiated Logout"
)
if end_session_endpoint:
params = urlencode({"id_token_hint": id_token})
return {"oidc_logout_url": f"{end_session_endpoint}?{params}"}
return None
@router.post("/token")
async def token(
request: Request, form_data: Annotated[OAuth2RequestForm, Depends()]
) -> TokenResponse:
"""OAuth2 token endpoint
Args:
form_data (Annotated[OAuth2RequestForm, Depends): Form Data with OAuth2 info
Raises:
HTTPException: Missing refresh token
HTTPException: Invalid refresh token
HTTPException: Missing username or password
HTTPException: Invalid username or password
HTTPException: Client credentials are not yet supported
HTTPException: Invalid or unsupported grant type
HTTPException: Insufficient scope
Returns:
TokenResponse: TypedDict with the new generated token info
"""
user: User | None
# Read before any credential check, so a revocation that lands during the
# check still covers the tokens issued below.
issued_at = datetime.now(timezone.utc)
# Support refreshing access tokens
if form_data.grant_type == "refresh_token":
token = form_data.refresh_token
if not token:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Missing refresh token"
)
user, claims = await oauth_handler.consume_refresh_token(token)
if not user or not claims:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
)
if not user.enabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled"
)
access_token = oauth_handler.create_access_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": claims.get("scopes"),
},
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
issued_at=issued_at,
)
refresh_token = oauth_handler.create_refresh_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": claims.get("scopes"),
},
expires_delta=timedelta(seconds=OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS),
issued_at=issued_at,
)
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer", # trunk-ignore(bandit/B105)
"expires": OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS,
"refresh_expires": OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS,
}
# Authentication via username/password
elif form_data.grant_type == "password":
if not form_data.username or not form_data.password:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Missing username or password",
)
user = await asyncio.to_thread(
auth_handler.authenticate_user, form_data.username, form_data.password
)
if not user:
_record_login_failure(request, form_data.username, "token", "credentials")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
)
if not user.enabled:
_record_login_failure(request, form_data.username, "token", "disabled")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled"
)
# TODO: Authentication via client_id/client_secret
elif form_data.grant_type == "client_credentials":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Client credentials are not yet supported",
)
else:
# All other grant types are unsupported
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid or unsupported grant type",
)
# Check if user has access to requested scopes
if not set(form_data.scopes).issubset(user.oauth_scopes):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient scope",
)
access_token = oauth_handler.create_access_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": " ".join(form_data.scopes),
},
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
issued_at=issued_at,
)
refresh_token = oauth_handler.create_refresh_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": " ".join(form_data.scopes),
},
expires_delta=timedelta(seconds=OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS),
issued_at=issued_at,
)
_record_login(request, user, "token")
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer", # trunk-ignore(bandit/B105)
"expires": OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS,
"refresh_expires": OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS,
}
# OIDC login and callback endpoints
@router.get("/login/openid")
async def login_via_openid(request: Request) -> RedirectResponse:
"""OIDC login endpoint
Args:
request (Request): Fastapi Request object
Raises:
OIDCDisabledException: OAuth is disabled
OIDCNotConfiguredException: OAuth not configured
Returns:
RedirectResponse: Redirect to OIDC provider
"""
if not OIDC_ENABLED:
raise OIDCDisabledException
if not oauth.openid:
raise OIDCNotConfiguredException
return cast(
RedirectResponse,
await oauth.openid.authorize_redirect(request, OIDC_REDIRECT_URI),
)
@router.get("/oauth/openid")
async def auth_openid(request: Request) -> RedirectResponse:
"""OIDC callback endpoint
Args:
request (Request): Fastapi Request object
Raises:
OIDCDisabledException: OAuth is disabled
OIDCNotConfiguredException: OAuth not configured
AuthCredentialsException: Invalid credentials
UserDisabledException: Auth is disabled
Returns:
RedirectResponse: Redirect to home, or to login if the provider rejects
"""
if not OIDC_ENABLED:
raise OIDCDisabledException
if not oauth.openid:
raise OIDCNotConfiguredException
# Authlib verifies the ID token with joserfc, whose errors are not Authlib's.
try:
token = await oauth.openid.authorize_access_token(request)
except (AuthlibBaseError, JoseError) as exc:
# repr() because error and description can come from the query string
log.warning(f"OIDC callback rejected: {exc.error!r}: {exc.description!r}")
if request.user.is_authenticated and not request.user.is_kiosk_guest:
return RedirectResponse(url="/")
# Without the bypass, OIDC autologin would send a persistent failure
# straight back to the provider and loop
return RedirectResponse(url="/login?bypass_autologin=true")
potential_user, _userinfo = (
await oidc_handler.get_current_active_user_from_openid_token(token)
)
if not potential_user:
_record_login_failure(request, None, "oidc", "credentials")
raise AuthCredentialsException
if not potential_user.enabled:
_record_login_failure(request, potential_user.username, "oidc", "disabled")
raise UserDisabledException
request.session["iss"] = "romm:auth"
request.session["sub"] = potential_user.username
if OIDC_RP_INITIATED_LOGOUT:
request.session["oidc_id_token"] = token.get("id_token", "")
# Auto-create or find the web browser device
device = create_or_find_web_device(request, potential_user)
request.session["device_id"] = device.id
# Update last login and active times
now = datetime.now(timezone.utc)
db_user_handler.update_user(
potential_user.id, {"last_login": now, "last_active": now}
)
_record_login(request, potential_user, "oidc", device.id)
return RedirectResponse(url="/")
@router.post("/forgot-password", status_code=status.HTTP_200_OK)
def request_password_reset(
request: Request,
background_tasks: BackgroundTasks,
username: str = Body(..., embed=True),
) -> None:
"""Request a password reset link for the user.
Args:
username (str): Username of the user requesting the reset
Returns:
None: Returns 200 OK status
"""
user = db_user_handler.get_user_by_username(username)
if user:
# After the response, so its timing can't tell whether the user exists.
# The record goes first: a link that fails to send stops the tasks after it.
background_tasks.add_task(
_record_password_reset_request, client_ip(request), user
)
background_tasks.add_task(auth_handler.send_password_reset_link, user)
else:
log.warning(
f"Reset password link requested for a user {hl(username, color=CYAN)}, but that username does not exist."
)
@router.post("/reset-password", status_code=status.HTTP_200_OK)
async def reset_password(
request: Request,
token: str = Body(..., embed=True),
new_password: str = Body(..., embed=True),
) -> None:
"""Reset password using the token.
Args:
token (str): Reset token from the URL
new_password (str): New user password
Returns:
None: Returns 200 OK status
"""
# Ahead of the token check, which spends the link: a rejected password
# leaves it usable for another try.
try:
validate_password(new_password)
except ValidationError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=exc.message,
) from exc
user = auth_handler.verify_password_reset_token(token)
await auth_handler.set_user_new_password(user, new_password)
record(
AuditAction.AUTH_PASSWORD_RESET,
AuditActor.for_user(user, ip_address=client_ip(request)),
AuditTarget.of_user(user),
)
log.info(
f"Password was successfully reset for user {hl(user.username, color=CYAN)}."
)