mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
Merge pull request #4694 from rommapp/claude/authz-and-invite-hardening
fix(security): check endpoint ownership and consume invites atomically
This commit is contained in:
@@ -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)
|
||||
@@ -565,6 +569,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(
|
||||
|
||||
@@ -75,6 +75,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")
|
||||
@@ -89,7 +98,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)
|
||||
@@ -289,13 +303,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.
|
||||
@@ -306,6 +331,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:
|
||||
@@ -319,16 +355,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:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
@@ -9,6 +10,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
|
||||
@@ -80,6 +82,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",
|
||||
@@ -223,6 +237,137 @@ 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
|
||||
|
||||
|
||||
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",
|
||||
[
|
||||
|
||||
@@ -28,6 +28,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):
|
||||
|
||||
@@ -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
|
||||
@@ -416,6 +433,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(
|
||||
|
||||
@@ -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]]:
|
||||
|
||||
Reference in New Issue
Block a user