🔀 merge: 合并 2.7.0 后端并固定新版管理前端构建
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
Create release / release-please (push) Canceled after 0s
Build and push Docker image / buildx (push) Canceled after 0s

This commit is contained in:
orion committed 2026-09-18 10:30:39 +08:00
commit 96e8eeac39
34 files changed
+1725 -336

No files matched your search

View File
Whitespace-only changes.
+55
View File
@@ -0,0 +1,55 @@
"""Shared test helpers: settings-override mixin and in-memory Tortoise setup.
Kept unittest-friendly (the legacy suite is unittest-based); pytest fixtures
live in conftest.py and build on top of these helpers.
"""
from tortoise import Tortoise
from core.settings import settings
# Mirrors core.database.get_db_config() but with an in-memory SQLite database
# and no WAL/startup-lock specifics, so tests never touch the real data dir's DB.
MEMORY_DB_CONFIG = {
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
class SettingsOverrideMixin:
"""Snapshot settings.user_config in setUp and restore it in tearDown."""
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
async def init_memory_db():
"""Init Tortoise against an in-memory DB and create all schemas."""
# 每个测试都是全新 DB,必须同步失效进程级配置 TTL 缓存,
# 否则上一个测试的缓存会让 middleware 误判初始化状态。
import core.config as config_module
import asyncio
import apps.admin.services as services_module
services_module.keyvalue_write_lock = asyncio.Lock()
config_module._config_cached_until = 0.0
await Tortoise.init(config=MEMORY_DB_CONFIG)
await Tortoise.generate_schemas()
async def close_db():
await Tortoise.close_connections()
+13 -2
View File
@@ -1,3 +1,4 @@
from unittest.mock import AsyncMock, patch
import asyncio
import copy
import unittest
@@ -127,7 +128,8 @@ class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
with self.assertRaises(ValueError):
verify_token(token)
def test_configured_session_lifetime_is_returned_by_login(self):
@patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_configured_session_lifetime_is_returned_by_login(self, refresh):
settings.admin_token = hash_password("admin-password")
settings.jwt_secret = "j" * 48
settings.adminSessionExpire = 90 * 24 * 60 * 60
@@ -157,7 +159,7 @@ class FakeKeyValue:
return None, True
async def fake_refresh_settings():
async def fake_refresh_settings(**kwargs):
return None
@@ -186,6 +188,15 @@ class FakeConfigKeyValue:
class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
self.refresh_patch = patch("apps.admin.services.refresh_settings", fake_refresh_settings)
self.refresh_patch.start()
def tearDown(self):
self.refresh_patch.stop()
super().tearDown()
def test_storage_limit_rejects_negative_values(self):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
with self.assertRaises(HTTPException) as context:
+135
View File
@@ -0,0 +1,135 @@
"""Tests for the background-URL config validation.
Themes inject the site ``background`` config into inline CSS ``url('...')``;
a single-quote breakout there is not neutralized by html escaping (the CSS
engine decodes entities back). The fix is upstream validation at config-write
time: only well-formed http(s) URLs (or empty) may be stored.
"""
import asyncio
import unittest
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from apps.admin.services import ConfigService
from core.utils import validate_background_url
VALID = [
"",
"https://example.com/bg.webp",
"http://cdn.example.org/a/b.jpg?id=1&token=ab",
]
INVALID = [
"x') ;background:url(https://evil.com/)",
"https://example.com/bg') ;background:url(evil)",
"javascript:alert(1)",
"data:image/svg+xml;base64,AAAA",
"/relative/path.jpg",
"//protocol-relative.example/bg",
"https://example.com/a b.png",
"https://example.com/a(b).png",
]
class ValidateBackgroundUrlTests(unittest.TestCase):
def test_valid_values_pass_through(self):
for value in VALID:
self.assertEqual(validate_background_url(value), value.strip() if value else "")
def test_injection_and_non_http_values_rejected(self):
for value in INVALID:
with self.assertRaises(ValueError, msg=value):
validate_background_url(value)
def test_none_and_whitespace_become_empty(self):
self.assertEqual(validate_background_url(None), "")
self.assertEqual(validate_background_url(" "), "")
class ConfigServiceBackgroundGuardTests(SettingsOverrideMixin, unittest.TestCase):
def test_update_config_rejects_malicious_background(self):
asyncio.run(self._scenario())
async def _scenario(self):
await init_memory_db()
try:
service = ConfigService()
# 合法值可通过
await service.update_config({"background": "https://ok.example/bg.png"})
# 恶意值被拒且不落库
from fastapi import HTTPException
with self.assertRaises(HTTPException) as ctx:
await service.update_config({"background": "x') ;background:url(https://evil.com/)"})
self.assertEqual(ctx.exception.status_code, 400)
from apps.base.models import KeyValue
record = await KeyValue.filter(key="settings").first()
self.assertEqual(
record.value.get("background"), "https://ok.example/bg.png",
"被拒绝的值不得写入配置",
)
finally:
await close_db()
class LegacyBackgroundUpgradeTests(SettingsOverrideMixin, unittest.TestCase):
"""存量部署升级:旧版本合法、新校验不接受的值,不得阻塞设置保存。"""
def test_unchanged_legacy_background_does_not_block_unrelated_save(self):
asyncio.run(self._unchanged_legacy_allows_save())
async def _unchanged_legacy_allows_save(self):
await init_memory_db()
try:
from core.config import refresh_settings
from apps.base.models import KeyValue
# 旧版本合法(相对路径 + 空格),新的 http(s) 校验会拒绝
legacy = "/static/bg image.png"
await KeyValue.create(
key="settings", value={"background": legacy, "name": "old"}
)
await refresh_settings(force=True)
service = ConfigService()
# 修复前这里会 400,导致存量部署连无关设置项都保存不了
await service.update_config({"name": "new"})
record = await KeyValue.filter(key="settings").first()
self.assertEqual(record.value.get("background"), legacy, "旧值应原样保留")
self.assertEqual(record.value.get("name"), "new")
finally:
await close_db()
def test_changing_background_is_still_validated(self):
asyncio.run(self._change_still_validated())
async def _change_still_validated(self):
await init_memory_db()
try:
from fastapi import HTTPException
from core.config import refresh_settings
from apps.base.models import KeyValue
await KeyValue.create(key="settings", value={"background": "/legacy/bg.png"})
await refresh_settings(force=True)
service = ConfigService()
# 修改为恶意值仍然被拒
with self.assertRaises(HTTPException) as ctx:
await service.update_config(
{"background": "x') ;background:url(https://evil.com/)"}
)
self.assertEqual(ctx.exception.status_code, 400)
# 修改为合法值可以通过
await service.update_config({"background": "https://ok.example/bg.png"})
record = await KeyValue.filter(key="settings").first()
self.assertEqual(record.value.get("background"), "https://ok.example/bg.png")
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
+5
View File
@@ -16,12 +16,16 @@ class SettingsOverrideMixin:
settings.user_config = self._original_user_config
THEMES_BUILT = all((BASE_DIR / f"themes/{year}/assets").is_dir() for year in (2023, 2024))
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
def get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
return assets[0].name
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
def test_resolves_assets_from_current_theme(self):
settings.themesSelect = "themes/2023"
theme_2023_asset = resolve_theme_file(
@@ -62,6 +66,7 @@ class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
)
self.assertEqual(response.status_code, 404)
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
def test_index_rewrites_assets_to_theme_specific_urls(self):
settings.themesSelect = "themes/2023"
+207
View File
@@ -0,0 +1,207 @@
"""Local NAS share: nested browse + zero-copy extract codes (issue #532)."""
import asyncio
import datetime
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from fastapi import HTTPException
from apps.admin.services import FileService, LocalFileClass, LocalFileService
LOCAL_REF_MARKER = "local-ref"
def is_local_ref(record):
return record.file_path == LOCAL_REF_MARKER
from apps.base.models import FileCodes
from apps.base.quota import get_storage_usage, reserve_storage
from core.tasks import delete_expire_files
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from core.settings import settings
from core.utils import get_now
class SleepSentinel(Exception):
pass
class LocalFileClassTests(unittest.TestCase):
def setUp(self):
self._tmpdir = TemporaryDirectory()
self.root = Path(self._tmpdir.name)
(self.root / "local").mkdir()
(self.root / "local" / "safe.txt").write_bytes(b"ok")
(self.root / "local" / "movies").mkdir()
(self.root / "local" / "movies" / "a.bin").write_bytes(b"nested")
self._patch = patch("core.settings.data_root", self.root)
self._patch.start()
def tearDown(self):
self._patch.stop()
self._tmpdir.cleanup()
def test_rejects_dotdot_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("../etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_nested_dotdot(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("movies/../../etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_absolute_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("/etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_allows_basename_inside_local(self):
local_file = LocalFileClass("safe.txt")
self.assertTrue(asyncio.run(local_file.exists()))
self.assertEqual(local_file.file, "safe.txt")
self.assertEqual(local_file.path, (self.root / "local" / "safe.txt").resolve())
def test_allows_nested_relative(self):
local_file = LocalFileClass("movies/a.bin")
self.assertTrue(asyncio.run(local_file.exists()))
self.assertEqual(local_file.file, "movies/a.bin")
self.assertEqual(local_file.name, "a.bin")
self.assertEqual(local_file.size, 6)
class LocalFileServiceListTests(unittest.TestCase):
def test_lists_nested_dirs_and_files(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
movies = root / "local" / "movies"
movies.mkdir(parents=True)
(root / "local" / "readme.txt").write_bytes(b"hi")
(movies / "a.bin").write_bytes(b"nested")
with patch("core.settings.data_root", root):
service = LocalFileService()
root_listing = await service.list_files("")
self.assertEqual(root_listing["path"], "")
names = {item["name"]: item for item in root_listing["items"]}
self.assertEqual(names["movies"]["type"], "dir")
self.assertEqual(names["readme.txt"]["type"], "file")
nested = await service.list_files("movies")
self.assertEqual(nested["path"], "movies")
self.assertEqual(nested["parent"], "")
self.assertEqual(nested["items"][0]["path"], "movies/a.bin")
self.assertEqual(nested["items"][0]["file"], "a.bin")
class ShareLocalFileTests(SettingsOverrideMixin, unittest.TestCase):
def test_share_local_file_is_zero_copy(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
await init_memory_db()
try:
root = Path(tmpdir)
movies = root / "local" / "movies"
movies.mkdir(parents=True)
source = movies / "doc.txt"
source.write_bytes(b"hello local share")
with patch("core.settings.data_root", root), patch(
"core.storage.data_root", root
):
class Item:
filename = "movies/doc.txt"
expire_value = 1
expire_style = "day"
result = await FileService().share_local_file(Item())
self.assertIn("code", result)
self.assertEqual(result["name"], "doc.txt")
self.assertEqual(result["path"], "movies/doc.txt")
record = await FileCodes.get(code=result["code"])
self.assertTrue(is_local_ref(record))
self.assertEqual(record.file_path, LOCAL_REF_MARKER)
self.assertEqual(record.uuid_file_name, "movies/doc.txt")
self.assertTrue(source.exists())
share_files = [
p for p in (root / "share").rglob("*") if p.is_file()
] if (root / "share").exists() else []
self.assertFalse(share_files)
finally:
await close_db()
class LocalRefCleanupTests(SettingsOverrideMixin, unittest.TestCase):
def test_expire_trashes_record_but_keeps_original(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
await init_memory_db()
try:
root = Path(tmpdir)
source = root / "local" / "keep.bin"
source.parent.mkdir(parents=True)
source.write_bytes(b"keep-me")
now = await get_now()
await FileCodes.create(
code="nas1",
prefix="keep",
suffix=".bin",
uuid_file_name="keep.bin",
file_path=LOCAL_REF_MARKER,
size=7,
expired_at=now - datetime.timedelta(days=1),
expired_count=-1,
)
def _sleep(_seconds):
raise SleepSentinel
with patch("core.settings.data_root", root), patch(
"core.storage.data_root", root
), patch("core.tasks.data_root", root), patch(
"core.tasks.asyncio.sleep", side_effect=_sleep
):
try:
await delete_expire_files()
except SleepSentinel:
pass
self.assertTrue(source.exists())
self.assertTrue((await FileCodes.get(code="nas1")).is_trashed)
finally:
await close_db()
class LocalRefQuotaTests(SettingsOverrideMixin, unittest.TestCase):
def test_local_ref_does_not_consume_quota(self):
asyncio.run(self._scenario())
async def _scenario(self):
settings.storageLimit = 100
await init_memory_db()
try:
await FileCodes.create(
code="nas-big",
size=10_000,
expired_count=-1,
file_path=LOCAL_REF_MARKER,
uuid_file_name="movies/huge.bin",
)
await FileCodes.create(code="owned", size=20, expired_count=-1)
usage = await get_storage_usage()
self.assertEqual(usage["used"], 20)
await reserve_storage("upload-ok", 50, 300)
usage = await get_storage_usage()
self.assertEqual(usage["reserved"], 50)
self.assertEqual(usage["available"], 30)
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
+152
View File
@@ -0,0 +1,152 @@
"""Tests for the scrypt password-hashing scheme and transparent rehash.
Legacy formats (sha256$salt$hash and plaintext) must keep verifying; new
hashes are scrypt (memory-hard). A successful login with a legacy-stored
password upgrades the stored hash in place.
"""
import asyncio
import time
import hashlib
import unittest
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from apps.admin import views as admin_views
from apps.base.models import KeyValue
from core.settings import settings
from core.utils import (
hash_password,
is_password_hashed,
password_needs_rehash,
verify_password,
)
class PasswordHashSchemeTests(unittest.TestCase):
def test_scrypt_roundtrip_and_rejection(self):
hashed = hash_password("s3cret-pass")
self.assertTrue(hashed.startswith("scrypt$"))
self.assertTrue(verify_password("s3cret-pass", hashed))
self.assertFalse(verify_password("wrong-pass", hashed))
def test_legacy_sha256_and_plaintext_still_verify(self):
salt = "abcd1234"
sha_hash = f"sha256${salt}${hashlib.sha256(f'{salt}legacy'.encode()).hexdigest()}"
self.assertTrue(verify_password("legacy", sha_hash))
self.assertFalse(verify_password("other", sha_hash))
self.assertTrue(verify_password("plain", "plain"))
self.assertFalse(verify_password("plain", "other-plain"))
def test_scheme_detection_helpers(self):
scrypt_hash = hash_password("x")
sha_hash = "sha256$a$b"
self.assertTrue(is_password_hashed(scrypt_hash))
self.assertTrue(is_password_hashed(sha_hash))
self.assertFalse(is_password_hashed("plaintext"))
self.assertFalse(password_needs_rehash(scrypt_hash))
self.assertTrue(password_needs_rehash(sha_hash))
self.assertTrue(password_needs_rehash("plaintext"))
self.assertFalse(password_needs_rehash(""))
def test_malformed_hashes_are_rejected_not_crashing(self):
self.assertFalse(verify_password("x", "scrypt$1$2$3"))
self.assertFalse(verify_password("x", "scrypt$n$r$p$salt$zzz"))
self.assertFalse(verify_password("x", "sha256$only-two"))
self.assertFalse(verify_password("x", ""))
# 超范围的 n/r/p:解释器抛 TypeError/ValueError(部分构建抛 OverflowError),
# 都必须被吞掉并判为不匹配,而不是让登录及每个请求 500
self.assertFalse(
verify_password("x", "scrypt$99999999999999999999999999$8$1$aa$bb")
)
class TransparentRehashTests(SettingsOverrideMixin, unittest.TestCase):
def test_legacy_hash_upgraded_on_successful_login(self):
asyncio.run(self._scenario())
async def _scenario(self):
await init_memory_db()
try:
legacy_password = "old-style-pass"
salt = "feed1234"
legacy_hash = (
f"sha256${salt}${hashlib.sha256(f'{salt}{legacy_password}'.encode()).hexdigest()}"
)
record = await KeyValue.create(
key="settings",
value={"admin_token": legacy_hash, "jwt_secret": "s" * 48},
)
settings.user_config = dict(record.value)
ok = await admin_views.login(
type("D", (), {"password": legacy_password})(), ip="1.2.3.4"
)
self.assertEqual(ok.detail["username"], "admin")
upgraded = (await KeyValue.filter(key="settings").first()).value["admin_token"]
self.assertTrue(upgraded.startswith("scrypt$"), upgraded[:20])
self.assertTrue(verify_password(legacy_password, upgraded))
self.assertFalse(password_needs_rehash(upgraded))
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
class CheapInitProbeTests(unittest.TestCase):
"""D1 回归:is_config_initialized 在每个请求都会被中间件调用,
对 scrypt 口令绝不允许跑慢哈希。"""
def test_scrypt_token_is_initialized_without_slow_hash(self):
from core.security import is_config_initialized
from core.utils import hash_password as hp
token = hp("some-real-password")
t0 = time.perf_counter()
self.assertTrue(is_config_initialized({"admin_token": token}))
self.assertLess(time.perf_counter() - t0, 0.01, "初始化探测不应执行 scrypt")
def test_empty_and_legacy_default_are_not_initialized(self):
from core.security import is_config_initialized, LEGACY_DEFAULT_ADMIN_TOKEN
self.assertFalse(is_config_initialized({"admin_token": ""}))
self.assertFalse(is_config_initialized({"admin_token": LEGACY_DEFAULT_ADMIN_TOKEN}))
class ConfigCacheTests(unittest.TestCase):
"""D6 回归:TTL 内的 refresh_settings 不再读库,写路径 force=True 必须穿透。
验证手法(无 mock):直接改 DB 里的值——
- TTL 内普通 refresh 不读库 → settings 仍是旧值;
- force=True 读库 → 新值生效。
"""
def test_ttl_cache_skips_db_and_force_bypasses(self):
import core.config as config_module
from apps.base.models import KeyValue
from tests.helpers import close_db, init_memory_db
async def scenario():
await init_memory_db()
try:
row = await KeyValue.create(
key="settings", value={"name": "旧值", "admin_token": "x" * 64}
)
await config_module.refresh_settings(force=True)
self.assertEqual(settings.name, "旧值")
# 直接改 DB(绕过应用层),TTL 内普通 refresh 不应看到
row.value = {"name": "新值", "admin_token": "x" * 64}
await row.save()
await config_module.refresh_settings()
self.assertEqual(settings.name, "旧值", "TTL 内不应读库")
await config_module.refresh_settings(force=True)
self.assertEqual(settings.name, "新值", "force 必须穿透缓存")
finally:
config_module._config_cached_until = 0.0
await close_db()
asyncio.run(scenario())
+1 -7
View File
@@ -1,7 +1,6 @@
from pathlib import Path
import unittest
from scripts.patch_admin_timeline_ui import build_lifecycle_script, patch_clipboard, patch_file_manage
from scripts.patch_admin_timeline_ui import build_lifecycle_script
class AdminTimelinePatchTests(unittest.TestCase):
@@ -12,11 +11,6 @@ class AdminTimelinePatchTests(unittest.TestCase):
self.assertIn("展开全部取件记录", script)
self.assertIn("row.style.overflow = 'visible'", script)
def test_shared_compiled_modules_are_not_rewritten(self):
placeholder = Path("unused.js")
self.assertFalse(patch_file_manage(placeholder))
self.assertFalse(patch_clipboard(placeholder))
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, patch
from tortoise import Tortoise
from apps.base.models import FileCodes, ShareCodeReservations
from apps.base.models import FileCodes
from apps.base.utils import CODE_LENGTH, get_random_code
from apps.admin.services import ConfigService, FileService
from core.settings import settings
@@ -59,7 +59,7 @@ class RecycleBinTests(unittest.TestCase):
purged = await FileCodes.create(code="purged", prefix="purged", suffix=".txt", file_path="share/data/purged", uuid_file_name="purged.txt", expired_count=-1, is_trashed=True, trash_purged_at=await get_now())
original_refresh = __import__("apps.admin.services", fromlist=["refresh_settings"]).refresh_settings
async def fake_refresh():
async def fake_refresh(**kwargs):
return None
module = __import__("apps.admin.services", fromlist=["refresh_settings"])
module.refresh_settings = fake_refresh
@@ -87,8 +87,8 @@ class RecycleBinTests(unittest.TestCase):
with self.assertRaises(Exception):
await service.restore_from_trash(item.id)
await ShareCodeReservations.create(code="RETIRE02", file_code_id=item.id)
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRE02", "FRESH002"])):
await FileCodes.create(code="RETIRED1", is_trashed=True, trash_purged_at=datetime.datetime.now())
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRED1", "FRESH002"])):
self.assertEqual(await get_random_code(), "FRESH002")
generated_code = await get_random_code()
+5 -2
View File
@@ -1,3 +1,4 @@
from unittest.mock import AsyncMock, patch
import asyncio
import unittest
from pathlib import Path
@@ -67,7 +68,8 @@ class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
ip_limit["login"] = self._original_login_limiter
super().tearDown()
def test_failed_logins_are_rate_limited(self):
@patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_failed_logins_are_rate_limited(self, refresh):
async def attempt(password: str):
return await admin_views.login(
data=LoginData(password=password), ip="203.0.113.10"
@@ -80,7 +82,8 @@ class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
def test_successful_login_does_not_consume_failure_quota(self):
@patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_successful_login_does_not_consume_failure_quota(self, refresh):
result = asyncio.run(
admin_views.login(
data=LoginData(password="correct-password-123"), ip="198.51.100.8"
+1 -1
View File
@@ -40,7 +40,7 @@ class LocalFilePathTraversalTests(unittest.TestCase):
self.local_root.mkdir(parents=True, exist_ok=True)
(self.local_root / "safe.txt").write_text("ok", encoding="utf-8")
self._data_root_patch = patch(
"apps.admin.services.data_root", Path(self._tmpdir.name)
"core.settings.data_root", Path(self._tmpdir.name)
)
self._data_root_patch.start()
+5 -8
View File
@@ -9,7 +9,7 @@ from apps.base.models import FileCodes, ShareCodeReservations
class ShareCodeReservationTests(unittest.TestCase):
def test_restore_reserves_old_code_before_assigning_new_code(self):
def test_restore_keeps_original_code_and_releases_own_reservation(self):
asyncio.run(self.scenario())
async def scenario(self):
@@ -25,13 +25,10 @@ class ShareCodeReservationTests(unittest.TestCase):
try:
item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text")
service = FileService()
with patch("apps.admin.services.get_random_code", AsyncMock(return_value="NEWCODE8")):
restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, "NEWCODE8")
reservation = await ShareCodeReservations.get(code="OLD_CODE")
self.assertEqual(reservation.file_code_id, item.id)
self.assertEqual(reservation.reason, "restored")
await ShareCodeReservations.create(code="OLD_CODE", file_code_id=item.id, reason="restored")
restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, "OLD_CODE")
self.assertFalse(await ShareCodeReservations.filter(code="OLD_CODE").exists())
# 模拟管理员手工改码:被替换的旧码也必须永久封存。
await ShareCodeReservations.get_or_create(
+195
View File
@@ -0,0 +1,195 @@
import datetime
import unittest
from unittest.mock import AsyncMock
from fastapi import HTTPException
from tortoise import Tortoise
from apps.admin.services import FileService
from apps.base.models import FileCodes, ShareCodeReservations
from core.utils import get_now
class TrashManagementTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
await Tortoise.init(config={
'connections': {'default': {'engine': 'tortoise.backends.sqlite', 'credentials': {'file_path': ':memory:'}}},
'apps': {'models': {'models': ['apps.base.models'], 'default_connection': 'default'}},
'use_tz': False, 'timezone': 'Asia/Shanghai',
})
await Tortoise.generate_schemas()
self.service = FileService()
self.now = await get_now()
self.a = await self.make('Alpha', 'ABC12345', 'manual', self.now + datetime.timedelta(days=30))
self.b = await self.make('Beta', 'BET12345', 'expired', None)
self.purged = await self.make('Retired', 'OLD12345', 'manual', None, self.now)
self.live = await FileCodes.create(code='LIVE1234', prefix='Alpha', suffix='.txt', text='live', expired_count=-1)
async def asyncTearDown(self):
await Tortoise.close_connections()
async def make(self, name, code, reason, expiry, purged=None):
return await FileCodes.create(code=code, prefix=name, suffix='.txt', text='test', expired_count=-1,
is_trashed=True, trashed_at=self.now, trash_reason=reason,
trash_expires_at=expiry, trash_purged_at=purged)
async def test_filters_apply_to_all_records_before_pagination(self):
result = await self.service.list_trash(1, 1, keyword='alpha.txt')
self.assertEqual(result['total'], 1)
self.assertEqual(result['data'][0]['id'], self.a.id)
self.assertEqual(result['summary'], {'total': 3, 'recoverable': 2, 'purged': 1})
by_code = await self.service.list_trash(1, 20, keyword='bet123')
self.assertEqual(by_code['data'][0]['id'], self.b.id)
for state, total in [('all', 3), ('recoverable', 2), ('permanent', 1), ('scheduled', 1), ('purged', 1)]:
self.assertEqual((await self.service.list_trash(1, 20, state=state))['total'], total)
self.assertEqual((await self.service.list_trash(1, 20, reason='expired'))['total'], 1)
self.assertEqual((await self.service.list_trash(1, 20, state='purged', reason='expired'))['total'], 0)
self.assertEqual((await self.service.list_trash(1, 20, keyword='no-match'))['total'], 0)
async def test_invalid_filters_and_page_bounds(self):
for kwargs in [{'state':'invalid'}, {'reason':'invalid'}]:
with self.assertRaises(HTTPException):
await self.service.list_trash(1, 20, **kwargs)
result = await self.service.list_trash(0, 1000)
self.assertEqual((result['page'], result['size']), (1, 100))
async def test_custom_deadline_supports_timezone_and_permanent(self):
deadline = self.now + datetime.timedelta(days=4)
await self.service.set_trash_retention(self.a.id, expires_at=deadline.astimezone(datetime.timezone.utc))
await self.a.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, deadline)
await self.service.set_trash_retention(self.a.id, expires_at=deadline.replace(tzinfo=None))
await self.a.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, deadline)
await self.service.set_trash_retention(self.a.id, 0)
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_expires_at)
await self.service.set_trash_retention(self.a.id, 7)
await self.a.refresh_from_db()
self.assertAlmostEqual((self.a.trash_expires_at-self.now).total_seconds(), 7*86400, delta=3)
async def test_retention_rejects_purged_live_missing_and_invalid_dates(self):
for file_id in [self.purged.id, self.live.id, 9999]:
with self.assertRaises(HTTPException):
await self.service.set_trash_retention(file_id, 0)
for kwargs in [dict(), {'retention_days': -1}, {'expires_at': self.now-datetime.timedelta(days=1)},
{'expires_at': self.now+datetime.timedelta(days=366)}, {'retention_days': 0, 'expires_at': self.now+datetime.timedelta(days=1)}]:
with self.assertRaises(HTTPException):
await self.service.set_trash_retention(self.a.id, **kwargs)
async def test_batch_updates_one_deadline_deduplicates_and_reports_failures(self):
deadline = self.now+datetime.timedelta(days=5)
result = await self.service.batch_trash([self.a.id, self.a.id, self.b.id, self.purged.id, self.live.id, 9999], 'retention', expires_at=deadline)
self.assertEqual(len(result['succeeded']), 2)
self.assertEqual(len(result['failed']), 3)
self.assertEqual(result['requestedCount'], 5)
await self.a.refresh_from_db(); await self.b.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, self.b.trash_expires_at)
self.assertEqual(self.a.trash_expires_at, deadline)
async def test_batch_restore_reuses_old_codes_and_preserves_live_records(self):
old = self.a.code
result = await self.service.batch_trash([self.a.id, self.b.id, self.purged.id, self.live.id], 'restore')
self.assertEqual(len(result['succeeded']), 2)
self.assertEqual(len(result['failed']), 2)
await self.a.refresh_from_db()
self.assertFalse(self.a.is_trashed)
self.assertEqual(old, self.a.code)
self.assertEqual(len(result['succeeded'][0]['code']), 8)
async def test_batch_purge_preserves_audit_and_sanitizes_storage_failures(self):
file = await FileCodes.create(code='FILE1234', prefix='error', suffix='.txt', is_trashed=True, file_path='share/test', uuid_file_name='test.txt', expired_count=-1)
self.service._file_storage = AsyncMock()
self.service._file_storage.delete_file.side_effect = RuntimeError('private storage credentials')
result = await self.service.batch_trash([file.id, self.a.id], 'purge')
self.assertEqual(len(result['succeeded']), 1)
self.assertEqual(result['failed'][0]['reason'], '操作失败,请重试')
await self.a.refresh_from_db(); await file.refresh_from_db()
self.assertIsNotNone(self.a.trash_purged_at)
self.assertTrue(self.a.is_trashed)
self.assertIsNone(file.trash_purged_at)
async def test_bad_batch_request_never_modifies_records(self):
for ids, action, kwargs in [([], 'restore', {}), (list(range(1,102)), 'purge', {}), ([self.a.id], 'bad', {}), ([self.a.id], 'retention', {'retention_days': -1})]:
with self.assertRaises(HTTPException):
await self.service.batch_trash(ids, action, **kwargs)
await self.a.refresh_from_db()
self.assertTrue(self.a.is_trashed)
self.assertIsNone(self.a.trash_purged_at)
async def test_specific_deletion_reasons_and_expiry_classification(self):
from apps.admin.trash_management import automatic_trash_reason
from types import SimpleNamespace
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=self.now, expired_count=-1), self.now), 'expired_time')
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=None, expired_count=0), self.now), 'expired_count')
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=self.now.replace(tzinfo=None), expired_count=0), self.now), 'expired_both')
self.assertIsNone(automatic_trash_reason(SimpleNamespace(expired_at=self.now+datetime.timedelta(days=1), expired_count=-1), self.now))
await self.service.delete_files([self.live.id])
await self.live.refresh_from_db()
self.assertEqual(self.live.trash_reason, 'batch_delete')
result=await self.service.list_trash(1,20,reason='batch_delete')
self.assertEqual(result['total'],1)
self.assertEqual((await self.service.list_trash(1,20,reason='expired_count'))['total'],0)
def api_client(self, authorized=True):
import httpx
from fastapi import FastAPI
from apps.admin.views import admin_api
from apps.admin.dependencies import admin_required, get_file_service
app = FastAPI()
app.include_router(admin_api)
if authorized:
app.dependency_overrides[admin_required] = lambda: None
app.dependency_overrides[get_file_service] = lambda: self.service
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test')
async def test_api_filters_and_batch_custom_deadline(self):
async with self.api_client() as client:
response = await client.get('/admin/trash/list', params={'keyword':'Alpha.txt','state':'scheduled','reason':'manual'})
self.assertEqual(response.status_code,200)
self.assertEqual(response.json()['detail']['total'],1)
self.assertTrue(response.json()['detail']['capabilities']['batch'])
date=(self.now+datetime.timedelta(days=2)).isoformat()
response=await client.post('/admin/trash/batch',json={'ids':[self.a.id,self.b.id],'action':'retention','expiresAt':date})
self.assertEqual(response.status_code,200)
self.assertEqual(len(response.json()['detail']['succeeded']),2)
response=await client.post('/admin/trash/retention',json={'id':self.a.id,'retentionDays':0})
self.assertEqual(response.status_code,200)
self.assertIsNone(response.json()['detail']['trashExpiresAt'])
async def test_api_schema_rejects_invalid_batches_and_requires_authentication(self):
async with self.api_client() as client:
for body in [
{'ids':[],'action':'purge'}, {'ids':[self.a.id],'action':'retention'},
{'ids':[self.a.id],'action':'purge','retentionDays':0},
{'ids':[self.a.id],'action':'retention','retentionDays':0,'expiresAt':self.now.isoformat()},
{'ids':[True],'action':'purge'}, {'ids':[self.a.id],'action':'invalid'},
{'ids':list(range(101)),'action':'purge'},
]:
self.assertEqual((await client.post('/admin/trash/batch',json=body)).status_code,422)
self.assertEqual((await client.post('/admin/trash/retention',json={'id':self.a.id})).status_code,422)
self.assertEqual((await client.get('/admin/trash/list',params={'state':'invalid'})).status_code,400)
async with self.api_client(authorized=False) as client:
response=await client.post('/admin/trash/batch',json={'ids':[self.a.id],'action':'purge'})
self.assertIn(response.status_code,[401,403])
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_purged_at)
async def test_invalid_direct_requests_and_all_failed_batches(self):
for ids,action,kwargs in [([0],'purge',{}),([True],'purge',{}),([self.a.id],'purge',{'retention_days':0})]:
with self.assertRaises(HTTPException):
await self.service.batch_trash(ids,action,**kwargs)
result=await self.service.batch_trash([self.purged.id],'purge')
self.assertEqual(result['succeeded'],[])
self.assertEqual(len(result['failed']),1)
result=await self.service.batch_trash([self.a.id,self.b.id],'retention',retention_days=0)
self.assertEqual(len(result['succeeded']),2)
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_expires_at)
async def test_restore_rejects_old_code_owned_by_another_active_file(self):
await ShareCodeReservations.create(code=self.a.code, reason='retired')
with self.assertRaises(HTTPException):
await self.service.restore_from_trash(self.a.id)
await self.a.refresh_from_db()
self.assertTrue(self.a.is_trashed)
+131
View File
@@ -0,0 +1,131 @@
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, 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)