from __future__ import annotations import json import uuid from datetime import timedelta from app.config import get_settings from app.database import SessionLocal from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess from app.security import hash_password from app.services.bootstrap_service import ensure_defaults from app.time_utils import utc_now def _token(client, username: str = "admin", password: str = "admin123456"): response = client.post("/api/auth/login", json={"username": username, "password": password}) return response.json()["access_token"] def _headers(client, username: str = "admin", password: str = "admin123456"): return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"} def _create_user(*, username: str, password: str, role: str = "user", full_name: str = "User") -> int: db = SessionLocal() try: user = User( username=username, full_name=full_name, password_hash=hash_password(password), role=role, is_active=True, primary_department_id=1, ) db.add(user) db.commit() db.refresh(user) return user.id finally: db.close() def _create_group(*, name: str) -> int: db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None group = Group(name=name, created_by_id=admin.id, department_id=1) db.add(group) db.commit() db.refresh(group) return group.id finally: db.close() def _create_department(*, name: str, description: str = "test department") -> int: db = SessionLocal() try: department = Department(name=name, description=description) db.add(department) db.commit() db.refresh(department) return department.id finally: db.close() def _create_stale_syncing_document() -> tuple[int, str]: db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin_id = admin.id group = Group(name=f"health-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title="stale-health", created_by_id=admin_id, is_deleted=False) db.add(document) db.commit() db.refresh(document) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="stale.docx", source_ext=".docx", source_path="/tmp/stale.docx", source_sha256=uuid.uuid4().hex, file_size=128, uploader_id=admin_id, convert_status="success", sync_status="syncing", ) db.add(version) db.commit() db.refresh(version) old_time = utc_now() - timedelta(minutes=20) job = Job( id=str(uuid.uuid4()), job_type="sync", status="running", group_id=group.id, document_id=document.id, version_id=version.id, created_by_id=admin_id, created_at=old_time, started_at=old_time, ) db.add(job) db.commit() record = DifySyncRecord( version_id=version.id, dataset_id="dataset-health", remote_document_id="remote-health", batch="batch-health", status="syncing", created_at=old_time, updated_at=old_time, ) db.add(record) db.commit() return version.id, job.id finally: db.close() def _create_stale_convert_document() -> tuple[int, str]: db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin_id = admin.id group = Group(name=f"convert-health-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title="convert-stale-health", created_by_id=admin_id, is_deleted=False) db.add(document) db.commit() db.refresh(document) old_time = utc_now() - timedelta(minutes=20) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="convert-stale.docx", source_ext=".docx", source_path="/tmp/convert-stale.docx", source_sha256=uuid.uuid4().hex, file_size=128, uploader_id=admin_id, convert_status="queued", sync_status="unsynced", uploaded_at=old_time, ) db.add(version) db.commit() db.refresh(version) job = Job( id=str(uuid.uuid4()), job_type="convert", status="queued", queue_job_id="missing-convert-job", group_id=group.id, document_id=document.id, version_id=version.id, created_by_id=admin_id, created_at=old_time, ) db.add(job) db.commit() return version.id, job.id finally: db.close() def test_admin_can_create_and_update_users(client): group_id = _create_group(name=f"access-{uuid.uuid4().hex[:8]}") create_response = client.post( "/api/admin/users", json={ "username": "operator", "password": "operator123", "full_name": "Ops User", "role": "user", "primary_department_id": 1, "accessible_department_ids": [1], }, headers=_headers(client), ) assert create_response.status_code == 200 assert create_response.json()["username"] == "operator" assert create_response.json()["accessible_department_ids"] == [1] db = SessionLocal() try: user = db.query(User).filter(User.username == "operator").first() assert user is not None user_id = user.id finally: db.close() update_response = client.patch( f"/api/admin/users/{user_id}", json={ "full_name": "Operations User", "role": "admin", "is_active": False, "primary_department_id": 1, "accessible_department_ids": [1], }, headers=_headers(client), ) assert update_response.status_code == 200 body = update_response.json() assert body["full_name"] == "Operations User" assert body["role"] == "admin" assert body["is_active"] is False assert body["accessible_department_ids"] == [1] def test_admin_can_delete_user_and_clear_created_by_references(client): user_id = _create_user(username=f"delete-user-{uuid.uuid4().hex[:8]}", password="delete123", role="user", full_name="Delete User") db = SessionLocal() try: user = db.query(User).filter(User.id == user_id).first() admin = db.query(User).filter(User.username == "admin").first() assert user is not None assert admin is not None group = Group(name=f"delete-user-group-{uuid.uuid4().hex[:8]}", created_by_id=user_id, department_id=1) db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title=f"delete-user-doc-{uuid.uuid4().hex[:8]}", created_by_id=user_id, is_deleted=False) db.add(document) db.commit() db.refresh(document) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="delete-user.docx", source_ext=".docx", source_path="/tmp/delete-user.docx", source_sha256=uuid.uuid4().hex, file_size=128, uploader_id=user_id, convert_status="success", sync_status="unsynced", ) db.add(version) db.add(Job(id=str(uuid.uuid4()), job_type="convert", status="success", created_by_id=user_id, document_id=document.id, version_id=version.id)) db.commit() group_id = group.id document_id = document.id version_id = version.id finally: db.close() response = client.delete(f"/api/admin/users/{user_id}", headers=_headers(client)) assert response.status_code == 200 assert response.json()["deleted_user_id"] == user_id db = SessionLocal() try: assert db.query(User).filter(User.id == user_id).first() is None group = db.query(Group).filter(Group.id == group_id).first() document = db.query(Document).filter(Document.id == document_id).first() version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() job = db.query(Job).filter(Job.document_id == document_id).first() assert group is not None and group.created_by_id is None assert document is not None and document.created_by_id is None assert version is not None and version.uploader_id is None assert job is not None and job.created_by_id is None finally: db.close() def test_admin_delete_protects_primary_super_admin_and_self(client): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin_id = admin.id finally: db.close() delete_admin = client.delete(f"/api/admin/users/{admin_id}", headers=_headers(client)) assert delete_admin.status_code == 400 assert "cannot be deleted" in delete_admin.json()["detail"] username = f"self-delete-{uuid.uuid4().hex[:8]}" user_id = _create_user(username=username, password="self123", role="admin", full_name="Self Delete") self_delete = client.delete( f"/api/admin/users/{user_id}", headers=_headers(client, username=username, password="self123"), ) assert self_delete.status_code == 400 assert "cannot delete your own account" in self_delete.json()["detail"].lower() def test_only_admin_can_hold_super_admin_role(client): create_response = client.post( "/api/admin/users", json={ "username": "other-super", "password": "operator123", "full_name": "Other Super", "role": "super_admin", "primary_department_id": 1, "accessible_department_ids": [], }, headers=_headers(client), ) assert create_response.status_code == 400 assert "Only admin can be a super admin" in create_response.json()["detail"] db = SessionLocal() try: admin_user = db.query(User).filter(User.username == "admin").first() operator = User( username="operator-promote", full_name="Operator Promote", password_hash=hash_password("operator123"), role="admin", is_active=True, primary_department_id=1, ) db.add(operator) db.commit() db.refresh(operator) assert admin_user is not None operator_id = operator.id admin_id = admin_user.id finally: db.close() promote_response = client.patch( f"/api/admin/users/{operator_id}", json={"role": "super_admin"}, headers=_headers(client), ) assert promote_response.status_code == 400 assert "Only admin can be a super admin" in promote_response.json()["detail"] demote_admin = client.patch( f"/api/admin/users/{admin_id}", json={"role": "admin"}, headers=_headers(client), ) assert demote_admin.status_code == 400 assert "admin must remain a super admin" in demote_admin.json()["detail"] def test_bootstrap_keeps_admin_as_unique_super_admin(): db = SessionLocal() try: rogue = User( username="legacy-super", full_name="Legacy Super", password_hash=hash_password("legacy123"), role="super_admin", is_active=True, primary_department_id=None, ) db.add(rogue) db.commit() ensure_defaults(db) admin = db.query(User).filter(User.username == "admin").first() legacy = db.query(User).filter(User.username == "legacy-super").first() adam = db.query(User).filter(User.username == "adam").first() assert admin is not None assert admin.role == "super_admin" assert legacy is not None assert legacy.role == "admin" assert legacy.primary_department_id is None assert adam is not None assert adam.role == "admin" finally: db.close() def test_admin_can_read_and_update_settings(client): initial = client.get("/api/admin/settings", headers=_headers(client)) assert initial.status_code == 200 assert initial.json()["search_method"] == "hybrid_search" updated = client.patch( "/api/admin/settings", json={ "search_method": "semantic_search", "top_k": 8, "score_threshold_enabled": False, "score_threshold": 0.4, "embedding_model_provider": "langgenius/siliconflow/siliconflow", "embedding_model": "Qwen/Qwen3-Embedding-8B", "reranking_model_provider": "langgenius/siliconflow/siliconflow", "reranking_model": "Qwen/Qwen3-Reranker-8B", }, headers=_headers(client), ) assert updated.status_code == 200 body = updated.json() assert body["search_method"] == "semantic_search" assert body["top_k"] == 8 assert body["score_threshold_enabled"] is False assert body["score_threshold"] == 0.4 assert body["embedding_model_provider"] == "langgenius/siliconflow/siliconflow" assert body["embedding_model"] == "Qwen/Qwen3-Embedding-8B" assert body["reranking_model_provider"] == "langgenius/siliconflow/siliconflow" assert body["reranking_model"] == "Qwen/Qwen3-Reranker-8B" def test_empty_department_can_be_deleted(client): department_id = _create_department(name=f"empty-dept-{uuid.uuid4().hex[:8]}") response = client.request( "DELETE", f"/api/admin/departments/{department_id}", headers=_headers(client), json={"target_department_id": None}, ) assert response.status_code == 200 assert response.json()["deleted_department_id"] == department_id db = SessionLocal() try: assert db.query(Department).filter(Department.id == department_id).first() is None finally: db.close() def test_department_delete_requires_migration_when_department_is_in_use(client): source_department_id = _create_department(name=f"source-dept-{uuid.uuid4().hex[:8]}") db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None group = Group(name=f"in-use-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id) db.add(group) db.commit() finally: db.close() response = client.request( "DELETE", f"/api/admin/departments/{source_department_id}", headers=_headers(client), json={"target_department_id": None}, ) assert response.status_code == 400 assert "Choose another department to migrate first" in response.json()["detail"] def test_department_delete_can_migrate_knowledge_bases_and_user_access(client): source_department_id = _create_department(name=f"source-migrate-{uuid.uuid4().hex[:8]}") target_department_id = _create_department(name=f"target-migrate-{uuid.uuid4().hex[:8]}") operator_id = _create_user(username=f"dept-user-{uuid.uuid4().hex[:8]}", password="operator123", role="user", full_name="Dept User") db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() operator = db.query(User).filter(User.id == operator_id).first() assert admin is not None assert operator is not None admin.primary_department_id = target_department_id operator.primary_department_id = source_department_id db.add(UserDepartmentAccess(user_id=admin.id, department_id=source_department_id)) group = Group(name=f"migrate-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id) db.add(group) db.commit() db.refresh(group) group_id = group.id admin_id = admin.id finally: db.close() response = client.request( "DELETE", f"/api/admin/departments/{source_department_id}", headers=_headers(client), json={"target_department_id": target_department_id}, ) assert response.status_code == 200 payload = response.json() assert payload["migrated_to_department_id"] == target_department_id assert payload["knowledge_base_count"] == 1 assert payload["primary_user_count"] == 1 assert payload["extra_user_count"] == 1 db = SessionLocal() try: assert db.query(Department).filter(Department.id == source_department_id).first() is None group = db.query(Group).filter(Group.id == group_id).first() operator = db.query(User).filter(User.id == operator_id).first() admin = db.query(User).filter(User.id == admin_id).first() assert group is not None assert operator is not None assert admin is not None assert group.department_id == target_department_id assert operator.primary_department_id == target_department_id assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == source_department_id).first() is None assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == target_department_id).first() is None finally: db.close() def test_admin_can_read_available_dify_models(client, monkeypatch): class FakeDifyService: def list_available_embedding_models(self): return [ type("Model", (), {"provider": "provider-a", "model": "embed-a", "label": "Provider A / embed-a"})() ] def list_available_rerank_models(self): return [ type("Model", (), {"provider": "provider-b", "model": "rerank-b", "label": "Provider B / rerank-b"})() ] def resolve_embedding_model_choice(self, *, provider=None, model=None): return ("provider-a", "embed-a") def resolve_rerank_model_choice(self, *, provider=None, model=None): return ("provider-b", "rerank-b") monkeypatch.setattr("app.api.admin.DifyService", FakeDifyService) response = client.get("/api/admin/dify-models", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["embedding_models"][0]["model"] == "embed-a" assert payload["rerank_models"][0]["model"] == "rerank-b" assert payload["automatic_defaults"] == { "embedding_model_provider": "provider-a", "embedding_model": "embed-a", "reranking_model_provider": "provider-b", "reranking_model": "rerank-b", } def test_admin_endpoints_require_admin_and_job_list_scopes_by_user(client): user_id = _create_user(username="viewer", password="viewer123", role="user", full_name="Viewer") admin_id = _create_user(username="ops-admin", password="ops123456", role="admin", full_name="Ops Admin") admin_headers = _headers(client) user_headers = _headers(client, username="viewer", password="viewer123") ops_headers = _headers(client, username="ops-admin", password="ops123456") db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None group = Group(name=f"ops-scope-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=1) db.add(group) db.commit() db.refresh(group) db.add(UserDepartmentAccess(user_id=admin_id, department_id=1)) db.add_all( [ Job( id=str(uuid.uuid4()), job_type="convert", status="success", created_by_id=admin.id, group_id=group.id, payload={"owner": "admin"}, ), Job( id=str(uuid.uuid4()), job_type="sync", status="queued", created_by_id=user_id, payload={"owner": "viewer"}, ), Job( id=str(uuid.uuid4()), job_type="sync", status="queued", created_by_id=admin_id, group_id=group.id, payload={"owner": "ops-admin"}, ), ] ) db.commit() finally: db.close() forbidden_users = client.get("/api/admin/users", headers=user_headers) forbidden_settings = client.get("/api/admin/settings", headers=user_headers) allowed_user_admin = client.get("/api/admin/users", headers=ops_headers) allowed_health_admin = client.get("/api/admin/dify-health", headers=ops_headers) assert forbidden_users.status_code == 403 assert forbidden_settings.status_code == 403 assert allowed_user_admin.status_code == 200 assert allowed_health_admin.status_code == 200 admin_jobs = client.get("/api/jobs", headers=admin_headers) assert admin_jobs.status_code == 200 assert len(admin_jobs.json()["data"]) == 3 user_jobs = client.get("/api/jobs", headers=user_headers) assert user_jobs.status_code == 200 assert len(user_jobs.json()["data"]) == 1 assert user_jobs.json()["data"][0]["payload"] == {"owner": "viewer"} ops_jobs = client.get("/api/jobs", headers=ops_headers) assert ops_jobs.status_code == 200 assert len(ops_jobs.json()["data"]) == 2 def test_admin_dify_health_reads_snapshot_and_local_summary(client): path = get_settings().data_root / "watchdog" / "dify-health.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps( { "status": "ok", "queue_lengths": {"priority_dataset": 1}, "worker": {"concurrency": 2}, } ), encoding="utf-8", ) _create_stale_syncing_document() response = client.get("/api/admin/dify-health", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["watchdog_snapshot"]["worker"]["concurrency"] == 2 assert payload["local_convert_health"]["pending_versions"] == 0 assert payload["local_sync_health"]["stale_candidates"] == 1 assert payload["dify_api_configured"] is False def test_admin_can_recover_stale_syncs(client): version_id, job_id = _create_stale_syncing_document() response = client.post("/api/admin/recover-stale-syncs", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["recovered_versions"] == 1 assert payload["recovered_jobs"] == 1 db = SessionLocal() try: version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() job = db.query(Job).filter(Job.id == job_id).first() assert version is not None assert job is not None assert version.sync_status == "sync_failed" assert job.status == "failed" finally: db.close() def test_admin_can_recover_stale_converts(client, monkeypatch): version_id, job_id = _create_stale_convert_document() monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) response = client.post("/api/admin/recover-stale-converts", headers=_headers(client)) assert response.status_code == 200 payload = response.json() assert payload["recovered_versions"] == 1 assert payload["recovered_jobs"] == 1 db = SessionLocal() try: version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() job = db.query(Job).filter(Job.id == job_id).first() assert version is not None assert job is not None assert version.convert_status == "failed" assert job.status == "failed" finally: db.close()