"""管理员删除账号必须清理全部自有数据,并等待执行与上传停止。""" import asyncio import io import os from pathlib import Path from tempfile import TemporaryDirectory import httpx import pytest from sqlalchemy import select from starlette.datastructures import UploadFile from app.core.security import Actor from app.models import ( ApiToken, Asset, AssetFolder, AssetReference, AssetTag, Base, Batch, BatchItem, Event, Execution, Folder, Job, JobAsset, QuotaReservation, Session, SharedAsset, ShotCandidate, ShotSelection, Submission, User, WorkflowDraft, WorkflowRun, WorkflowStep, ) from conftest import PASSWORD @pytest.fixture def tmp_path(): # 本模块覆盖pytest默认保留目录,隔离DB/媒体/锁文件在fixture退出时立即清理。 with TemporaryDirectory(prefix="cmvr-user-deletion-") as directory: yield Path(directory) async def account(client): return (await client.get("/api/auth/me")).json()["user"] async def upload(client, png_bytes): response = await client.post( "/api/assets", files={"file": ("picture.png", png_bytes, "image/png")} ) assert response.status_code == 201, response.text return response.json() async def test_delete_user_requires_admin_session_csrf_and_forbids_self(system, other_client): target = await account(other_client) url = f"/api/auth/users/{target['id']}" assert (await other_client.delete(url)).status_code == 403 assert (await system.client.delete(url, headers={"X-CSRF-Token": "wrong"})).status_code == 403 own = await account(system.client) denied = await system.client.delete(f"/api/auth/users/{own['id']}") assert denied.status_code == 409, denied.text assert (await system.client.delete("/api/auth/users/missing")).status_code == 404 async def test_delete_user_removes_complete_tree_and_preserves_other_import( system, other_client, png_bytes ): target = await account(other_client) admin = await account(system.client) owner = target["id"] source = await upload(other_client, png_bytes) shared = (await other_client.post(f"/api/assets/{source['id']}/publish")).json() imported = await system.client.post(f"/api/shared-assets/{shared['id']}/import") assert imported.status_code == 201, imported.text imported_id = imported.json()["id"] token = await other_client.post( "/api/auth/tokens", json={"name": "machine", "scopes": ["jobs:read"]} ) assert token.status_code == 201, token.text token_value = token.json()["token"] async with system.app.state.db.session() as session: folder = Folder(owner_id=owner, name="root") session.add(folder) await session.flush() child = Folder(owner_id=owner, name="child", parent_id=folder.id, parent_key=folder.id) draft = WorkflowDraft(owner_id=owner, name="story", kind="story_v3", spec={}) batch = Batch(owner_id=owner, name="batch", state="succeeded") session.add_all([child, draft, batch]) await session.flush() run = WorkflowRun( owner_id=owner, draft_id=draft.id, draft_revision=1, spec_hash="hash", state="succeeded", batch_id=batch.id, ) session.add(run) await session.flush() job = Job( owner_id=owner, task_type="image.generate", state="succeeded", phase="done", input_json={}, parameters={}, request_hash="hash", upstream_key="tree-job", run_id=run.id, batch_id=batch.id, folder_id=child.id, ) session.add(job) await session.flush() job_id = job.id source_row = await session.get(Asset, source["id"]) source_row.source_job_id = job.id session.add_all( [ AssetFolder(asset_id=source_row.id, folder_id=child.id), JobAsset(job_id=job.id, asset_id=source_row.id), AssetTag(owner_id=owner, asset_id=source_row.id, tag="mine"), AssetReference( owner_id=owner, asset_id=source_row.id, ref_kind="draft", ref_id=draft.id ), WorkflowStep( run_id=run.id, step_key="shot", kind="image.generate", semantic_input_hash="hash", selected_job_id=job.id, ), BatchItem(batch_id=batch.id, item_index=0, target_kind="run", target_id=run.id), Execution( job_id=job.id, ordinal=1, phase_key="execute", resource_pool="cpu_media", fence_token="fence", state="exited", ), ShotCandidate( owner_id=owner, draft_id=draft.id, shot_id="s1", kind="image", source_kind="generated", job_id=job.id, asset_id=source_row.id, context_hash="hash", generation_hash="hash", created_revision=1, ), ShotSelection( owner_id=owner, draft_id=draft.id, shot_id="s1", kind="image", asset_id=source_row.id, context_hash="hash", ), Submission(owner_id=owner, operation="story.render", key="key", body_hash="hash"), QuotaReservation(owner_id=owner, operation="story.render"), Event(owner_id=owner, event_type="test", data={}), ] ) imported_row = await session.get(Asset, imported_id) preserved = system.settings.asset_root / imported_row.storage_key await session.commit() work = system.settings.job_work_root / job_id / "attempt-0001" work.mkdir(parents=True) (work / "output.bin").write_bytes(b"output") # 中断上传或已软删素材遗留的字节也只能在本账号目录内清理。 leftover = system.settings.asset_root / owner / "orphan" / "upload.part" leftover.parent.mkdir(parents=True) leftover.write_bytes(b"partial") response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 204, response.text assert not (system.settings.asset_root / owner).exists() assert not (system.settings.job_work_root / job_id).exists() assert preserved.read_bytes() == png_bytes assert (await other_client.get("/api/auth/me")).status_code == 401 assert ( await other_client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) ).status_code == 401 assert (await system.client.get(imported.json()["preview_url"])).content == png_bytes assert (await system.client.get(shared["preview_url"])).status_code == 404 async with httpx.AsyncClient( transport=httpx.ASGITransport(app=system.app), base_url="http://test" ) as machine: assert ( await machine.get("/api/jobs", headers={"Authorization": "Bearer " + token_value}) ).status_code == 401 async with system.app.state.db.session() as session: assert await session.get(User, owner) is None assert await session.get(User, admin["id"]) is not None assert await session.get(Asset, imported_id) is not None for table in Base.metadata.tables.values(): field = table.c.get("owner_id") if field is None: field = table.c.get("publisher_id") if field is None: field = table.c.get("user_id") if field is not None: assert ( await session.execute(select(table).where(field == owner)) ).first() is None, table.name for model in (JobAsset, AssetFolder, WorkflowStep, BatchItem, Execution): assert await session.scalar(select(model)) is None @pytest.mark.parametrize("state", ["allocated", "running", "stopping", "unknown", "future"]) async def test_delete_waits_for_execution_cleanup(system, other_client, png_bytes, state): owner = (await account(other_client))["id"] asset = await upload(other_client, png_bytes) response = await other_client.post( "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} ) job_id = response.json()["jobs"][0]["id"] async with system.app.state.db.session() as session: (await session.get(Job, job_id)).state = "cancelled" execution = Execution( job_id=job_id, ordinal=1, phase_key="execute", resource_pool="cpu_media", fence_token="fence", state=state, ) session.add(execution) await session.commit() execution_id = execution.id path = system.settings.asset_root / owner response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "cleanup_pending" assert path.exists() assert (await other_client.get("/api/auth/me")).status_code == 401 async with system.app.state.db.session() as session: assert (await session.get(User, owner)).disabled assert await session.get(Asset, asset["id"]) is not None assert await session.scalar(select(Session).where(Session.user_id == owner)) is None (await session.get(Execution, execution_id)).state = "exited" await session.commit() assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 async def test_delete_persists_cancellation_before_removing_active_gpu_files( system, other_client, png_bytes ): owner = (await account(other_client))["id"] await upload(other_client, png_bytes) response = await other_client.post( "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} ) job_id = response.json()["jobs"][0]["id"] await system.app.state.coordinator.run_once(force=True) preparing = list(system.app.state.coordinator._preparing.values()) if preparing: await asyncio.gather(*preparing) await system.app.state.coordinator.run_once(force=True) response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "cleanup_pending" assert (system.settings.asset_root / owner).exists() async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert job.cancel_requested and job.desired_state == "cancel" await system.app.state.coordinator.run_once(force=True) assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 async def test_delete_preflights_all_paths_before_unlinking(system, other_client, png_bytes): owner = (await account(other_client))["id"] good = await upload(other_client, png_bytes) bad = await upload(other_client, png_bytes) other = await upload(system.client, png_bytes) async with system.app.state.db.session() as session: good_path = system.settings.asset_root / (await session.get(Asset, good["id"])).storage_key other_path = ( system.settings.asset_root / (await session.get(Asset, other["id"])).storage_key ) (await session.get(Asset, bad["id"])).storage_key = ( other_path.relative_to(system.settings.asset_root).as_posix() + ".unsafe" ) await session.commit() response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "unsafe_user_path" assert good_path.exists() and other_path.read_bytes() == png_bytes async def test_delete_waits_for_inflight_upload_and_prevents_new_upload( system, other_client, png_bytes, monkeypatch ): from app.services import assets owner = (await account(other_client))["id"] user = await account(other_client) actor = Actor(owner, user["username"], user["display_name"], "user", "", "") started, release = asyncio.Event(), asyncio.Event() real_build = assets.build_asset async def paused_build(*args, **kwargs): started.set() await release.wait() return await real_build(*args, **kwargs) monkeypatch.setattr(assets, "build_asset", paused_build) task = asyncio.create_task( assets.upload( runtime=system.app.state, file=UploadFile(io.BytesIO(png_bytes), filename="picture.png"), actor=actor, ) ) try: await asyncio.wait_for(started.wait(), timeout=5) response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "cleanup_pending" finally: release.set() outcome = await asyncio.gather(task, return_exceptions=True) assert isinstance(outcome[0], Exception), "禁用后的在途上传不可提交新素材" assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 assert not (system.settings.asset_root / owner).exists() async def test_delete_filesystem_failure_retains_rows_for_retry( system, other_client, png_bytes, monkeypatch ): owner = (await account(other_client))["id"] asset = await upload(other_client, png_bytes) real_unlink = Path.unlink def fail_unlink(path, *args, **kwargs): if owner in path.parts: raise PermissionError("busy file") return real_unlink(path, *args, **kwargs) with monkeypatch.context() as patch: patch.setattr(Path, "unlink", fail_unlink) response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 503, response.text async with system.app.state.db.session() as session: assert await session.get(User, owner) is not None assert await session.get(Asset, asset["id"]) is not None assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 async def test_delete_waits_for_execution_reference_not_owned_job(system, other_client, png_bytes): owner = (await account(other_client))["id"] asset = await upload(other_client, png_bytes) async with system.app.state.db.session() as session: execution = Execution( job_id="foreign-job", ordinal=1, phase_key="execute", resource_pool="cpu_media", fence_token="fence", state="running", ) session.add(execution) await session.flush() session.add( AssetReference( owner_id=owner, asset_id=asset["id"], ref_kind="execution", ref_id=execution.id ) ) await session.commit() response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "cleanup_pending" assert (system.settings.asset_root / owner).is_dir() async def test_delete_waits_for_background_writer_after_job_terminal( system, other_client, png_bytes ): owner = (await account(other_client))["id"] await upload(other_client, png_bytes) response = await other_client.post( "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} ) job_id = response.json()["jobs"][0]["id"] async with system.app.state.db.session() as session: (await session.get(Job, job_id)).state = "succeeded" await session.commit() release = asyncio.Event() writer = asyncio.create_task(release.wait()) system.app.state.coordinator._collecting[job_id] = writer try: response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "cleanup_pending" assert (system.settings.asset_root / owner).is_dir() finally: release.set() await writer assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 async def test_delete_refuses_link_inside_user_tree(system, other_client, png_bytes, tmp_path): owner = (await account(other_client))["id"] await upload(other_client, png_bytes) external = tmp_path / "other-account-secret" external.mkdir() (external / "keep.bin").write_bytes(b"keep") link = system.settings.asset_root / owner / "linked" try: os.symlink(external, link, target_is_directory=True) except OSError as exc: pytest.skip(f"OS does not permit test symlink: {exc}") try: response = await system.client.delete(f"/api/auth/users/{owner}") assert response.status_code == 409, response.text assert response.json()["detail"]["code"] == "unsafe_user_path" assert (external / "keep.bin").read_bytes() == b"keep" finally: link.unlink()