cmvr-visual/backend/tests/test_user_status.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

182 lines
7.9 KiB
Python

import httpx
from pathlib import Path
from tempfile import TemporaryDirectory
import pytest
from sqlalchemy import delete
from conftest import PASSWORD
from app.models import Batch, Job, Session, User, WorkflowDraft, WorkflowRun
from app.services.events import session_is_active
@pytest.fixture
def tmp_path():
with TemporaryDirectory(prefix="cmvr-user-status-") as directory:
yield Path(directory)
async def test_disable_and_enable_preserve_resources_and_remove_only_admin_holds(
system, other_client, png_bytes
):
owner = (await other_client.get("/api/auth/me")).json()["user"]["id"]
cookie = other_client.cookies.get("cmvr_session")
asset = (
await other_client.post(
"/api/assets", files={"file": ("owned.png", png_bytes, "image/png")}
)
).json()
token = (
await other_client.post(
"/api/auth/tokens", json={"name": "existing reader", "scopes": ["assets:read"]}
)
).json()["token"]
jobs = (
await other_client.post(
"/api/jobs",
json={"task_type": "image.generate", "input": {"prompt": "preserve"}, "count": 2},
)
).json()["jobs"]
async with system.app.state.db.session() as session:
draft = WorkflowDraft(owner_id=owner, name="preserve draft", spec={"shots": []})
session.add(draft)
await session.flush()
run = WorkflowRun(
owner_id=owner,
draft_id=draft.id,
draft_revision=1,
spec_snapshot={"shots": []},
spec_hash="hash",
hold_reasons=["manual"],
)
batch = Batch(owner_id=owner, name="preserve batch", hold_reasons=["batch_pause"])
session.add_all([run, batch])
(await session.get(Job, jobs[0]["id"])).hold_reasons = ["manual"]
await session.commit()
run_id, batch_id = run.id, batch.id
response = await system.client.patch("/api/auth/users/" + owner, json={"disabled": True})
assert response.status_code == 200
assert not await session_is_active(system.app.state.db, cookie)
assert not await session_is_active(system.app.state.db, "Bearer " + token)
assert (await other_client.get("/api/assets")).status_code == 401
assert (await other_client.post("/api/jobs", json={})).status_code == 401
assert (
await other_client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD})
).status_code == 401
async with system.app.state.db.session() as session:
assert "admin_suspend" in (await session.get(Job, jobs[0]["id"])).hold_reasons
assert "admin_suspend" in (await session.get(WorkflowRun, run_id)).hold_reasons
assert "admin_suspend" in (await session.get(Batch, batch_id)).hold_reasons
assert (
await system.client.patch("/api/auth/users/" + owner, json={"disabled": False})
).status_code == 200
# 旧 Cookie 保持失效;已有机器令牌随账号启用恢复,资源不需要重建。
assert (await other_client.get("/api/auth/me")).status_code == 401
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=system.app),
base_url="http://test",
headers={"Authorization": "Bearer " + token},
) as machine:
assert (await machine.get("/api/assets")).status_code == 200
login = await other_client.post(
"/api/auth/login", json={"username": "alice", "password": PASSWORD}
)
assert login.status_code == 200
assert (await other_client.get(asset["preview_url"])).status_code == 200
assert asset["id"] in [a["id"] for a in (await other_client.get("/api/assets")).json()["items"]]
async with system.app.state.db.session() as session:
assert (await session.get(Job, jobs[0]["id"])).hold_reasons == ["manual"]
assert (await session.get(Job, jobs[1]["id"])).hold_reasons == []
assert (await session.get(WorkflowRun, run_id)).hold_reasons == ["manual"]
assert (await session.get(Batch, batch_id)).hold_reasons == ["batch_pause"]
async def test_reenabled_unheld_cpu_task_can_continue(system, other_client):
owner = (await other_client.get("/api/auth/me")).json()["user"]["id"]
created = await other_client.post(
"/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "resume"}}
)
assert created.status_code == 202
jid = created.json()["jobs"][0]["id"]
await system.client.patch("/api/auth/users/" + owner, json={"disabled": True})
await system.app.state.coordinator.run_once(force=True)
assert system.provider.cpu_runs == 0
await system.client.patch("/api/auth/users/" + owner, json={"disabled": False})
import asyncio
for _ in range(4):
await system.app.state.coordinator.run_once(force=True)
pending = list(system.app.state.coordinator._cpu.values())
if pending:
await asyncio.gather(*pending)
assert system.provider.cpu_runs == 1
async with system.app.state.db.session() as session:
assert (await session.get(Job, jid)).state == "succeeded"
async def test_admin_cannot_disable_their_own_account_even_with_another_admin(system):
admin = (await system.client.get("/api/auth/me")).json()["user"]["id"]
async with system.app.state.db.session() as session:
first = await session.get(User, admin)
session.add(
User(
username="backup-admin",
display_name="Backup",
role="admin",
password_hash=first.password_hash,
)
)
await session.commit()
response = await system.client.patch("/api/auth/users/" + admin, json={"disabled": True})
assert response.status_code == 409
assert (await system.client.get("/api/auth/me")).status_code == 200
async def test_stale_authenticated_admin_cannot_reenable_or_create_users(system, other_client):
from app.api.dependencies import current_actor
from app.core.security import Actor, token_hash
me = (await system.client.get("/api/auth/me")).json()["user"]
target = (await other_client.get("/api/auth/me")).json()["user"]["id"]
actor = Actor(
me["id"],
me["username"],
me["display_name"],
"admin",
system.client.headers["X-CSRF-Token"],
token_hash(system.client.cookies.get("cmvr_session")),
)
async with system.app.state.db.session() as session:
admin = await session.get(User, actor.id)
admin.disabled = True
await session.execute(delete(Session).where(Session.user_id == actor.id))
await session.commit()
# 模拟鉴权已完成、业务事务尚未开始时,管理员被另一请求停用。
system.app.dependency_overrides[current_actor] = lambda: actor
try:
assert (
await system.client.patch("/api/auth/users/" + actor.id, json={"disabled": False})
).status_code in {401, 403}
assert (
await system.client.post(
"/api/auth/users", json={"username": "stale-admin-created", "password": PASSWORD}
)
).status_code in {401, 403}
assert (await system.client.get("/api/auth/users")).status_code in {401, 403}
assert (await system.client.delete("/api/auth/users/" + target)).status_code in {401, 403}
async with system.app.state.db.session() as session:
assert (await session.get(User, actor.id)).disabled
# 即使稍后重新启用,旧的已撤销会话也不能恢复操作。
(await session.get(User, actor.id)).disabled = False
await session.commit()
assert (
await system.client.patch("/api/auth/users/" + target, json={"disabled": True})
).status_code in {401, 403}
assert (
await system.client.post(
"/api/auth/password",
json={"current_password": PASSWORD, "new_password": PASSWORD + "-new"},
)
).status_code in {401, 403}
finally:
system.app.dependency_overrides.clear()