mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
Merge pull request #3102 from HydroSulphide/fix-oauth-token-expiry-and-refresh-rotation
Fix OAuth token expiry and implement refresh token rotation
This commit is contained in:
@@ -122,7 +122,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:
|
||||
@@ -130,38 +130,41 @@ 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"
|
||||
)
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
access_token = oauth_handler.create_oauth_token(
|
||||
access_token = oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": claims.get("scopes"),
|
||||
"type": "access",
|
||||
},
|
||||
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"),
|
||||
},
|
||||
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,
|
||||
"refresh_expires": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,
|
||||
}
|
||||
|
||||
# Authentication via username/password
|
||||
@@ -205,22 +208,20 @@ 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",
|
||||
"scopes": " ".join(form_data.scopes),
|
||||
"type": "access",
|
||||
},
|
||||
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",
|
||||
"scopes": " ".join(form_data.scopes),
|
||||
"type": "refresh",
|
||||
},
|
||||
expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS),
|
||||
)
|
||||
@@ -230,6 +231,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
|
||||
"refresh_token": refresh_token,
|
||||
"token_type": "bearer", # trunk-ignore(bandit/B105)
|
||||
"expires": ACCESS_TOKEN_EXPIRE_SECONDS,
|
||||
"refresh_expires": REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ class TokenResponse(TypedDict):
|
||||
refresh_token: NotRequired[str]
|
||||
token_type: str
|
||||
expires: int
|
||||
refresh_expires: NotRequired[int]
|
||||
|
||||
|
||||
class OIDCLogoutResponse(TypedDict):
|
||||
|
||||
@@ -248,12 +248,12 @@ class OAuthHandler:
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def create_oauth_token(
|
||||
def _create_oauth_token(
|
||||
self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY
|
||||
) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
to_encode.update({"exp": expire})
|
||||
expire = int((datetime.now(timezone.utc) + expires_delta).timestamp())
|
||||
to_encode["exp"] = expire
|
||||
|
||||
return jwt.encode(
|
||||
{"alg": ALGORITHM},
|
||||
@@ -261,6 +261,70 @@ class OAuthHandler:
|
||||
oct_key,
|
||||
)
|
||||
|
||||
def create_access_token(
|
||||
self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY
|
||||
) -> str:
|
||||
to_encode = data.copy()
|
||||
to_encode["type"] = "access"
|
||||
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(
|
||||
{
|
||||
"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()),
|
||||
"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.getdel(f"refresh-jti:{jti}") != b"valid":
|
||||
raise OAuthCredentialsException
|
||||
|
||||
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 +333,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
|
||||
|
||||
@@ -44,6 +44,7 @@ class HybridAuthBackend(AuthenticationBackend):
|
||||
user,
|
||||
claims,
|
||||
) = await oauth_handler.get_current_active_user_from_bearer_token(token)
|
||||
|
||||
if user is None or claims is None:
|
||||
return None
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
|
||||
|
||||
@@ -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",
|
||||
@@ -117,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
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -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,22 @@ 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_protected_route():
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user