fix: Avoid query during import time to set add_user endpoint scopes

The `add_user` endpoint was querying the database at import time, to
decide whether to enforce the `users.write` scope or not. This is
problematic because the database might not be ready at import time.

Also, the decided `scopes` was being maintained for the entire
application lifetime, which is not ideal, as users can be created
without having the `users.write` scope, until the application is
restarted.
This commit is contained in:
Michael Manganiello committed 2024-10-13 22:27:14 -03:00
1 parent 4c5221916d
commit 1df27079c4
2 files changed
+69 -10

No files matched your search

+57 -4
View File
@@ -1,7 +1,13 @@
import base64
from datetime import timedelta
from http import HTTPStatus
from unittest import mock
import pytest
from endpoints.auth import ACCESS_TOKEN_EXPIRE_MINUTES
from fastapi.testclient import TestClient
from handler.auth import oauth_handler
from handler.database.users_handler import DBUsersHandler
from handler.redis_handler import sync_cache
from main import app
from models.user import Role
@@ -61,21 +67,68 @@ def test_get_user(client, access_token, editor_user):
assert user["username"] == "test_editor"
def test_create_user(client, access_token):
@pytest.mark.parametrize("new_user_role", [Role.VIEWER, Role.EDITOR, Role.ADMIN])
def test_add_user_from_admin_user(client, access_token, new_user_role):
response = client.post(
"/api/users",
params={
"username": "new_user",
"password": "new_user_password",
"role": "viewer",
"role": new_user_role.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == 201
assert response.status_code == HTTPStatus.CREATED
user = response.json()
assert user["username"] == "new_user"
assert user["role"] == "viewer"
assert user["role"] == new_user_role.value
@pytest.mark.parametrize(
"fixture_requesting_user, existing_admin_users, expected_status_code",
[
("editor_user", False, HTTPStatus.CREATED),
("editor_user", True, HTTPStatus.FORBIDDEN),
("viewer_user", False, HTTPStatus.CREATED),
("viewer_user", True, HTTPStatus.FORBIDDEN),
],
)
def test_add_user_from_unauthorized_user(
request,
client,
admin_user,
fixture_requesting_user,
existing_admin_users,
expected_status_code,
):
requesting_user = request.getfixturevalue(fixture_requesting_user)
data = {
"sub": requesting_user.username,
"iss": "romm:oauth",
"scopes": " ".join(requesting_user.oauth_scopes),
"type": "access",
}
access_token = oauth_handler.create_oauth_token(
data=data, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
with mock.patch.object(
DBUsersHandler,
"get_admin_users",
return_value=[admin_user] if existing_admin_users else [],
):
response = client.post(
"/api/users",
params={
"username": "new_user",
"password": "new_user_password",
"role": Role.VIEWER.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == expected_status_code
def test_update_user(client, access_token, editor_user):
+12 -6
View File
@@ -2,7 +2,7 @@ from pathlib import Path
from typing import Annotated
from anyio import open_file
from config import ASSETS_BASE_PATH, IS_PYTEST_RUN
from config import ASSETS_BASE_PATH
from decorators.auth import protected_route
from endpoints.forms.identity import UserForm
from endpoints.responses import MessageResponse
@@ -21,11 +21,7 @@ router = APIRouter()
@protected_route(
router.post,
"/users",
(
[]
if not IS_PYTEST_RUN and len(db_user_handler.get_admin_users()) == 0
else ["users.write"]
),
[],
status_code=status.HTTP_201_CREATED,
)
def add_user(request: Request, username: str, password: str, role: str) -> UserSchema:
@@ -41,6 +37,16 @@ def add_user(request: Request, username: str, password: str, role: str) -> UserS
UserSchema: Created user info
"""
# If there are admin users already, enforce the `users.write` scope.
if (
"users.write" not in request.auth.scopes
and len(db_user_handler.get_admin_users()) > 0
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Forbidden",
)
if username in [user.username for user in db_user_handler.get_users()]:
msg = f"Username {username} already exists"
log.error(msg)