From 41f64eb42b7c48dfdf63d36ffe2c8d44cdc2ad7a Mon Sep 17 00:00:00 2001 From: HydroSulphide Date: Mon, 9 Mar 2026 17:03:29 +0100 Subject: [PATCH 1/7] fix: oauth token invalidation on expiration date and rotating refresh token --- backend/endpoints/auth.py | 29 +++++++---- backend/endpoints/responses/oauth.py | 3 +- backend/handler/auth/base_handler.py | 77 +++++++++++++++++++++++++++- 3 files changed, 97 insertions(+), 12 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index 4acbfed0c..29bde9f22 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -93,7 +93,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp TokenResponse: TypedDict with the new generated token info """ - # Suppport refreshing access tokens + # Support refreshing access tokens if form_data.grant_type == "refresh_token": token = form_data.refresh_token if not token: @@ -101,9 +101,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp status_code=status.HTTP_400_BAD_REQUEST, detail="Missing refresh token" ) - user, claims = await oauth_handler.get_current_active_user_from_bearer_token( - 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" @@ -119,7 +117,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled" ) - access_token = oauth_handler.create_oauth_token( + access_token = oauth_handler.create_access_token( data={ "sub": user.username, "iss": "romm:oauth", @@ -129,10 +127,22 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) + refresh_token = oauth_handler.create_refresh_token( + data={ + "sub": user.username, + "iss": "romm:oauth", + "scopes": claims.get("scopes"), + "type": "refresh", + }, + expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS), + ) + return { "access_token": access_token, + "refresh_token": refresh_token, "token_type": "bearer", # trunk-ignore(bandit/B105) - "expires": ACCESS_TOKEN_EXPIRE_SECONDS, + "expires_in": ACCESS_TOKEN_EXPIRE_SECONDS, + "refresh_expires_in": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, } # Authentication via username/password @@ -176,7 +186,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp detail="Insufficient scope", ) - access_token = oauth_handler.create_oauth_token( + access_token = oauth_handler.create_access_token( data={ "sub": user.username, "iss": "romm:oauth", @@ -186,7 +196,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) - refresh_token = oauth_handler.create_oauth_token( + refresh_token = oauth_handler.create_refresh_token( data={ "sub": user.username, "iss": "romm:oauth", @@ -200,7 +210,8 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer", # trunk-ignore(bandit/B105) - "expires": ACCESS_TOKEN_EXPIRE_SECONDS, + "expires_in": ACCESS_TOKEN_EXPIRE_SECONDS, + "refresh_expires_in": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, } diff --git a/backend/endpoints/responses/oauth.py b/backend/endpoints/responses/oauth.py index f70023a9b..179f704c0 100644 --- a/backend/endpoints/responses/oauth.py +++ b/backend/endpoints/responses/oauth.py @@ -5,4 +5,5 @@ class TokenResponse(TypedDict): access_token: str refresh_token: NotRequired[str] token_type: str - expires: int + expires_in: int + refresh_expires_in: int diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 0c2b1c460..d56240bf0 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -249,10 +249,10 @@ class OAuthHandler: pass def create_oauth_token( - self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY + self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY ) -> str: to_encode = data.copy() - expire = datetime.now(timezone.utc) + expires_delta + expire = int((datetime.now(timezone.utc) + expires_delta).timestamp()) to_encode.update({"exp": expire}) return jwt.encode( @@ -261,6 +261,75 @@ class OAuthHandler: oct_key, ) + def create_access_token( + self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY + ) -> str: + return self.create_oauth_token(data, expires_delta) + + def create_refresh_token( + self, data: dict, expires_delta: timedelta + ) -> str: + to_encode = data.copy() + expire = int((datetime.now(timezone.utc) + expires_delta).timestamp()) + jti = str(uuid.uuid4()) + + to_encode.update({ + "exp": expire, + "jti": jti, + "type": "refresh", + }) + + token = jwt.encode( + {"alg": ALGORITHM}, + to_encode, + oct_key, + ) + + redis_client.setex( + f"refresh-jti:{jti}", + int(expires_delta.total_seconds()), + "valid", + ) + + return token + + async def consume_refresh_token(self, token: str): + from handler.database import db_user_handler + + try: + payload = jwt.decode(token, oct_key, algorithms=[ALGORITHM]) + except (BadSignatureError, DecodeError, ValueError) as exc: + raise OAuthCredentialsException from exc + + now = datetime.now(timezone.utc).timestamp() + if now > payload.claims.get("exp", 0): + raise OAuthCredentialsException + + if payload.claims.get("iss") != "romm:oauth": + raise OAuthCredentialsException + + if payload.claims.get("type") != "refresh": + raise OAuthCredentialsException + + jti = payload.claims.get("jti") + if not jti or redis_client.get(f"refresh-jti:{jti}") != b"valid": + raise OAuthCredentialsException + + redis_client.delete(f"refresh-jti:{jti}") + + username = payload.claims.get("sub") + if not username: + raise OAuthCredentialsException + + user = db_user_handler.get_user_by_username(username) + if user is None: + raise OAuthCredentialsException + + if not user.enabled: + raise UserDisabledException + + return user, payload.claims + async def get_current_active_user_from_bearer_token(self, token: str): from handler.database import db_user_handler @@ -269,6 +338,10 @@ class OAuthHandler: except (BadSignatureError, DecodeError, ValueError) as exc: raise OAuthCredentialsException from exc + now = datetime.now(timezone.utc).timestamp() + if now > payload.claims.get("exp", 0): + raise OAuthCredentialsException + issuer = payload.claims.get("iss") if not issuer or issuer != "romm:oauth": return None, None From ad09babce8c99eac529aa19b5b44b703ddc27b98 Mon Sep 17 00:00:00 2001 From: HydroSulphide Date: Mon, 9 Mar 2026 18:29:28 +0100 Subject: [PATCH 2/7] fix: catch http exception on code 401 so api call with expired access token doesn't lead to internal server error --- backend/handler/auth/hybrid_auth.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index e3d610e61..c9be10895 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,4 +1,5 @@ from fastapi.security.http import HTTPBasic +from fastapi import HTTPException from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection @@ -40,10 +41,12 @@ class HybridAuthBackend(AuthenticationBackend): # Check if bearer auth header is valid if scheme.lower() == "bearer": - ( - user, - claims, - ) = await oauth_handler.get_current_active_user_from_bearer_token(token) + try: + user, claims = await oauth_handler.get_current_active_user_from_bearer_token(token) + except HTTPException as exc: + if exc.status_code == 401: + return None + if user is None or claims is None: return None From 8758cb31b73cb5e62efae502ed1e0533c2aa638c Mon Sep 17 00:00:00 2001 From: HydroSulphide Date: Tue, 10 Mar 2026 07:22:02 +0100 Subject: [PATCH 3/7] Tried to fix everything the bot complained about and the failed pytests. Three tests were also implemented to check initial implementation that now invalidates expired access and refresh tokens and also rotating refresh tokens. Since I introduced wrapper functions for create_oauth_token to distinguish between access and refresh token there is no need to set the token type in the data dict, since the type is now enforced in the wrapper functions create_access_token and create_refresh_token. By convention I renamed create_oauth_token to _create_oauth_token as it is considered a private helper function now. --- backend/endpoints/auth.py | 17 ++----- backend/endpoints/responses/oauth.py | 4 +- backend/handler/auth/base_handler.py | 38 +++++++--------- backend/handler/auth/hybrid_auth.py | 9 ++-- backend/tests/endpoints/conftest.py | 6 +-- backend/tests/endpoints/roms/test_upload.py | 3 +- backend/tests/endpoints/test_device.py | 3 +- backend/tests/endpoints/test_identity.py | 3 +- backend/tests/endpoints/test_oauth.py | 39 ++++++++++++++++ backend/tests/endpoints/test_saves.py | 3 +- backend/tests/endpoints/test_tasks.py | 3 +- backend/tests/handler/auth/test_auth.py | 12 ++--- backend/tests/handler/auth/test_oauth.py | 49 ++++++++++++++++++--- 13 files changed, 120 insertions(+), 69 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index 29bde9f22..21b2bf340 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -107,11 +107,6 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token" ) - if claims.get("type") != "refresh": - 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" @@ -122,7 +117,6 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "sub": user.username, "iss": "romm:oauth", "scopes": claims.get("scopes"), - "type": "access", }, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) @@ -132,7 +126,6 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "sub": user.username, "iss": "romm:oauth", "scopes": claims.get("scopes"), - "type": "refresh", }, expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS), ) @@ -141,8 +134,8 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer", # trunk-ignore(bandit/B105) - "expires_in": ACCESS_TOKEN_EXPIRE_SECONDS, - "refresh_expires_in": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, + "expires": ACCESS_TOKEN_EXPIRE_SECONDS, + "refresh_expires": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, } # Authentication via username/password @@ -191,7 +184,6 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "sub": user.username, "iss": "romm:oauth", "scopes": " ".join(form_data.scopes), - "type": "access", }, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) @@ -201,7 +193,6 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "sub": user.username, "iss": "romm:oauth", "scopes": " ".join(form_data.scopes), - "type": "refresh", }, expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS), ) @@ -210,8 +201,8 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp "access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer", # trunk-ignore(bandit/B105) - "expires_in": ACCESS_TOKEN_EXPIRE_SECONDS, - "refresh_expires_in": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, + "expires": ACCESS_TOKEN_EXPIRE_SECONDS, + "refresh_expires": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, } diff --git a/backend/endpoints/responses/oauth.py b/backend/endpoints/responses/oauth.py index 179f704c0..e217b5459 100644 --- a/backend/endpoints/responses/oauth.py +++ b/backend/endpoints/responses/oauth.py @@ -5,5 +5,5 @@ class TokenResponse(TypedDict): access_token: str refresh_token: NotRequired[str] token_type: str - expires_in: int - refresh_expires_in: int + expires: int + refresh_expires: int diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index d56240bf0..4315a6570 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -248,12 +248,12 @@ class OAuthHandler: def __init__(self) -> None: pass - def create_oauth_token( - self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY + def _create_oauth_token( + self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY ) -> str: to_encode = data.copy() expire = int((datetime.now(timezone.utc) + expires_delta).timestamp()) - to_encode.update({"exp": expire}) + to_encode["exp"] = expire return jwt.encode( {"alg": ALGORITHM}, @@ -263,28 +263,23 @@ class OAuthHandler: def create_access_token( self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY - ) -> str: - return self.create_oauth_token(data, expires_delta) - - def create_refresh_token( - self, data: dict, expires_delta: timedelta ) -> str: to_encode = data.copy() - expire = int((datetime.now(timezone.utc) + expires_delta).timestamp()) + to_encode["type"] = "access" + return self._create_oauth_token(to_encode, expires_delta) + + def create_refresh_token(self, data: dict, expires_delta: timedelta) -> str: + to_encode = data.copy() jti = str(uuid.uuid4()) - - to_encode.update({ - "exp": expire, - "jti": jti, - "type": "refresh", - }) - - token = jwt.encode( - {"alg": ALGORITHM}, - to_encode, - oct_key, + to_encode.update( + { + "jti": jti, + "type": "refresh", + } ) + token = self._create_oauth_token(to_encode, expires_delta) + redis_client.setex( f"refresh-jti:{jti}", int(expires_delta.total_seconds()), @@ -315,8 +310,6 @@ class OAuthHandler: if not jti or redis_client.get(f"refresh-jti:{jti}") != b"valid": raise OAuthCredentialsException - redis_client.delete(f"refresh-jti:{jti}") - username = payload.claims.get("sub") if not username: raise OAuthCredentialsException @@ -328,6 +321,7 @@ class OAuthHandler: if not user.enabled: raise UserDisabledException + redis_client.delete(f"refresh-jti:{jti}") return user, payload.claims async def get_current_active_user_from_bearer_token(self, token: str): diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index c9be10895..03c40304e 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,5 +1,4 @@ from fastapi.security.http import HTTPBasic -from fastapi import HTTPException from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection @@ -41,11 +40,9 @@ class HybridAuthBackend(AuthenticationBackend): # Check if bearer auth header is valid if scheme.lower() == "bearer": - try: - user, claims = await oauth_handler.get_current_active_user_from_bearer_token(token) - except HTTPException as exc: - if exc.status_code == 401: - return None + user, claims = ( + await oauth_handler.get_current_active_user_from_bearer_token(token) + ) if user is None or claims is None: return None diff --git a/backend/tests/endpoints/conftest.py b/backend/tests/endpoints/conftest.py index 432c91bc5..9343667e6 100644 --- a/backend/tests/endpoints/conftest.py +++ b/backend/tests/endpoints/conftest.py @@ -12,10 +12,9 @@ def access_token(admin_user): # noqa "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(admin_user.oauth_scopes), - "type": "access", } - return oauth_handler.create_oauth_token( + return oauth_handler.create_access_token( data=data, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS) ) @@ -26,9 +25,8 @@ def refresh_token(admin_user): # noqa "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(admin_user.oauth_scopes), - "type": "refresh", } - return oauth_handler.create_oauth_token( + return oauth_handler.create_refresh_token( data=data, expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) ) diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index bee083bf6..286772bfe 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -31,12 +31,11 @@ def clear_cache(): @pytest.fixture def editor_access_token(editor_user: User): - return oauth_handler.create_oauth_token( + return oauth_handler.create_access_token( data={ "sub": editor_user.username, "iss": "romm:oauth", "scopes": " ".join(editor_user.oauth_scopes), - "type": "access", }, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) diff --git a/backend/tests/endpoints/test_device.py b/backend/tests/endpoints/test_device.py index a36a22386..a165df2a2 100644 --- a/backend/tests/endpoints/test_device.py +++ b/backend/tests/endpoints/test_device.py @@ -27,12 +27,11 @@ def clear_cache(): @pytest.fixture def editor_access_token(editor_user: User): - return oauth_handler.create_oauth_token( + return oauth_handler.create_access_token( data={ "sub": editor_user.username, "iss": "romm:oauth", "scopes": " ".join(editor_user.oauth_scopes), - "type": "access", }, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index c28ad12e3..6f5daa0f2 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -111,9 +111,8 @@ def test_add_user_from_unauthorized_user( "sub": requesting_user.username, "iss": "romm:oauth", "scopes": " ".join(requesting_user.oauth_scopes), - "type": "access", } - access_token = oauth_handler.create_oauth_token( + access_token = oauth_handler.create_access_token( data=data, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS) ) diff --git a/backend/tests/endpoints/test_oauth.py b/backend/tests/endpoints/test_oauth.py index e31bc44af..12aedab80 100644 --- a/backend/tests/endpoints/test_oauth.py +++ b/backend/tests/endpoints/test_oauth.py @@ -57,6 +57,45 @@ def test_refreshing_oauth_token_with_invalid_refresh_token(client): assert e.detail == "Invalid refresh token" +def test_refresh_token_rotation_invalidates_old_token(client, refresh_token): + first_response = client.post( + "/api/token", + data={ + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + + assert first_response.status_code == status.HTTP_200_OK + first_body = first_response.json() + + assert first_body["access_token"] + assert first_body["refresh_token"] + assert first_body["refresh_token"] != refresh_token + + new_refresh_token = first_body["refresh_token"] + + second_response = client.post( + "/api/token", + data={ + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + + assert second_response.status_code == status.HTTP_401_UNAUTHORIZED + + third_response = client.post( + "/api/token", + data={ + "grant_type": "refresh_token", + "refresh_token": new_refresh_token, + }, + ) + + assert third_response.status_code == status.HTTP_200_OK + + def test_auth_via_upass(client, admin_user): response = client.post( "/api/token", diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index 660e8a9c3..7a2a279a5 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -49,12 +49,11 @@ def token_without_device_scopes(admin_user: User): for s in admin_user.oauth_scopes if s not in (Scope.DEVICES_READ, Scope.DEVICES_WRITE) ] - return oauth_handler.create_oauth_token( + return oauth_handler.create_access_token( data={ "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(scopes), - "type": "access", }, expires_delta=timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS), ) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index ea0451150..f231d59b9 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -196,10 +196,9 @@ class TestListTasks: "sub": admin_user.username, "iss": "romm:oauth", "scopes": "roms:read", # Missing TASKS_RUN scope - "type": "access", } - token = oauth_handler.create_oauth_token( + token = oauth_handler.create_access_token( data=data, expires_delta=timedelta(minutes=30) ) diff --git a/backend/tests/handler/auth/test_auth.py b/backend/tests/handler/auth/test_auth.py index 9e22f8e49..fe902f53a 100644 --- a/backend/tests/handler/auth/test_auth.py +++ b/backend/tests/handler/auth/test_auth.py @@ -1,10 +1,12 @@ from base64 import b64encode +from datetime import timedelta import pytest from fastapi import status from fastapi.exceptions import HTTPException from starlette.requests import HTTPConnection +from endpoints.auth import REFRESH_TOKEN_EXPIRE_DAYS from handler.auth import auth_handler, oauth_handler from handler.auth.constants import EDIT_SCOPES from handler.auth.hybrid_auth import HybridAuthBackend @@ -107,12 +109,11 @@ async def test_hybrid_auth_backend_empty_session_and_headers(editor_user: User): async def test_hybrid_auth_backend_bearer_auth_header(editor_user: User): - access_token = oauth_handler.create_oauth_token( + access_token = oauth_handler.create_access_token( data={ "sub": editor_user.username, "iss": "romm:oauth", "scopes": " ".join(editor_user.oauth_scopes), - "type": "access", }, ) @@ -192,13 +193,13 @@ async def test_hybrid_auth_backend_invalid_scheme(): async def test_hybrid_auth_backend_with_refresh_token(editor_user: User): - refresh_token = oauth_handler.create_oauth_token( + refresh_token = oauth_handler.create_refresh_token( data={ "sub": editor_user.username, "iss": "romm:oauth", "scopes": " ".join(editor_user.oauth_scopes), - "type": "refresh", }, + expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS), ) class MockConnection(HTTPConnection): @@ -215,12 +216,11 @@ async def test_hybrid_auth_backend_with_refresh_token(editor_user: User): async def test_hybrid_auth_backend_scope_subset(editor_user: User): scopes = editor_user.oauth_scopes[:3] - access_token = oauth_handler.create_oauth_token( + access_token = oauth_handler.create_access_token( data={ "sub": editor_user.username, "iss": "romm:oauth", "scopes": " ".join(scopes), - "type": "access", }, ) diff --git a/backend/tests/handler/auth/test_oauth.py b/backend/tests/handler/auth/test_oauth.py index c87704c35..dd2440d31 100644 --- a/backend/tests/handler/auth/test_oauth.py +++ b/backend/tests/handler/auth/test_oauth.py @@ -1,3 +1,5 @@ +from datetime import timedelta + import pytest from fastapi import Request, status from fastapi.exceptions import HTTPException @@ -9,18 +11,17 @@ from utils.router import APIRouter def test_create_oauth_token(): - token = oauth_handler.create_oauth_token(data={"sub": "test_user"}) + token = oauth_handler.create_access_token(data={"sub": "test_user"}) assert isinstance(token, str) async def test_get_current_active_user_from_bearer_token(admin_user): - token = oauth_handler.create_oauth_token( + token = oauth_handler.create_access_token( data={ "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(admin_user.oauth_scopes), - "type": "access", }, ) user, claims = await oauth_handler.get_current_active_user_from_bearer_token(token) @@ -40,7 +41,7 @@ async def test_get_current_active_user_from_bearer_token_invalid_token(): async def test_get_current_active_user_from_bearer_token_invalid_user(): - token = oauth_handler.create_oauth_token( + token = oauth_handler.create_access_token( data={"sub": "invalid_user", "iss": "romm:oauth"} ) @@ -49,12 +50,11 @@ async def test_get_current_active_user_from_bearer_token_invalid_user(): async def test_get_current_active_user_from_bearer_token_disabled_user(admin_user): - token = oauth_handler.create_oauth_token( + token = oauth_handler.create_access_token( data={ "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(admin_user.oauth_scopes), - "type": "access", }, ) @@ -67,6 +67,43 @@ async def test_get_current_active_user_from_bearer_token_disabled_user(admin_use assert e.detail == "Disabled user" +async def test_get_current_active_user_from_bearer_token_expired_token(admin_user): + token = oauth_handler.create_access_token( + data={ + "sub": admin_user.username, + "iss": "romm:oauth", + "scopes": " ".join(admin_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=-1), + ) + + with pytest.raises(HTTPException) as exc: + await oauth_handler.get_current_active_user_from_bearer_token(token) + + assert exc.value.status_code == status.HTTP_401_UNAUTHORIZED + + +def test_refreshing_oauth_token_expired_refresh_token(client, admin_user): + refresh_token = oauth_handler.create_refresh_token( + data={ + "sub": admin_user.username, + "iss": "romm:oauth", + "scopes": " ".join(admin_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=-1), + ) + + response = client.post( + "/api/token", + data={ + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + + assert response.status_code == status.HTTP_401_UNAUTHORIZED + + def test_protected_route(): router = APIRouter() From 02336974a651cae94b2ca97beb681ca4cf1802d4 Mon Sep 17 00:00:00 2001 From: HydroSulphide Date: Tue, 10 Mar 2026 08:04:07 +0100 Subject: [PATCH 4/7] Implemented greptile suggestions --- backend/endpoints/responses/oauth.py | 2 +- backend/handler/auth/base_handler.py | 3 +++ backend/handler/auth/hybrid_auth.py | 14 +++++++++++--- backend/tests/handler/auth/test_oauth.py | 22 +++++++++++++++++----- 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/backend/endpoints/responses/oauth.py b/backend/endpoints/responses/oauth.py index e217b5459..11c6f2dac 100644 --- a/backend/endpoints/responses/oauth.py +++ b/backend/endpoints/responses/oauth.py @@ -6,4 +6,4 @@ class TokenResponse(TypedDict): refresh_token: NotRequired[str] token_type: str expires: int - refresh_expires: int + refresh_expires: NotRequired[int] diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 4315a6570..9847b289a 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -269,6 +269,9 @@ class OAuthHandler: return self._create_oauth_token(to_encode, expires_delta) def create_refresh_token(self, data: dict, expires_delta: timedelta) -> str: + if expires_delta <= timedelta(0): + raise ValueError("expires_delta must be positive for refresh tokens") + to_encode = data.copy() jti = str(uuid.uuid4()) to_encode.update( diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index 03c40304e..e1d1d9d6a 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,3 +1,4 @@ +from fastapi import HTTPException, status from fastapi.security.http import HTTPBasic from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection @@ -40,9 +41,16 @@ class HybridAuthBackend(AuthenticationBackend): # Check if bearer auth header is valid if scheme.lower() == "bearer": - user, claims = ( - await oauth_handler.get_current_active_user_from_bearer_token(token) - ) + try: + user, claims = ( + await oauth_handler.get_current_active_user_from_bearer_token( + token + ) + ) + except HTTPException as exc: + if exc.status_code == status.HTTP_401_UNAUTHORIZED: + return None + raise if user is None or claims is None: return None diff --git a/backend/tests/handler/auth/test_oauth.py b/backend/tests/handler/auth/test_oauth.py index dd2440d31..db11f0e35 100644 --- a/backend/tests/handler/auth/test_oauth.py +++ b/backend/tests/handler/auth/test_oauth.py @@ -1,11 +1,13 @@ -from datetime import timedelta +from datetime import datetime, timedelta, timezone import pytest from fastapi import Request, status from fastapi.exceptions import HTTPException +from joserfc import jwt from decorators.auth import protected_route from handler.auth import oauth_handler +from handler.auth.base_handler import ALGORITHM, oct_key from handler.database import db_user_handler from utils.router import APIRouter @@ -83,16 +85,26 @@ async def test_get_current_active_user_from_bearer_token_expired_token(admin_use assert exc.value.status_code == status.HTTP_401_UNAUTHORIZED -def test_refreshing_oauth_token_expired_refresh_token(client, admin_user): - refresh_token = oauth_handler.create_refresh_token( - data={ +def make_expired_refresh_token(admin_user) -> str: + expire = int((datetime.now(timezone.utc) + timedelta(seconds=-1)).timestamp()) + + return jwt.encode( + {"alg": ALGORITHM}, + { "sub": admin_user.username, "iss": "romm:oauth", "scopes": " ".join(admin_user.oauth_scopes), + "type": "refresh", + "jti": "expired-test-jti", + "exp": expire, }, - expires_delta=timedelta(seconds=-1), + oct_key, ) + +def test_refreshing_oauth_token_expired_refresh_token(client, admin_user): + refresh_token = make_expired_refresh_token(admin_user) + response = client.post( "/api/token", data={ From fd788684b96ff8a731f56079da419b29c6e232c3 Mon Sep 17 00:00:00 2001 From: HydroSulphide Date: Tue, 10 Mar 2026 08:38:32 +0100 Subject: [PATCH 5/7] fix: TOCTOU race condition allows duplicate refresh token use --- backend/handler/auth/base_handler.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 9847b289a..8a07ecadf 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -310,7 +310,7 @@ class OAuthHandler: raise OAuthCredentialsException jti = payload.claims.get("jti") - if not jti or redis_client.get(f"refresh-jti:{jti}") != b"valid": + if not jti or redis_client.getdel(f"refresh-jti:{jti}") != b"valid": raise OAuthCredentialsException username = payload.claims.get("sub") @@ -323,8 +323,6 @@ class OAuthHandler: if not user.enabled: raise UserDisabledException - - redis_client.delete(f"refresh-jti:{jti}") return user, payload.claims async def get_current_active_user_from_bearer_token(self, token: str): From f6eb686559413d6702d312e802816e31fdf936b1 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 10 Mar 2026 08:38:43 -0400 Subject: [PATCH 6/7] fix tests --- backend/handler/auth/hybrid_auth.py | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index e1d1d9d6a..688b8c081 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,4 +1,3 @@ -from fastapi import HTTPException, status from fastapi.security.http import HTTPBasic from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection @@ -41,16 +40,10 @@ class HybridAuthBackend(AuthenticationBackend): # Check if bearer auth header is valid if scheme.lower() == "bearer": - try: - user, claims = ( - await oauth_handler.get_current_active_user_from_bearer_token( - token - ) - ) - except HTTPException as exc: - if exc.status_code == status.HTTP_401_UNAUTHORIZED: - return None - raise + ( + user, + claims, + ) = await oauth_handler.get_current_active_user_from_bearer_token(token) if user is None or claims is None: return None From f0e5abadc90d63ab4f81c9af7f5e6f0c0c768fd5 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 10 Mar 2026 09:23:12 -0400 Subject: [PATCH 7/7] fix tests again --- backend/tests/conftest.py | 22 +++++++++++++++ backend/tests/endpoints/test_oauth.py | 14 ++++++++++ backend/tests/handler/auth/test_oauth.py | 35 +----------------------- 3 files changed, 37 insertions(+), 34 deletions(-) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 0f7f19f4b..37138fb50 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,10 +1,14 @@ +from datetime import datetime, timedelta, timezone + import alembic.config import pytest +from joserfc import jwt from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from config.config_manager import ConfigManager from handler.auth import auth_handler +from handler.auth.base_handler import ALGORITHM, oct_key from handler.database import ( db_platform_handler, db_rom_handler, @@ -153,3 +157,21 @@ def viewer_user(): role=Role.VIEWER, ) return db_user_handler.add_user(user) + + +@pytest.fixture +def expired_refresh_token(admin_user: User) -> str: + expire = int((datetime.now(timezone.utc) + timedelta(seconds=-1)).timestamp()) + + return jwt.encode( + {"alg": ALGORITHM}, + { + "sub": admin_user.username, + "iss": "romm:oauth", + "scopes": " ".join(admin_user.oauth_scopes), + "type": "refresh", + "jti": "expired-test-jti", + "exp": expire, + }, + oct_key, + ) diff --git a/backend/tests/endpoints/test_oauth.py b/backend/tests/endpoints/test_oauth.py index 12aedab80..c4ca8f6c2 100644 --- a/backend/tests/endpoints/test_oauth.py +++ b/backend/tests/endpoints/test_oauth.py @@ -156,3 +156,17 @@ def test_auth_with_invalid_grant_type(client): except HTTPException as e: assert e.status_code == status.HTTP_400_BAD_REQUEST assert e.detail == "Invalid or unsupported grant type" + + +def test_refreshing_oauth_token_expired_refresh_token( + client, admin_user, expired_refresh_token +): + response = client.post( + "/api/token", + data={ + "grant_type": "refresh_token", + "refresh_token": expired_refresh_token, + }, + ) + + assert response.status_code == status.HTTP_401_UNAUTHORIZED diff --git a/backend/tests/handler/auth/test_oauth.py b/backend/tests/handler/auth/test_oauth.py index db11f0e35..ca292750f 100644 --- a/backend/tests/handler/auth/test_oauth.py +++ b/backend/tests/handler/auth/test_oauth.py @@ -1,13 +1,11 @@ -from datetime import datetime, timedelta, timezone +from datetime import timedelta import pytest from fastapi import Request, status from fastapi.exceptions import HTTPException -from joserfc import jwt from decorators.auth import protected_route from handler.auth import oauth_handler -from handler.auth.base_handler import ALGORITHM, oct_key from handler.database import db_user_handler from utils.router import APIRouter @@ -85,37 +83,6 @@ async def test_get_current_active_user_from_bearer_token_expired_token(admin_use assert exc.value.status_code == status.HTTP_401_UNAUTHORIZED -def make_expired_refresh_token(admin_user) -> str: - expire = int((datetime.now(timezone.utc) + timedelta(seconds=-1)).timestamp()) - - return jwt.encode( - {"alg": ALGORITHM}, - { - "sub": admin_user.username, - "iss": "romm:oauth", - "scopes": " ".join(admin_user.oauth_scopes), - "type": "refresh", - "jti": "expired-test-jti", - "exp": expire, - }, - oct_key, - ) - - -def test_refreshing_oauth_token_expired_refresh_token(client, admin_user): - refresh_token = make_expired_refresh_token(admin_user) - - response = client.post( - "/api/token", - data={ - "grant_type": "refresh_token", - "refresh_token": refresh_token, - }, - ) - - assert response.status_code == status.HTTP_401_UNAUTHORIZED - - def test_protected_route(): router = APIRouter()