-
-
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
885399d
Add DELETE /users/{id} with no-resources rule
e3b016d
query update
96f3122
suggested changes
0b615b9
Refine user deletion tests and logging
9d29e6b
Ignore TC002 (false positive on FastAPI Annotated[] / fixtures)
0e580c5
Merge remote-tracking branch 'upstream/main' into issue/194
a940c43
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ee84cb5
Use per-line TC002 noqa instead of global ignore
f74f16a
Merge branch 'issue/194' of https://github.com/igennova/server-api in…
168f550
Restore TC002 noqa stripped by pre-commit.ci autofix
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
Some comments aren't visible on the classic Files Changed page.
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,61 @@ | ||
| """User account HTTP endpoints.""" | ||
|
|
||
| from typing import Annotated | ||
|
|
||
| from fastapi import APIRouter, Depends, Path, Response | ||
| 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."}, | ||
|
igennova marked this conversation as resolved.
Outdated
|
||
| }, | ||
| ) | ||
| 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 a user account when they have no uploaded resources (Phase 1). | ||
|
|
||
| Callers may delete their own account. Administrators may delete any account | ||
| that satisfies the no-resources rule. | ||
|
igennova marked this conversation as resolved.
Outdated
igennova marked this conversation as resolved.
Outdated
|
||
| """ | ||
|
igennova marked this conversation as resolved.
|
||
| 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: | ||
| # Safety net: a user-reference table was added without updating | ||
| # ``has_user_references``. Surface a clean 409 instead of a 500. | ||
| raise AccountHasResourcesError(_ACCOUNT_HAS_RESOURCES_MSG) from exc | ||
|
igennova marked this conversation as resolved.
igennova marked this conversation as resolved.
|
||
|
|
||
|
igennova marked this conversation as resolved.
|
||
| return Response(status_code=204) | ||
|
igennova marked this conversation as resolved.
Outdated
|
||
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,192 @@ | ||
| """Tests for DELETE /users/{user_id} (Phase 1: no resources, self or admin).""" | ||
|
igennova marked this conversation as resolved.
Outdated
|
||
|
|
||
| import uuid | ||
| from http import HTTPStatus | ||
|
|
||
| import httpx | ||
| import pytest | ||
| from sqlalchemy import text | ||
| 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." | ||
|
|
||
|
|
||
| async def test_delete_user_not_found(py_api: httpx.AsyncClient) -> None: | ||
| response = await py_api.delete( | ||
| "/users/999999999", | ||
| params={"api_key": ApiKey.ADMIN}, | ||
| ) | ||
| assert response.status_code == HTTPStatus.NOT_FOUND | ||
| assert response.headers["content-type"] == "application/problem+json" | ||
| body = response.json() | ||
| assert body["type"] == UserNotFoundError.uri | ||
| assert body["detail"] == "User 999999999 not found." | ||
|
|
||
|
|
||
| async def test_delete_user_forbidden_non_admin_deletes_other( | ||
| py_api: httpx.AsyncClient, | ||
| ) -> None: | ||
| response = await py_api.delete( | ||
| f"/users/{ADMIN_USER.user_id}", | ||
| params={"api_key": ApiKey.SOME_USER}, | ||
| ) | ||
| assert response.status_code == HTTPStatus.FORBIDDEN | ||
| body = response.json() | ||
| assert body["type"] == ForbiddenError.uri | ||
| assert body["detail"] == "You may only delete your own user account." | ||
|
|
||
|
|
||
| async def test_delete_user_conflict_when_user_has_resources( | ||
| py_api: httpx.AsyncClient, | ||
| ) -> None: | ||
| """User 16 owns dataset 130 in the test database.""" | ||
| response = await py_api.delete( | ||
| "/users/16", | ||
| params={"api_key": ApiKey.ADMIN}, | ||
| ) | ||
| assert response.status_code == HTTPStatus.CONFLICT | ||
| assert response.headers["content-type"] == "application/problem+json" | ||
| body = response.json() | ||
| assert body["type"] == AccountHasResourcesError.uri | ||
| assert "datasets" in body["detail"] | ||
|
igennova marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| @pytest.mark.mut | ||
| async def test_delete_user_api_success_self_delete( | ||
| py_api: httpx.AsyncClient, | ||
| user_test: AsyncConnection, | ||
| ) -> None: | ||
| """Disposable user deletes their own account using their API key (session_hash).""" | ||
| api_key = "fedcba9876543210fedcba9876543210" | ||
|
igennova marked this conversation as resolved.
Outdated
|
||
| suffix = uuid.uuid4().hex[:10] | ||
| username = f"tmp_self_{suffix}" | ||
| email = f"{suffix}@openml-self-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}, | ||
| ) | ||
|
|
||
| response = await py_api.delete( | ||
| f"/users/{new_id}", | ||
| params={"api_key": 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": new_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, | ||
| ) -> None: | ||
| suffix = uuid.uuid4().hex[:12] | ||
| username = f"tmp_del_{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 | ||
| ) VALUES ( | ||
| '127.0.0.1', :username, 'x', :email, UNIX_TIMESTAMP(), | ||
| '', '', '' | ||
| ) | ||
| """, | ||
| ), | ||
| parameters={"username": username, "email": email}, | ||
| ) | ||
| 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}, | ||
| ) | ||
|
|
||
| response = await py_api.delete( | ||
| f"/users/{new_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": new_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\."): | ||
| await delete_user_account( | ||
| user_id=888888888, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
|
|
||
|
|
||
| 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\."): | ||
| await delete_user_account( | ||
| user_id=ADMIN_USER.user_id, | ||
| current_user=SOME_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
|
|
||
|
|
||
| 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"): | ||
| await delete_user_account( | ||
| user_id=16, | ||
| current_user=ADMIN_USER, | ||
| expdb=expdb_test, | ||
| userdb=user_test, | ||
| ) | ||
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.