From 9ea1379c6207036c73d287adf48908bc6e10ae1a Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 09:45:16 -0500 Subject: [PATCH 1/5] fix(security): fail closed on a password hash passlib cannot identify OIDC-provisioned accounts hold a placeholder rather than a bcrypt hash. passlib raises on one it cannot identify, so a login against such an account turned a 401 into a 500 that marked it as OIDC-backed. Co-Authored-By: Claude Sonnet 5 --- backend/handler/auth/base_handler.py | 7 ++++++- backend/tests/handler/auth/test_auth.py | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 6f8f1cd94..e020a59a6 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -88,7 +88,12 @@ class AuthHandler: return hashlib.sha256(raw.encode()).hexdigest() def verify_password(self, plain_password, hashed_password): - return self.pwd_context.verify(plain_password, hashed_password) + try: + return self.pwd_context.verify(plain_password, hashed_password) + except ValueError: + # OIDC-provisioned accounts hold a placeholder, not a bcrypt hash, + # and passlib raises on one it cannot identify. + return False def get_password_hash(self, password): return self.pwd_context.hash(password) diff --git a/backend/tests/handler/auth/test_auth.py b/backend/tests/handler/auth/test_auth.py index 0dd1fe759..063afba98 100644 --- a/backend/tests/handler/auth/test_auth.py +++ b/backend/tests/handler/auth/test_auth.py @@ -27,6 +27,11 @@ def test_verify_password(): assert not auth_handler.verify_password( "password", auth_handler.get_password_hash("notpassword") ) + # OIDC-provisioned accounts hold a placeholder instead of a bcrypt hash; + # it has to fail the check rather than raise. + assert not auth_handler.verify_password( + "password", "3f2b1c7e-0c1d-4f5a-9a2b-8e7d6c5b4a39" + ) def test_authenticate_user(admin_user: User): From 1dca4a00e7fa82cc5e7e388d4b608f207059456d Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 09:46:10 -0500 Subject: [PATCH 2/5] fix(security): check an invite before the account checks, and spend it atomically Registration ran the username and email uniqueness checks ahead of the token, so an anonymous caller with any garbage token could enumerate accounts one guess at a time. The token is now verified first, without consuming it, so a registration rejected on a duplicate keeps the invite. Consumption moves from a GET followed by a DELETE to a single GETDEL, so two registrations racing on one invite cannot both see it as valid and both create an account. The invite link itself is no longer written to the log, only its id; the link is already in the response. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/user.py | 4 ++ backend/handler/auth/base_handler.py | 47 ++++++++++++---- backend/tests/endpoints/test_identity.py | 71 ++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 11 deletions(-) diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 246df940c..12d380a8b 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -201,6 +201,10 @@ def create_user_from_invite( UserSchema: Newly created user """ + # Ahead of the "already exists" checks, which would otherwise enumerate + # accounts for an invalid token. Not consumed, so a retry keeps the invite. + auth_handler.assert_invite_link_token_valid(token) + try: validate_username(username) validate_password(password) diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index e020a59a6..d112f39ab 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -74,6 +74,15 @@ def _romm_username(provided: str, fallback: str) -> str: return username +def _invite_token_spent() -> HTTPException: + """The one response for a spent or unusable invite, so neither caller + distinguishes them.""" + return HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invite token has already been used or is invalid.", + ) + + class AuthHandler: def __init__(self) -> None: self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") @@ -257,13 +266,24 @@ class AuthHandler: to_encode, oct_key, ) - invite_link = f"{ROMM_BASE_URL}/register?token={token}" + # The link is already in the response; the token registers an account on + # its own, so the log gets only its id. log.info( - f"Invite link created by {hl(user.username, color=CYAN)}: {hl(invite_link)}" + f"Invite link created by {hl(user.username, color=CYAN)} (jti: {hl(jti)})" ) redis_client.setex(f"invite-jti:{jti}", expires_in, "valid") return token + def assert_invite_link_token_valid(self, token: str) -> None: + """Raise unless the invite link token is valid, leaving it unspent. + + Args: + token (str): The token to check. + """ + jti, _ = self._decode_invite_link_token(token) + if redis_client.get(f"invite-jti:{jti}") != b"valid": + raise _invite_token_spent() + def consume_invite_link_token(self, token: str) -> str: """ Verify and consume the invite link token, which invalidates the token to prevent reuse. @@ -274,6 +294,17 @@ class AuthHandler: Returns: str: The role associated with the token. """ + jti, role = self._decode_invite_link_token(token) + + # Read and invalidate in one operation, so two registrations racing on + # one invite cannot both see it as valid and both create an account. + if redis_client.getdel(f"invite-jti:{jti}") != b"valid": + raise _invite_token_spent() + + return role + + def _decode_invite_link_token(self, token: str) -> tuple[str, str]: + """Decode an invite link token and return its `(jti, role)`.""" try: payload = jwt.decode(token, oct_key, algorithms=[ALGORITHM]) except (BadSignatureError, DecodeError, ValueError) as exc: @@ -287,16 +318,10 @@ class AuthHandler: jti = payload.claims.get("jti") role = payload.claims.get("role", "USER").upper() - if not jti or redis_client.get(f"invite-jti:{jti}") != b"valid": - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Invite token has already been used or is invalid.", - ) + if not jti: + raise _invite_token_spent() - # Invalidate the token as soon as it's read - redis_client.delete(f"invite-jti:{jti}") - - return role + return jti, role class OAuthHandler: diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index 4cf6374c4..d8eb21142 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -222,6 +222,77 @@ def test_update_user_accepts_png_avatar( assert response.json()["avatar_path"].endswith("avatar.png") +def _invite_token(client, access_token: str) -> str: + response = client.post( + "/api/users/invite-link", + params={"role": Role.USER.value}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == HTTPStatus.CREATED + return response.json()["token"] + + +def test_register_with_a_bad_token_does_not_disclose_existing_accounts( + client, access_token: str, editor_user: User +): + """The token is checked first, so the duplicate-account errors below it + cannot be used to enumerate accounts without a valid invite.""" + response = client.post( + "/api/users/register", + json={ + "username": editor_user.username, + "email": "someone@example.com", + "password": "a-good-password", + "token": "not-a-real-token", + }, + ) + + assert response.status_code == HTTPStatus.BAD_REQUEST + assert editor_user.username not in response.json()["detail"] + + +def test_a_rejected_registration_leaves_the_invite_usable( + client, access_token: str, editor_user: User +): + token = _invite_token(client, access_token) + + # Rejected on the duplicate username, after the token was checked. + response = client.post( + "/api/users/register", + json={ + "username": editor_user.username, + "email": "someone@example.com", + "password": "a-good-password", + "token": token, + }, + ) + assert response.status_code == HTTPStatus.BAD_REQUEST + + # The invite was verified, not spent, so it still registers an account. + response = client.post( + "/api/users/register", + json={ + "username": "test_invitee", + "email": "invitee@example.com", + "password": "a-good-password", + "token": token, + }, + ) + assert response.status_code == HTTPStatus.CREATED + + # And now it is spent. + response = client.post( + "/api/users/register", + json={ + "username": "test_invitee_2", + "email": "invitee2@example.com", + "password": "a-good-password", + "token": token, + }, + ) + assert response.status_code == HTTPStatus.BAD_REQUEST + + @pytest.mark.parametrize( "base_url, expected_url", [ From 78fddfe4e96a85aa46ada0bdc1831236f6e30185 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 09:46:16 -0500 Subject: [PATCH 3/5] fix(security): require ownership or admin to refresh another user's RetroAchievements The endpoint took an arbitrary user id under me.write and looked it up with no ownership check, so any authenticated user could trigger a RetroAchievements fetch for another account and overwrite its stored progression. Co-Authored-By: Claude Sonnet 5 --- backend/endpoints/user.py | 4 ++++ backend/tests/endpoints/test_identity.py | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 12d380a8b..e82215444 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -562,6 +562,10 @@ async def refresh_retro_achievements( ] = False, ) -> None: """Refresh RetroAchievements progression data for a user.""" + # Admin users can refresh any user, while other users can only refresh self + if id != request.user.id and request.user.role != Role.ADMIN: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") + user = db_user_handler.get_user(id) if not user or not user.ra_username: raise HTTPException( diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index d8eb21142..adab1b098 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -79,6 +79,18 @@ def test_get_user_avatar( assert response.headers["content-type"].startswith("image/") +def test_refresh_ra_for_another_user_is_forbidden( + client, viewer_access_token: str, admin_user: User +): + # Rejected on ownership before the user is looked up, so it does not depend + # on the target having a RetroAchievements username set. + response = client.post( + f"/api/users/{admin_user.id}/ra/refresh", + headers={"Authorization": f"Bearer {viewer_access_token}"}, + ) + assert response.status_code == status.HTTP_403_FORBIDDEN + + def test_get_user_avatar_none_set(client, access_token: str, admin_user: User): response = client.get( f"/api/users/{admin_user.id}/avatar", From 27404355f0940c6b4429ff825a11ec4a98101a63 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 09:46:22 -0500 Subject: [PATCH 4/5] fix(security): stop 7-Zip reading an archive member name as a switch Member names come from the archive's own listing, so an entry stored as "-x" or "@listfile" was parsed as an option. "--" terminates switch parsing before the name, matching what the bsdtar path already does. Co-Authored-By: Claude Sonnet 5 --- backend/tests/utils/test_archives.py | 13 +++++++++++++ backend/utils/archives.py | 16 +++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index a7051b3fb..a7abc8a33 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -416,6 +416,19 @@ class TestRarArchives: Path("/fake/game.7z"), "a.gba" ) assert seven_zip_command[0] == archives.SEVEN_ZIP_PATH + assert seven_zip_command[-2:] == ["--", "a.gba"] + + def test_extraction_command_terminates_switches_before_the_member(self): + """Member names come from the archive's own listing, so one shaped like + a switch has to reach 7-Zip as a name.""" + for member in ("-x", "@listfile", "-so"): + command = archives._archive_member_command(Path("/fake/game.7z"), member) + assert command[-2:] == ["--", member] + + rar_command = archives._archive_member_command( + Path("/fake/GAME.RAR"), member + ) + assert rar_command[-2:] == ["--", member] def test_read_rar_archive_files_streams_members_in_ascii_order(self): listing = MagicMock( diff --git a/backend/utils/archives.py b/backend/utils/archives.py index 56573277d..e1ca2bfa3 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -177,7 +177,16 @@ def _process_largest_7z_member( start_decompression_time = time.monotonic() with subprocess.Popen( - [SEVEN_ZIP_PATH, "e", str(file_path), largest_file, "-so", "-y", "-spd"], + [ + SEVEN_ZIP_PATH, + "e", + str(file_path), + "-so", + "-y", + "-spd", + "--", + largest_file, + ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated @@ -557,8 +566,9 @@ def _archive_member_command(file_path: Path, member: str) -> list[str]: ] # "-spd" disables wildcard matching so a member name containing "*" or "?" - # can't select (and concatenate) other members. - return [SEVEN_ZIP_PATH, "e", str(file_path), member, "-so", "-y", "-spd"] + # can't select other members; "--" stops switch parsing so one starting + # with "-" or "@" stays a member name. + return [SEVEN_ZIP_PATH, "e", str(file_path), "-so", "-y", "-spd", "--", member] def _list_archive_file_members(file_path: Path) -> list[tuple[str, int]]: From bd7e4b97796d0a9f43a247c3e4c58a0e89baa014 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Tue, 22 Sep 2026 09:58:46 -0500 Subject: [PATCH 5/5] test: cover the invite race and the second 7-Zip call site The sequential reuse test passes against a non-atomic get-then-delete, so it did not pin the property the change exists for. The new test rendezvouses both registrations at the token check and asserts exactly one account is created; reverting consume to get+delete makes it fail. Also asserts the hashing path's 7-Zip command terminates switches, since the real-7zz test only exercises the member-extraction path. Co-Authored-By: Claude Sonnet 5 --- backend/tests/endpoints/test_identity.py | 62 ++++++++++++++++++++++++ backend/tests/utils/test_archives.py | 17 +++++++ 2 files changed, 79 insertions(+) diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index adab1b098..5b0fa0bb2 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -1,5 +1,6 @@ import base64 import json +import threading from datetime import timedelta from http import HTTPStatus from unittest import mock @@ -8,6 +9,7 @@ import pytest from fastapi import status from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +from handler.auth import base_handler as auth_handler_module from handler.auth import oauth_handler from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware from handler.database.users_handler import DBUsersHandler @@ -305,6 +307,66 @@ def test_a_rejected_registration_leaves_the_invite_usable( assert response.status_code == HTTPStatus.BAD_REQUEST +def test_overlapping_registrations_spend_one_invite_once(client, access_token: str): + """Two registrations racing on one invite must not both create an account.""" + from handler.database import db_user_handler + + token = _invite_token(client, access_token) + # Hold each request at the token check until the other arrives, so the only + # thing that can keep the second out is the consume being one operation. + rendezvous = threading.Barrier(2) + live_redis = auth_handler_module.redis_client + + class _RendezvousRedis: + def get(self, key, *args, **kwargs): + value = live_redis.get(key, *args, **kwargs) + if key.startswith("invite-jti:"): + rendezvous.wait(timeout=30) + return value + + def __getattr__(self, name): + return getattr(live_redis, name) + + responses: list = [] + + def register(index: int) -> None: + responses.append( + client.post( + "/api/users/register", + json={ + "username": f"test_racer_{index}", + "email": f"racer{index}@example.com", + "password": "a-good-password", + "token": token, + }, + ) + ) + + with mock.patch.object(auth_handler_module, "redis_client", _RendezvousRedis()): + threads = [threading.Thread(target=register, args=(i,)) for i in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + created = [r for r in responses if r.status_code == HTTPStatus.CREATED] + assert len(created) == 1 + + rejected = [r for r in responses if r.status_code == HTTPStatus.BAD_REQUEST] + assert [r.json()["detail"] for r in rejected] == [ + "Invite token has already been used or is invalid." + ] + + # And the loser left no account behind. + assert ( + sum( + db_user_handler.get_user_by_username(f"test_racer_{i}") is not None + for i in range(2) + ) + == 1 + ) + + @pytest.mark.parametrize( "base_url, expected_url", [ diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index a7abc8a33..333b98c75 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -143,6 +143,23 @@ def test_read_7z_archive_files_raises_when_a_member_fails_midway(): list(chunks) +def test_largest_member_hashing_terminates_switches_before_the_member(): + """The hashing path builds its own 7-Zip command, so a switch-shaped member + name from the archive's own listing must reach it as a name too.""" + # The size comparison has to pick "-x" for it to be the name passed on. + listing = MagicMock(stdout=_fake_7z_listing_sized([("game.bin", 5), ("-x", 99)])) + popen = _mock_popen_streaming([[b"data"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + assert archives._process_largest_7z_member(Path("/fake/game.7z"), MagicMock()) + + command = popen.call_args[0][0] + assert command[-2:] == ["--", "-x"] + + class TestExtractLargestArchiveMember: """Extraction of an archive's largest member to a destination directory, used to feed RAHasher a real ROM file instead of raw container bytes