import asyncio import datetime import unittest from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch import httpx from fastapi import FastAPI from apps.admin.services import ConfigService, FileService from apps.admin.views import admin_api from apps.base.models import FileCodes, KeyValue from apps.base.views import share_api from core.settings import settings from core.utils import get_now, hash_password from tests.helpers import close_db, init_memory_db class UpgradeIntegrationTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original_settings = dict(settings.user_config) await init_memory_db() async def asyncTearDown(self): settings.user_config = self.original_settings await close_db() async def test_time_based_records_do_not_expire_immediately(self): item = await FileCodes.create(code="DEFAULT1", expired_at=await get_now() + datetime.timedelta(days=1)) self.assertFalse(await item.is_expired()) async def test_legacy_listing_keeps_files_when_many_directories_exist(self): from apps.admin.services import LocalFileService from apps.admin.views import get_local_lists with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)): root = Path(tmp, "local") root.mkdir() for n in range(501): (root / f"dir-{n}").mkdir() (root / "visible.txt").write_text("visible") result = await get_local_lists(path=None, page=None, size=20, keyword="", local_file_service=LocalFileService()) self.assertEqual([item["file"] for item in result.detail], ["visible.txt"]) async def test_local_paths_preserve_spaces_and_reject_external_symlinks(self): from apps.admin.services import LocalFileClass, LocalFileService from fastapi import HTTPException with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)): root = Path(tmp, "local") root.mkdir() (root / " report.txt ").write_bytes(b"spaced") self.assertEqual(await LocalFileClass(" report.txt ").read(), b"spaced") outside = Path(tmp, "private.txt") outside.write_bytes(b"private") (root / "escape.txt").symlink_to(outside) with self.assertRaises(HTTPException): LocalFileClass("escape.txt") listing = await LocalFileService().list_files() self.assertEqual([item["name"] for item in listing["items"]], [" report.txt "]) async def test_concurrent_activity_writes_keep_every_event(self): await asyncio.gather(*(FileService().record_admin_activity("file.update", "file", n, f"file-{n}") for n in range(20))) items = (await FileService().list_admin_activities(size=100))["items"] self.assertEqual({item["targetId"] for item in items}, set(range(20))) async def test_concurrent_settings_updates_preserve_both_changes(self): await ConfigService().update_config({"name": "before", "description": "before"}) await asyncio.gather(ConfigService().update_config({"name": "after"}), ConfigService().update_config({"description": "after"})) stored = (await KeyValue.get(key="settings")).value self.assertEqual((stored["name"], stored["description"]), ("after", "after")) async def test_password_change_rejects_login_waiting_on_old_password(self): from apps.admin import services, views from core.config import refresh_settings from fastapi import HTTPException row = await KeyValue.create(key="settings", value={"admin_token": hash_password("old-password"), "jwt_secret": "s" * 48}) await refresh_settings(force=True) async with services.keyvalue_write_lock: pending = asyncio.create_task(views.login(type("Login", (), {"password": "old-password"})(), ip="192.0.2.77")) await asyncio.sleep(0) row.value = {"admin_token": hash_password("new-password"), "jwt_secret": "n" * 48} await row.save() await refresh_settings(force=True) with self.assertRaises(HTTPException) as error: await pending self.assertEqual(error.exception.status_code, 401) async def test_local_share_http_download_trash_restore_and_purge_preserve_source(self): settings.user_config = {"admin_token": hash_password("integration-password"), "jwt_secret": "s" * 48, "file_storage": "webdav"} await KeyValue.create(key="settings", value=dict(settings.user_config)) app = FastAPI() app.include_router(admin_api) app.include_router(share_api) async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: login = await client.post("/admin/login", json={"password": "integration-password"}) self.assertEqual(login.status_code, 200, login.text) headers = {"Authorization": "Bearer " + login.json()["detail"]["token"]} with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)): source = Path(tmp, "local", "nested", "sample.txt") source.parent.mkdir(parents=True) source.write_bytes(b"original NAS bytes") unauthorized = await client.get("/admin/local/lists", params={"path": "nested"}) self.assertIn(unauthorized.status_code, (401, 403)) listing = await client.get("/admin/local/lists", params={"path": "nested"}, headers=headers) self.assertEqual(listing.json()["detail"]["items"][0]["path"], "nested/sample.txt") legacy = await client.get("/admin/local/lists", headers=headers) self.assertIsInstance(legacy.json()["detail"], list) bad = await client.get("/admin/local/lists", params={"path": "../"}, headers=headers) self.assertEqual(bad.status_code, 400) shared = await client.post("/admin/local/share", headers=headers, json={"filename": "nested/sample.txt", "expire_style": "day", "expire_value": 1}) self.assertEqual(shared.status_code, 200, shared.text) code = shared.json()["detail"]["code"] item = await FileCodes.get(code=code) selected = await client.post("/share/select/", json={"code": code}) self.assertEqual(selected.json()["detail"]["used_count"], 0) downloaded = await client.get(selected.json()["detail"]["download_url"]) self.assertEqual(downloaded.content, b"original NAS bytes") service = FileService() await service.move_to_trash(item, reason="manual") hidden = await client.post("/share/select/", json={"code": code}) self.assertEqual(hidden.json()["code"], 404) restored = await service.restore_from_trash(item.id) self.assertEqual(restored.code, code) self.assertEqual((await client.get("/admin/file/download", params={"id": item.id}, headers=headers)).content, b"original NAS bytes") await service.move_to_trash(restored, reason="manual") await service.purge_trashed_file(restored) self.assertEqual(source.read_bytes(), b"original NAS bytes") self.assertIsNotNone((await FileCodes.get(id=item.id)).trash_purged_at)