-
-
Notifications
You must be signed in to change notification settings - Fork 50
Add DELETE /users/{id} with no-resources rule #317
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
igennova
wants to merge
3
commits into
openml:main
Choose a base branch
from
igennova:issue/194
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| """User account HTTP endpoints.""" | ||
|
|
||
| from typing import Annotated | ||
|
|
||
| from fastapi import APIRouter, Depends, Path, Response | ||
| from loguru import logger | ||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| import database.users | ||
| from core.errors import AccountHasResourcesError, ForbiddenError, UserNotFoundError | ||
| from database.users import User | ||
| from routers.dependencies import expdb_connection, fetch_user_or_raise, userdb_connection | ||
|
|
||
| _ACCOUNT_HAS_RESOURCES_MSG = ( | ||
| "Cannot delete this account while records still reference the user " | ||
| "(datasets, flows, runs, studies, tags, etc.). Remove or transfer them first." | ||
| ) | ||
|
|
||
| router = APIRouter(prefix="/users", tags=["users"]) | ||
|
|
||
|
|
||
| @router.delete( | ||
| "/{user_id}", | ||
| responses={ | ||
| 204: {"description": "User account deleted."}, | ||
| 401: {"description": "Authentication failed or missing."}, | ||
| 403: {"description": "Not allowed to delete this account."}, | ||
| 404: {"description": "User id not found."}, | ||
| 409: {"description": "User still has datasets, flows, runs, or studies."}, | ||
| }, | ||
| ) | ||
| async def delete_user_account( | ||
| user_id: Annotated[int, Path(description="Numeric user id to delete.", gt=0)], | ||
| current_user: Annotated[User, Depends(fetch_user_or_raise)], | ||
| expdb: Annotated[AsyncConnection, Depends(expdb_connection)], | ||
| userdb: Annotated[AsyncConnection, Depends(userdb_connection)], | ||
| ) -> Response: | ||
| """Delete the user account if they have no associated resources. | ||
|
|
||
| The account to be deleted must not have associated resources (such as | ||
| datasets, tasks, or tags). Users may only delete their own account. | ||
| Administrators may delete any account that satisfies the no-resources rule. | ||
| """ | ||
| if current_user.user_id != user_id and not await current_user.is_admin(): | ||
| msg = "You may only delete your own user account." | ||
| raise ForbiddenError(msg) | ||
|
|
||
| if not await database.users.exists_by_id(user_id=user_id, connection=userdb): | ||
| msg = f"User {user_id} not found." | ||
| raise UserNotFoundError(msg) | ||
|
|
||
| if await database.users.has_user_references(user_id=user_id, expdb=expdb): | ||
| raise AccountHasResourcesError(_ACCOUNT_HAS_RESOURCES_MSG) | ||
|
|
||
| try: | ||
| await database.users.delete_user_rows(user_id=user_id, userdb=userdb) | ||
| except IntegrityError as exc: | ||
| logger.error( | ||
| "Delete of user {user_id} failed with integrity error after pre-check.", | ||
| user_id=user_id, | ||
| ) | ||
| raise AccountHasResourcesError(_ACCOUNT_HAS_RESOURCES_MSG) from exc | ||
|
igennova marked this conversation as resolved.
|
||
|
|
||
|
igennova marked this conversation as resolved.
|
||
| logger.info("User account {user_id} was removed.", user_id=user_id) | ||
| return Response(status_code=204) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| """Tests for DELETE /users/{user_id} (Phase 1: no resources, self or admin).""" | ||
|
|
||
| import uuid | ||
| from collections.abc import AsyncGenerator | ||
| from http import HTTPStatus | ||
| from typing import NamedTuple | ||
|
|
||
| import httpx | ||
| import pytest | ||
| import pytest_mock | ||
| from sqlalchemy import text | ||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| from core.errors import AccountHasResourcesError, ForbiddenError, UserNotFoundError | ||
| from database.users import UserGroup | ||
| from routers.openml.users import delete_user_account | ||
| from tests.users import ADMIN_USER, SOME_USER, ApiKey | ||
|
|
||
|
|
||
| async def test_delete_user_missing_auth(py_api: httpx.AsyncClient) -> None: | ||
| response = await py_api.delete("/users/1") | ||
| assert response.status_code == HTTPStatus.UNAUTHORIZED | ||
| body = response.json() | ||
| assert body["code"] == "103" | ||
| assert body["detail"] == "No API key provided." | ||
|
|
||
|
|
||
| class DisposableUser(NamedTuple): | ||
| user_id: int | ||
| api_key: str | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| async def disposable_user(user_test: AsyncConnection) -> AsyncGenerator[DisposableUser]: | ||
| api_key = uuid.uuid4().hex | ||
| suffix = uuid.uuid4().hex[:10] | ||
| username = f"tmp_user_{suffix}" | ||
| email = f"{suffix}@openml-delete.test" | ||
|
|
||
| await user_test.execute( | ||
| text( | ||
| """ | ||
| INSERT INTO users ( | ||
| ip_address, username, password, email, created_on, | ||
| company, country, bio, session_hash | ||
| ) VALUES ( | ||
| '127.0.0.1', :username, 'x', :email, UNIX_TIMESTAMP(), | ||
| '', '', '', :api_key | ||
| ) | ||
| """, | ||
| ), | ||
| parameters={"username": username, "email": email, "api_key": api_key}, | ||
| ) | ||
| uid_row = await user_test.execute(text("SELECT LAST_INSERT_ID() AS id")) | ||
| (new_id,) = uid_row.one() | ||
| await user_test.execute( | ||
| text("INSERT INTO users_groups (user_id, group_id) VALUES (:uid, :gid)"), | ||
| parameters={"uid": new_id, "gid": UserGroup.READ_WRITE.value}, | ||
| ) | ||
| yield DisposableUser(user_id=new_id, api_key=api_key) | ||
| await user_test.execute( | ||
| text("DELETE FROM users_groups WHERE user_id = :uid"), | ||
| parameters={"uid": new_id}, | ||
| ) | ||
| await user_test.execute( | ||
| text("DELETE FROM users WHERE id = :uid"), | ||
| parameters={"uid": new_id}, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.mut | ||
| async def test_delete_user_api_success_self_delete( | ||
| py_api: httpx.AsyncClient, | ||
| user_test: AsyncConnection, | ||
| disposable_user: DisposableUser, | ||
| ) -> None: | ||
| response = await py_api.delete( | ||
| f"/users/{disposable_user.user_id}", | ||
| params={"api_key": disposable_user.api_key}, | ||
| ) | ||
| assert response.status_code == HTTPStatus.NO_CONTENT | ||
| assert response.content == b"" | ||
|
|
||
| exists = await user_test.execute( | ||
| text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), | ||
| parameters={"id": disposable_user.user_id}, | ||
| ) | ||
| assert exists.one_or_none() is None | ||
|
|
||
|
|
||
| @pytest.mark.mut | ||
| async def test_delete_user_api_success_admin_deletes_disposable_user( | ||
| py_api: httpx.AsyncClient, | ||
| user_test: AsyncConnection, | ||
| disposable_user: DisposableUser, | ||
| ) -> None: | ||
| response = await py_api.delete( | ||
| f"/users/{disposable_user.user_id}", | ||
| params={"api_key": ApiKey.ADMIN}, | ||
| ) | ||
| assert response.status_code == HTTPStatus.NO_CONTENT | ||
| assert response.content == b"" | ||
|
|
||
| exists = await user_test.execute( | ||
| text("SELECT 1 FROM users WHERE id = :id LIMIT 1"), | ||
| parameters={"id": disposable_user.user_id}, | ||
| ) | ||
| assert exists.one_or_none() is None | ||
|
|
||
|
|
||
| # ── Direct handler tests ── | ||
|
|
||
|
|
||
| async def test_delete_user_direct_not_found( | ||
| user_test: AsyncConnection, | ||
| expdb_test: AsyncConnection, | ||
| ) -> None: | ||
| with pytest.raises(UserNotFoundError, match=r"User 888888888 not found\.") as exc_info: | ||
| await delete_user_account( | ||
| user_id=888888888, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
| assert exc_info.value.status_code == HTTPStatus.NOT_FOUND | ||
| assert exc_info.value.uri == UserNotFoundError.uri | ||
|
|
||
|
|
||
| async def test_delete_user_direct_forbidden( | ||
| user_test: AsyncConnection, | ||
| expdb_test: AsyncConnection, | ||
| ) -> None: | ||
| with pytest.raises( | ||
| ForbiddenError, match=r"You may only delete your own user account\." | ||
| ) as exc_info: | ||
| await delete_user_account( | ||
| user_id=ADMIN_USER.user_id, | ||
| current_user=SOME_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
| assert exc_info.value.status_code == HTTPStatus.FORBIDDEN | ||
| assert exc_info.value.uri == ForbiddenError.uri | ||
|
|
||
|
|
||
| async def test_delete_user_direct_conflict_has_resources( | ||
| user_test: AsyncConnection, | ||
| expdb_test: AsyncConnection, | ||
| ) -> None: | ||
| with pytest.raises(AccountHasResourcesError, match="Cannot delete this account") as exc_info: | ||
| await delete_user_account( | ||
| user_id=16, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
| assert exc_info.value.status_code == HTTPStatus.CONFLICT | ||
| assert exc_info.value.uri == AccountHasResourcesError.uri | ||
|
|
||
|
|
||
| @pytest.mark.mut | ||
| async def test_delete_user_direct_success_logs_info( | ||
| user_test: AsyncConnection, | ||
| expdb_test: AsyncConnection, | ||
| disposable_user: DisposableUser, | ||
| mocker: pytest_mock.MockerFixture, | ||
| ) -> None: | ||
| log_info = mocker.patch("routers.openml.users.logger.info") | ||
|
|
||
| response = await delete_user_account( | ||
| user_id=disposable_user.user_id, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
|
|
||
| assert response.status_code == HTTPStatus.NO_CONTENT | ||
| log_info.assert_called_once_with( | ||
| "User account {user_id} was removed.", | ||
| user_id=disposable_user.user_id, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.mut | ||
| async def test_delete_user_integrity_error_logs_and_raises_conflict( | ||
| user_test: AsyncConnection, | ||
| expdb_test: AsyncConnection, | ||
| disposable_user: DisposableUser, | ||
| mocker: pytest_mock.MockerFixture, | ||
| ) -> None: | ||
| mocker.patch( | ||
| "database.users.delete_user_rows", | ||
| side_effect=IntegrityError( | ||
| "DELETE FROM users", {"user_id": disposable_user.user_id}, Exception("fk") | ||
| ), | ||
| ) | ||
| log_error = mocker.patch("routers.openml.users.logger.error") | ||
|
|
||
| with pytest.raises(AccountHasResourcesError, match="Cannot delete this account") as exc_info: | ||
| await delete_user_account( | ||
| user_id=disposable_user.user_id, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
|
|
||
| assert exc_info.value.status_code == HTTPStatus.CONFLICT | ||
| log_error.assert_called_once_with( | ||
| "Delete of user {user_id} failed with integrity error after pre-check.", | ||
| user_id=disposable_user.user_id, | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.