feat: 整合官方 2.7.0 安全修复与本地文件分享
This commit is contained in:
1 parent
b10113e5ab
commit
9e9571b031
42 files changed
+2824
-268
No files matched your search
Whitespace-only changes.
@@ -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()
|
||||
@@ -0,0 +1,279 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import asyncio
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
import apps.admin.services as admin_services
|
||||
import apps.admin.views as admin_views
|
||||
import apps.admin.dependencies as admin_dependencies
|
||||
import core.config as core_config
|
||||
from apps.admin.dependencies import create_token, verify_token
|
||||
from apps.admin.schemas import LoginData
|
||||
from apps.admin.services import ConfigService
|
||||
from fastapi import HTTPException
|
||||
from main import parse_setup_options
|
||||
from core.security import (
|
||||
LEGACY_DEFAULT_ADMIN_TOKEN,
|
||||
is_config_initialized,
|
||||
prepare_security_config,
|
||||
)
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
from core.utils import hash_password, verify_password
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class SecurityConfigTests(unittest.TestCase):
|
||||
def test_initial_security_config_requires_setup_and_generates_jwt_secret(self):
|
||||
result = prepare_security_config(DEFAULT_CONFIG)
|
||||
|
||||
self.assertTrue(result.changed)
|
||||
self.assertTrue(result.setup_required)
|
||||
self.assertEqual(result.config["admin_token"], "")
|
||||
self.assertFalse(is_config_initialized(result.config))
|
||||
self.assertGreaterEqual(len(result.config["jwt_secret"]), 32)
|
||||
|
||||
def test_legacy_default_password_requires_setup(self):
|
||||
config = copy.deepcopy(DEFAULT_CONFIG)
|
||||
config["admin_token"] = hash_password(LEGACY_DEFAULT_ADMIN_TOKEN)
|
||||
config["jwt_secret"] = "j" * 48
|
||||
|
||||
result = prepare_security_config(config)
|
||||
|
||||
self.assertTrue(result.setup_required)
|
||||
self.assertEqual(result.config["admin_token"], "")
|
||||
self.assertEqual(result.config["jwt_secret"], "j" * 48)
|
||||
|
||||
def test_custom_plaintext_password_is_hashed_and_initialized(self):
|
||||
config = copy.deepcopy(DEFAULT_CONFIG)
|
||||
config["admin_token"] = "custom-password"
|
||||
config["jwt_secret"] = "j" * 48
|
||||
|
||||
result = prepare_security_config(config)
|
||||
|
||||
self.assertTrue(result.password_hashed)
|
||||
self.assertTrue(is_config_initialized(result.config))
|
||||
self.assertTrue(verify_password("custom-password", result.config["admin_token"]))
|
||||
|
||||
|
||||
class SetupOptionTests(unittest.TestCase):
|
||||
def test_parse_setup_options_converts_common_fields(self):
|
||||
options = parse_setup_options(
|
||||
{
|
||||
"upload_size_value": "20",
|
||||
"upload_size_unit": "MB",
|
||||
"save_time_value": "7",
|
||||
"save_time_unit": "day",
|
||||
"uploadCount": "30",
|
||||
"uploadMinute": "2",
|
||||
"errorCount": "5",
|
||||
"errorMinute": "1",
|
||||
"loginCount": "4",
|
||||
"loginMinute": "20",
|
||||
"openUpload": ["0", "1"],
|
||||
"enableChunk": "0",
|
||||
"code_generate_type": "secret",
|
||||
"expireStyle": ["day", "count"],
|
||||
"allowed_file_types": ".zip, image/*",
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
|
||||
self.assertEqual(options["max_save_seconds"], 7 * 86400)
|
||||
self.assertEqual(options["uploadCount"], 30)
|
||||
self.assertEqual(options["uploadMinute"], 2)
|
||||
self.assertEqual(options["errorCount"], 5)
|
||||
self.assertEqual(options["errorMinute"], 1)
|
||||
self.assertEqual(options["loginCount"], 4)
|
||||
self.assertEqual(options["loginMinute"], 20)
|
||||
self.assertEqual(options["openUpload"], 1)
|
||||
self.assertEqual(options["enableChunk"], 0)
|
||||
self.assertEqual(options["code_generate_type"], "secret")
|
||||
self.assertEqual(options["expireStyle"], ["day", "count"])
|
||||
self.assertEqual(options["allowed_file_types"], [".zip", "image/*"])
|
||||
|
||||
def test_parse_setup_options_allows_turning_guest_upload_off(self):
|
||||
options = parse_setup_options(
|
||||
{
|
||||
"openUpload": "0",
|
||||
"expireStyle": ["day"],
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(options["openUpload"], 0)
|
||||
|
||||
def test_parse_setup_options_requires_expire_style(self):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_setup_options({"expireStyle": []})
|
||||
|
||||
|
||||
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_admin_jwt_signature_uses_independent_secret(self):
|
||||
settings.admin_token = hash_password("old-admin-password")
|
||||
settings.jwt_secret = "j" * 48
|
||||
|
||||
token = create_token({"is_admin": True}, expires_in=60)
|
||||
self.assertTrue(verify_token(token)["is_admin"])
|
||||
|
||||
settings.admin_token = hash_password("new-admin-password")
|
||||
self.assertTrue(verify_token(token)["is_admin"])
|
||||
|
||||
settings.jwt_secret = "k" * 48
|
||||
with self.assertRaises(ValueError):
|
||||
verify_token(token)
|
||||
|
||||
@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
|
||||
original_time = admin_dependencies.time.time
|
||||
admin_dependencies.time.time = lambda: 1_800_000_000
|
||||
try:
|
||||
response = asyncio.run(
|
||||
admin_views.login(LoginData(password="admin-password"))
|
||||
)
|
||||
payload = verify_token(response.detail["token"])
|
||||
finally:
|
||||
admin_dependencies.time.time = original_time
|
||||
|
||||
self.assertEqual(response.detail["expires_in"], 90 * 24 * 60 * 60)
|
||||
self.assertEqual(
|
||||
response.detail["expires_at"], 1_800_000_000 + 90 * 24 * 60 * 60
|
||||
)
|
||||
self.assertEqual(payload["exp"], response.detail["expires_at"])
|
||||
|
||||
|
||||
class FakeKeyValue:
|
||||
saved_value = None
|
||||
|
||||
@classmethod
|
||||
async def update_or_create(cls, key, defaults):
|
||||
cls.saved_value = defaults["value"]
|
||||
return None, True
|
||||
|
||||
|
||||
async def fake_refresh_settings(**kwargs):
|
||||
return None
|
||||
|
||||
|
||||
class FakeConfigRecord:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
|
||||
class FakeConfigQuery:
|
||||
async def first(self):
|
||||
return FakeConfigKeyValue.record
|
||||
|
||||
|
||||
class FakeConfigKeyValue:
|
||||
record = None
|
||||
saved_value = None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, key):
|
||||
return FakeConfigQuery()
|
||||
|
||||
@classmethod
|
||||
async def update_or_create(cls, key, defaults):
|
||||
cls.saved_value = defaults["value"]
|
||||
return None, True
|
||||
|
||||
|
||||
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:
|
||||
asyncio.run(ConfigService().update_config({"storageLimit": -1}))
|
||||
self.assertEqual(context.exception.status_code, 400)
|
||||
|
||||
def test_admin_session_lifetime_rejects_out_of_range_values(self):
|
||||
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
|
||||
|
||||
for invalid_value in (0, 86399, 90000, 365 * 24 * 60 * 60 + 1):
|
||||
with self.subTest(invalid_value=invalid_value):
|
||||
with self.assertRaises(HTTPException) as context:
|
||||
asyncio.run(
|
||||
ConfigService().update_config(
|
||||
{"adminSessionExpire": invalid_value}
|
||||
)
|
||||
)
|
||||
self.assertEqual(context.exception.status_code, 400)
|
||||
|
||||
def test_admin_password_update_rotates_jwt_secret(self):
|
||||
old_secret = "j" * 48
|
||||
settings.user_config = {
|
||||
**copy.deepcopy(DEFAULT_CONFIG),
|
||||
"admin_token": hash_password("old-admin-password"),
|
||||
"jwt_secret": old_secret,
|
||||
}
|
||||
original_key_value = admin_services.KeyValue
|
||||
original_refresh_settings = admin_services.refresh_settings
|
||||
admin_services.KeyValue = FakeKeyValue
|
||||
admin_services.refresh_settings = fake_refresh_settings
|
||||
FakeKeyValue.saved_value = None
|
||||
try:
|
||||
asyncio.run(ConfigService().update_config({"admin_token": "new-admin-password"}))
|
||||
finally:
|
||||
admin_services.KeyValue = original_key_value
|
||||
admin_services.refresh_settings = original_refresh_settings
|
||||
|
||||
self.assertIsNotNone(FakeKeyValue.saved_value)
|
||||
self.assertTrue(verify_password("new-admin-password", FakeKeyValue.saved_value["admin_token"]))
|
||||
self.assertNotEqual(FakeKeyValue.saved_value["jwt_secret"], old_secret)
|
||||
self.assertGreaterEqual(len(FakeKeyValue.saved_value["jwt_secret"]), 32)
|
||||
|
||||
def test_initialize_system_sets_admin_password_and_jwt_secret(self):
|
||||
original_key_value = core_config.KeyValue
|
||||
original_refresh_settings = core_config.refresh_settings
|
||||
FakeConfigKeyValue.record = FakeConfigRecord(
|
||||
{
|
||||
**copy.deepcopy(DEFAULT_CONFIG),
|
||||
"admin_token": "",
|
||||
"jwt_secret": "",
|
||||
}
|
||||
)
|
||||
FakeConfigKeyValue.saved_value = None
|
||||
core_config.KeyValue = FakeConfigKeyValue
|
||||
core_config.refresh_settings = fake_refresh_settings
|
||||
try:
|
||||
asyncio.run(
|
||||
core_config.initialize_system(
|
||||
admin_password="new-admin-password",
|
||||
site_name="我的文件快递柜",
|
||||
setup_options={
|
||||
"uploadSize": 50 * 1024 * 1024,
|
||||
"errorCount": 6,
|
||||
"expireStyle": ["day", "count"],
|
||||
},
|
||||
)
|
||||
)
|
||||
finally:
|
||||
core_config.KeyValue = original_key_value
|
||||
core_config.refresh_settings = original_refresh_settings
|
||||
|
||||
self.assertIsNotNone(FakeConfigKeyValue.saved_value)
|
||||
self.assertTrue(
|
||||
verify_password("new-admin-password", FakeConfigKeyValue.saved_value["admin_token"])
|
||||
)
|
||||
self.assertGreaterEqual(len(FakeConfigKeyValue.saved_value["jwt_secret"]), 32)
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["name"], "我的文件快递柜")
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["uploadSize"], 50 * 1024 * 1024)
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["errorCount"], 6)
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["expireStyle"], ["day", "count"])
|
||||
@@ -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()
|
||||
@@ -0,0 +1,33 @@
|
||||
import unittest
|
||||
|
||||
from core.settings import settings
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_client_config_uses_path_style_when_configured(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "path"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertEqual(config.signature_version, "s3v4")
|
||||
self.assertEqual(config.s3["addressing_style"], "path")
|
||||
|
||||
def test_client_config_ignores_invalid_addressing_style(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "invalid"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertIsNone(config.s3)
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from apps.admin.services import FileService
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FakeFileCode:
|
||||
def __init__(self):
|
||||
self.id = 1
|
||||
self.code = "ABC123"
|
||||
self.prefix = "report"
|
||||
self.suffix = ".txt"
|
||||
self.uuid_file_name = "report.txt"
|
||||
self.file_path = "share/data/2026/01/01/abc"
|
||||
self.size = 12
|
||||
self.text = None
|
||||
self.expired_at = datetime(2026, 1, 2, 12, 0, 0)
|
||||
self.expired_count = 3
|
||||
self.used_count = 0
|
||||
self.created_at = datetime(2026, 1, 1, 12, 0, 0)
|
||||
self.file_hash = "a" * 64
|
||||
self.is_chunked = False
|
||||
self.upload_id = None
|
||||
|
||||
async def is_expired(self):
|
||||
return False
|
||||
|
||||
|
||||
class AdminFileItemTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_build_admin_file_item_serializes_required_fields(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
now = datetime(2026, 1, 1, 13, 0, 0)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(FakeFileCode(), now=now))
|
||||
|
||||
self.assertEqual(item["id"], 1)
|
||||
self.assertEqual(item["name"], "report.txt")
|
||||
self.assertEqual(item["type"], "file")
|
||||
self.assertFalse(item["isExpired"])
|
||||
self.assertEqual(item["remainingDownloads"], 3)
|
||||
self.assertEqual(item["file_path"], "share/data/2026/01/01/abc")
|
||||
self.assertIn("never_retrieved", item["statusInsights"]["reasons"])
|
||||
self.assertEqual(item["statusInsights"]["metrics"]["ageSeconds"], 3600)
|
||||
|
||||
def test_build_admin_file_item_marks_expiring_soon(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
file_code = FakeFileCode()
|
||||
now = file_code.expired_at - timedelta(hours=2)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(file_code, now=now))
|
||||
|
||||
self.assertEqual(item["statusInsights"]["severity"], "warning")
|
||||
self.assertIn("expires_soon", item["statusInsights"]["reasons"])
|
||||
@@ -0,0 +1,31 @@
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.base.views import validate_file_type
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_allows_extensions_and_mime_patterns(self):
|
||||
settings.allowed_file_types = ["rar", ".zip", "image/*"]
|
||||
|
||||
validate_file_type("backup.RAR")
|
||||
validate_file_type("archive.zip")
|
||||
validate_file_type("avatar.bin", "image/png")
|
||||
|
||||
def test_rejects_disallowed_file_type(self):
|
||||
settings.allowed_file_types = ["rar"]
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
validate_file_type("payload.exe", "application/octet-stream")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 403)
|
||||
@@ -0,0 +1,34 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
import apps.base.views as views
|
||||
from apps.base.views import normalize_share_code
|
||||
|
||||
|
||||
class FakeFileCodes:
|
||||
seen_code = None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
cls.seen_code = kwargs.get("code")
|
||||
return cls()
|
||||
|
||||
async def first(self):
|
||||
return None
|
||||
|
||||
|
||||
class RetrieveCodeTests(unittest.TestCase):
|
||||
def test_normalize_share_code_strips_surrounding_whitespace(self):
|
||||
self.assertEqual(normalize_share_code(" 12345\n"), "12345")
|
||||
|
||||
def test_get_code_file_by_code_queries_normalized_code(self):
|
||||
original_file_codes = views.FileCodes
|
||||
views.FileCodes = FakeFileCodes
|
||||
try:
|
||||
has_file, message = asyncio.run(views.get_code_file_by_code(" 12345\n"))
|
||||
finally:
|
||||
views.FileCodes = original_file_codes
|
||||
|
||||
self.assertFalse(has_file)
|
||||
self.assertEqual(message, "文件不存在")
|
||||
self.assertEqual(FakeFileCodes.seen_code, "12345")
|
||||
@@ -0,0 +1,79 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.settings import BASE_DIR, settings
|
||||
from main import index, resolve_theme_file, theme_asset
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
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(
|
||||
"assets", self.get_theme_index_asset("themes/2023")
|
||||
)
|
||||
|
||||
settings.themesSelect = "themes/2024"
|
||||
theme_2024_asset = resolve_theme_file(
|
||||
"assets", self.get_theme_index_asset("themes/2024")
|
||||
)
|
||||
|
||||
self.assertIn("themes/2023/assets", str(theme_2023_asset))
|
||||
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
||||
|
||||
def test_rejects_theme_asset_path_traversal(self):
|
||||
settings.themesSelect = "themes/2024"
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
|
||||
def test_theme_asset_returns_404_for_missing_or_traversal_paths(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
|
||||
for asset_path in ("missing.js", "../../core/settings.py"):
|
||||
with self.subTest(asset_path=asset_path):
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(theme_asset(asset_path))
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
|
||||
response = asyncio.run(
|
||||
index(
|
||||
request=SimpleNamespace(
|
||||
url=SimpleNamespace(path="/theme-assets/missing.js")
|
||||
)
|
||||
)
|
||||
)
|
||||
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"
|
||||
|
||||
response = asyncio.run(index())
|
||||
html = response.body.decode("utf-8")
|
||||
|
||||
self.assertIn('src="/theme-assets/', html)
|
||||
self.assertIn('href="/theme-assets/', html)
|
||||
self.assertNotIn('src="/assets/', html)
|
||||
self.assertNotIn('href="/assets/', html)
|
||||
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class FakeS3Client:
|
||||
def __init__(self, list_response):
|
||||
self.list_response = list_response
|
||||
self.head_calls = 0
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
async def head_object(self, **kwargs):
|
||||
self.head_calls += 1
|
||||
raise RuntimeError("head not supported")
|
||||
|
||||
async def list_objects_v2(self, **kwargs):
|
||||
return self.list_response
|
||||
|
||||
|
||||
class S3FileExistsTests(unittest.TestCase):
|
||||
def test_file_exists_falls_back_to_list_objects(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertTrue(exists)
|
||||
self.assertEqual(client.head_calls, 3)
|
||||
|
||||
def test_file_exists_returns_false_when_missing(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertFalse(exists)
|
||||
@@ -0,0 +1,26 @@
|
||||
import unittest
|
||||
|
||||
from core.settings import settings
|
||||
from main import build_public_config, build_public_meta
|
||||
|
||||
|
||||
class AdminAddressPublicConfigTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
def test_admin_address_is_exposed_as_strict_binary_flag(self):
|
||||
cases = ((0, 0), (1, 1), ("0", 0), ("1", 1))
|
||||
|
||||
for configured_value, expected_value in cases:
|
||||
with self.subTest(configured_value=configured_value):
|
||||
settings.showAdminAddr = configured_value
|
||||
|
||||
public_value = build_public_config()["show_admin_address"]
|
||||
feature_value = build_public_meta()["features"]["adminAddressVisible"]
|
||||
|
||||
self.assertIs(type(public_value), int)
|
||||
self.assertEqual(public_value, expected_value)
|
||||
self.assertIs(feature_value, bool(expected_value))
|
||||
@@ -0,0 +1,218 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base import views
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
from core.utils import get_now, get_select_token
|
||||
from main import build_setup_page, parse_setup_options
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
direct_url_calls = 0
|
||||
|
||||
async def get_file_url(self, file_code):
|
||||
self.direct_url_calls += 1
|
||||
return "https://storage.example/reusable-url"
|
||||
|
||||
async def get_file_response(self, file_code):
|
||||
return {"downloaded": file_code.code}
|
||||
|
||||
|
||||
class FakeRateLimit:
|
||||
def __init__(self):
|
||||
self.seen_ips = []
|
||||
|
||||
def add_ip(self, ip):
|
||||
self.seen_ips.append(ip)
|
||||
|
||||
|
||||
class ShareUsageSecurityTests(unittest.TestCase):
|
||||
def test_new_installations_default_to_secret_codes(self):
|
||||
self.assertEqual(DEFAULT_CONFIG["code_generate_type"], "secret")
|
||||
self.assertEqual(
|
||||
parse_setup_options({"expireStyle": ["day"]})["code_generate_type"],
|
||||
"secret",
|
||||
)
|
||||
self.assertIn('<option value="secret" selected>', build_setup_page())
|
||||
|
||||
def test_atomic_usage_download_and_metadata_limits(self):
|
||||
asyncio.run(self._run_scenario())
|
||||
|
||||
async def _run_scenario(self):
|
||||
original_config = dict(settings.user_config)
|
||||
original_metadata_limit = views.ip_limit["metadata"]
|
||||
settings.file_storage = "local"
|
||||
settings.jwt_secret = "test-download-secret"
|
||||
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()
|
||||
try:
|
||||
await self._assert_count_consumption_is_atomic()
|
||||
await self._assert_time_expiration_and_usage_are_atomic()
|
||||
await self._assert_download_url_is_single_use()
|
||||
await self._assert_text_share_downloads_as_txt()
|
||||
await self._assert_limited_files_do_not_expose_direct_urls()
|
||||
await self._assert_metadata_counts_all_attempts()
|
||||
finally:
|
||||
views.ip_limit["metadata"] = original_metadata_limit
|
||||
settings.user_config = original_config
|
||||
await Tortoise.close_connections()
|
||||
|
||||
async def _assert_count_consumption_is_atomic(self):
|
||||
record = await FileCodes.create(
|
||||
code="atomic",
|
||||
prefix="atomic",
|
||||
suffix=".txt",
|
||||
expired_count=1,
|
||||
expired_at=await get_now() + datetime.timedelta(days=1),
|
||||
)
|
||||
stale_copies = await asyncio.gather(
|
||||
*(FileCodes.get(id=record.id) for _ in range(20))
|
||||
)
|
||||
|
||||
consumed = await asyncio.gather(
|
||||
*(views.consume_file_usage(item) for item in stale_copies)
|
||||
)
|
||||
|
||||
await record.refresh_from_db()
|
||||
self.assertEqual(sum(consumed), 1)
|
||||
self.assertEqual(record.expired_count, 0)
|
||||
self.assertEqual(record.used_count, 1)
|
||||
|
||||
async def _assert_time_expiration_and_usage_are_atomic(self):
|
||||
valid = await FileCodes.create(
|
||||
code="time-valid",
|
||||
text="valid",
|
||||
expired_count=-1,
|
||||
expired_at=await get_now() + datetime.timedelta(minutes=5),
|
||||
)
|
||||
expired = await FileCodes.create(
|
||||
code="time-expired",
|
||||
text="expired",
|
||||
expired_count=-1,
|
||||
expired_at=await get_now() - datetime.timedelta(seconds=1),
|
||||
)
|
||||
valid_copies = await asyncio.gather(
|
||||
*(FileCodes.get(id=valid.id) for _ in range(20))
|
||||
)
|
||||
|
||||
consumed = await asyncio.gather(
|
||||
*(views.consume_file_usage(item) for item in valid_copies)
|
||||
)
|
||||
|
||||
self.assertTrue(all(consumed))
|
||||
self.assertFalse(await views.consume_file_usage(expired))
|
||||
await valid.refresh_from_db()
|
||||
await expired.refresh_from_db()
|
||||
self.assertEqual(valid.expired_count, -1)
|
||||
self.assertEqual(valid.used_count, 20)
|
||||
self.assertEqual(expired.used_count, 0)
|
||||
|
||||
async def _assert_download_url_is_single_use(self):
|
||||
record = await FileCodes.create(
|
||||
code="single-use",
|
||||
prefix="report",
|
||||
suffix=".pdf",
|
||||
expired_count=1,
|
||||
expired_at=await get_now() + datetime.timedelta(days=1),
|
||||
)
|
||||
key = await get_select_token(record.code)
|
||||
|
||||
with patch.dict(views.storages, {"local": FakeStorage}):
|
||||
selected = await views.select_file(
|
||||
data=views.SelectFileModel(code=record.code), ip="127.0.0.1"
|
||||
)
|
||||
await record.refresh_from_db()
|
||||
self.assertEqual(selected.detail["expired_count"], 1)
|
||||
self.assertEqual(record.expired_count, 1)
|
||||
self.assertEqual(record.used_count, 0)
|
||||
|
||||
first = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
|
||||
second = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
|
||||
|
||||
self.assertEqual(first, {"downloaded": record.code})
|
||||
self.assertEqual(second.code, 404)
|
||||
await record.refresh_from_db()
|
||||
self.assertEqual(record.expired_count, 0)
|
||||
self.assertEqual(record.used_count, 1)
|
||||
|
||||
async def _assert_text_share_downloads_as_txt(self):
|
||||
record = await FileCodes.create(
|
||||
code="text-download",
|
||||
prefix="TAG",
|
||||
text="hello, 文本直链",
|
||||
expired_count=-1,
|
||||
expired_at=None,
|
||||
)
|
||||
|
||||
with patch.dict(views.storages, {"local": FakeStorage}):
|
||||
response = await views.get_code_file(
|
||||
code=record.code, ip="127.0.0.1"
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.body.decode("utf-8"), record.text)
|
||||
self.assertEqual(response.media_type, "text/plain")
|
||||
self.assertEqual(
|
||||
response.headers["content-disposition"],
|
||||
"attachment; filename*=UTF-8''TAG.txt",
|
||||
)
|
||||
await record.refresh_from_db()
|
||||
self.assertEqual(record.used_count, 1)
|
||||
|
||||
async def _assert_limited_files_do_not_expose_direct_urls(self):
|
||||
record = await FileCodes.create(
|
||||
code="proxy-only",
|
||||
prefix="archive",
|
||||
suffix=".zip",
|
||||
expired_count=2,
|
||||
expired_at=await get_now() + datetime.timedelta(days=1),
|
||||
)
|
||||
storage = FakeStorage()
|
||||
|
||||
detail = await views.build_select_detail(record, storage)
|
||||
|
||||
self.assertTrue(detail["download_url"].startswith("/share/download?"))
|
||||
self.assertEqual(storage.direct_url_calls, 0)
|
||||
|
||||
async def _assert_metadata_counts_all_attempts(self):
|
||||
await FileCodes.create(
|
||||
code="metadata",
|
||||
text="hello",
|
||||
expired_count=-1,
|
||||
expired_at=None,
|
||||
)
|
||||
limiter = FakeRateLimit()
|
||||
views.ip_limit["metadata"] = limiter
|
||||
|
||||
success = await views.get_file_metadata(code="metadata", ip="192.0.2.1")
|
||||
missing = await views.get_file_metadata(code="missing", ip="192.0.2.1")
|
||||
|
||||
self.assertEqual(success.code, 200)
|
||||
self.assertEqual(missing.code, 404)
|
||||
self.assertEqual(limiter.seen_ips, ["192.0.2.1", "192.0.2.1"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,91 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base.models import FileCodes, StorageReservation
|
||||
from apps.base.quota import get_storage_usage, release_storage, reserve_storage
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
class StorageQuotaTests(unittest.TestCase):
|
||||
def test_quota_reservations_are_atomic_and_reusable(self):
|
||||
asyncio.run(self._run_scenario())
|
||||
|
||||
async def _run_scenario(self):
|
||||
original_config = dict(settings.user_config)
|
||||
settings.storageLimit = 100
|
||||
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()
|
||||
try:
|
||||
await FileCodes.create(code="existing", size=60, expired_count=-1)
|
||||
|
||||
results = await asyncio.gather(
|
||||
reserve_storage("upload-a", 30, 300),
|
||||
reserve_storage("upload-b", 30, 300),
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
self.assertEqual(sum(result is None for result in results), 1)
|
||||
rejected = [result for result in results if isinstance(result, HTTPException)]
|
||||
self.assertEqual(len(rejected), 1)
|
||||
self.assertEqual(rejected[0].status_code, 507)
|
||||
|
||||
usage = await get_storage_usage()
|
||||
self.assertEqual(usage["used"], 60)
|
||||
self.assertEqual(usage["reserved"], 30)
|
||||
self.assertEqual(usage["available"], 10)
|
||||
|
||||
active = await StorageReservation.first()
|
||||
await release_storage(active.token)
|
||||
await reserve_storage("upload-c", 40, 300)
|
||||
self.assertEqual((await get_storage_usage())["available"], 0)
|
||||
|
||||
settings.storageLimit = 0
|
||||
await reserve_storage("unlimited", 10_000, 300)
|
||||
self.assertFalse(
|
||||
await StorageReservation.filter(token="unlimited").exists()
|
||||
)
|
||||
|
||||
settings.storageLimit = 100
|
||||
expired = await StorageReservation.get(token="upload-c")
|
||||
expired.expires_at = await get_now()
|
||||
await expired.save(update_fields=["expires_at"])
|
||||
await reserve_storage("upload-d", 40, 300)
|
||||
self.assertEqual((await get_storage_usage())["reserved"], 40)
|
||||
|
||||
await release_storage("upload-d")
|
||||
same_token_results = await asyncio.gather(
|
||||
*(reserve_storage("same-upload", 40, 300) for _ in range(10)),
|
||||
return_exceptions=True,
|
||||
)
|
||||
self.assertTrue(all(result is None for result in same_token_results))
|
||||
self.assertEqual(
|
||||
await StorageReservation.filter(token="same-upload").count(), 1
|
||||
)
|
||||
finally:
|
||||
settings.user_config = original_config
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,60 @@
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import core.logger as logger_module
|
||||
|
||||
|
||||
class LoggingConfigurationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.environment_patch = None
|
||||
|
||||
def tearDown(self):
|
||||
if self.environment_patch is not None:
|
||||
self.environment_patch.stop()
|
||||
importlib.reload(logger_module)
|
||||
|
||||
def reload_with_environment(self, values):
|
||||
self.environment_patch = patch.dict(os.environ, values, clear=True)
|
||||
self.environment_patch.start()
|
||||
return importlib.reload(logger_module)
|
||||
|
||||
def test_production_defaults_to_warning_and_disables_access_logs(self):
|
||||
module = self.reload_with_environment({"APP_ENV": "production"})
|
||||
|
||||
self.assertEqual(module.get_log_level_name(), "warning")
|
||||
self.assertEqual(module.logger.level, logging.WARNING)
|
||||
self.assertFalse(module.is_access_log_enabled())
|
||||
|
||||
def test_development_defaults_to_info_and_keeps_access_logs(self):
|
||||
module = self.reload_with_environment({"APP_ENV": "development"})
|
||||
|
||||
self.assertEqual(module.get_log_level_name(), "info")
|
||||
self.assertEqual(module.logger.level, logging.INFO)
|
||||
self.assertTrue(module.is_access_log_enabled())
|
||||
|
||||
def test_explicit_log_and_access_settings_override_environment_defaults(self):
|
||||
module = self.reload_with_environment(
|
||||
{"APP_ENV": "production", "LOG_LEVEL": "error", "ACCESS_LOG": "true"}
|
||||
)
|
||||
|
||||
self.assertEqual(module.get_log_level_name(), "error")
|
||||
self.assertEqual(module.logger.level, logging.ERROR)
|
||||
self.assertTrue(module.is_access_log_enabled())
|
||||
|
||||
def test_log_file_configuration_is_bounded_in_docker_compose(self):
|
||||
compose = Path("docker-compose.yml").read_text(encoding="utf-8")
|
||||
dockerfile = Path("Dockerfile").read_text(encoding="utf-8")
|
||||
|
||||
self.assertIn('max-size: "10m"', compose)
|
||||
self.assertIn('max-file: "3"', compose)
|
||||
self.assertIn('APP_ENV="production"', dockerfile)
|
||||
self.assertIn('LOG_LEVEL="warning"', dockerfile)
|
||||
self.assertIn("--no-access-log", dockerfile)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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())
|
||||
@@ -0,0 +1,141 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import HTTPException
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base import views
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.quota import _detect_sql_dialect, _sql_placeholders, reserve_storage
|
||||
from apps.base.utils import validate_expire_style
|
||||
from core.settings import settings
|
||||
from core.utils import get_select_token
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
async def get_file_url(self, file_code):
|
||||
return f"https://example.invalid/{file_code.code}"
|
||||
|
||||
async def get_file_response(self, file_code):
|
||||
return {"downloaded": file_code.code}
|
||||
|
||||
|
||||
class SecurityPatchTests(unittest.TestCase):
|
||||
def test_validate_expire_style_rejects_unknown_mode(self):
|
||||
original = dict(settings.user_config)
|
||||
try:
|
||||
settings.expireStyle = ["day", "count"]
|
||||
self.assertEqual(validate_expire_style("day"), "day")
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_expire_style("forever")
|
||||
self.assertEqual(ctx.exception.status_code, 400)
|
||||
finally:
|
||||
settings.user_config = original
|
||||
|
||||
def test_sql_placeholders_follow_dialect(self):
|
||||
asyncio.run(self._assert_sql_placeholders())
|
||||
|
||||
async def _assert_sql_placeholders(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",
|
||||
}
|
||||
)
|
||||
try:
|
||||
self.assertEqual(_detect_sql_dialect(), "sqlite")
|
||||
self.assertEqual(_sql_placeholders(3), ["?", "?", "?"])
|
||||
|
||||
with patch(
|
||||
"apps.base.quota._detect_sql_dialect", return_value="postgres"
|
||||
):
|
||||
self.assertEqual(_sql_placeholders(3), ["$1", "$2", "$3"])
|
||||
with patch("apps.base.quota._detect_sql_dialect", return_value="mysql"):
|
||||
self.assertEqual(_sql_placeholders(2), ["%s", "%s"])
|
||||
|
||||
# sqlite 下 reserve_storage 仍可正常工作
|
||||
settings.storageLimit = 100
|
||||
await Tortoise.generate_schemas()
|
||||
await reserve_storage("patch-token", 10, 300)
|
||||
finally:
|
||||
settings.storageLimit = 0
|
||||
await Tortoise.close_connections()
|
||||
|
||||
def test_download_token_accepts_previous_window(self):
|
||||
asyncio.run(self._assert_download_token_window())
|
||||
|
||||
async def _assert_download_token_window(self):
|
||||
original = dict(settings.user_config)
|
||||
settings.jwt_secret = "test-secret-key-for-token-window"
|
||||
now = 2_000_500 # 落在窗口 2000 内
|
||||
code = "ABCDE"
|
||||
with patch("core.utils.time.time", return_value=now):
|
||||
current = await get_select_token(code, offset=0)
|
||||
previous = await get_select_token(code, offset=1)
|
||||
|
||||
expected_current = hashlib.sha256(
|
||||
f"{code}{int(now / 1000)}000{settings.jwt_secret}".encode()
|
||||
).hexdigest()
|
||||
expected_previous = hashlib.sha256(
|
||||
f"{code}{int(now / 1000) - 1}000{settings.jwt_secret}".encode()
|
||||
).hexdigest()
|
||||
self.assertEqual(current, expected_current)
|
||||
self.assertEqual(previous, expected_previous)
|
||||
|
||||
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()
|
||||
try:
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
prefix="demo",
|
||||
suffix=".txt",
|
||||
expired_count=-1,
|
||||
size=1,
|
||||
)
|
||||
# 模拟请求进入下一窗口,但仍携带上一窗口 token
|
||||
next_window = now + 1000
|
||||
with patch("core.utils.time.time", return_value=next_window):
|
||||
with patch.dict(views.storages, {"local": FakeStorage}):
|
||||
result = await views.download_file(
|
||||
key=current, code=code, ip="127.0.0.1"
|
||||
)
|
||||
self.assertEqual(result, {"downloaded": code})
|
||||
finally:
|
||||
settings.user_config = original
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import asyncio
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.admin import views as admin_views
|
||||
from apps.admin.schemas import LoginData
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.file_validation import detect_file_kind, validate_file_magic, validate_file_type
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import settings
|
||||
from core.utils import hash_password
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_detects_common_signatures(self):
|
||||
self.assertEqual(detect_file_kind(b"\x89PNG\r\n\x1a\nxxxx").name, "png")
|
||||
self.assertEqual(detect_file_kind(b"\xff\xd8\xff\xe0xxxx").name, "jpg")
|
||||
self.assertEqual(detect_file_kind(b"%PDF-1.7").name, "pdf")
|
||||
self.assertEqual(detect_file_kind(b"PK\x03\x04xxxx").name, "zip")
|
||||
self.assertEqual(detect_file_kind(b"RIFF\x00\x00\x00\x00WEBPxxxx").name, "webp")
|
||||
self.assertEqual(detect_file_kind(b"\x00\x00\x00\x18ftypmp42").name, "mp4")
|
||||
|
||||
def test_rejects_extension_spoofing(self):
|
||||
settings.allowed_file_types = ["*"]
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_file_magic("photo.png", "image/png", b"MZ" + b"\x00" * 20)
|
||||
self.assertEqual(ctx.exception.status_code, 403)
|
||||
self.assertIn("扩展名", ctx.exception.detail)
|
||||
|
||||
def test_rejects_content_type_spoofing(self):
|
||||
settings.allowed_file_types = ["*"]
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_file_magic("blob.bin", "image/png", b"MZ" + b"\x00" * 20)
|
||||
self.assertEqual(ctx.exception.status_code, 403)
|
||||
|
||||
def test_accepts_matching_png(self):
|
||||
settings.allowed_file_types = [".png", "image/*"]
|
||||
validate_file_magic("a.png", "image/png", b"\x89PNG\r\n\x1a\nxxxx")
|
||||
|
||||
def test_whitelist_still_enforced(self):
|
||||
settings.allowed_file_types = [".png"]
|
||||
with self.assertRaises(HTTPException):
|
||||
validate_file_type("a.exe", "application/x-msdownload")
|
||||
|
||||
|
||||
class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
settings.admin_token = hash_password("correct-password-123")
|
||||
settings.jwt_secret = "j" * 48
|
||||
settings.loginCount = 3
|
||||
settings.loginMinute = 15
|
||||
self._original_login_limiter = ip_limit["login"]
|
||||
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
|
||||
|
||||
def tearDown(self):
|
||||
ip_limit["login"] = self._original_login_limiter
|
||||
super().tearDown()
|
||||
|
||||
@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"
|
||||
)
|
||||
|
||||
for _ in range(3):
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
asyncio.run(attempt("wrong-password"))
|
||||
self.assertEqual(ctx.exception.status_code, 401)
|
||||
|
||||
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
|
||||
|
||||
@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"
|
||||
)
|
||||
)
|
||||
self.assertIn("token", result.detail)
|
||||
self.assertTrue(ip_limit["login"].check_ip("198.51.100.8"))
|
||||
|
||||
|
||||
class DockerRuntimeUserTests(unittest.TestCase):
|
||||
def test_dockerfile_defaults_to_root_for_volume_compatibility(self):
|
||||
# 默认 root:兼容已有 data 卷权限;如需非 root 可由编排层自行指定 user
|
||||
text = Path("Dockerfile").read_text()
|
||||
self.assertNotIn("USER appuser", text)
|
||||
compose = Path("docker-compose.yml").read_text()
|
||||
self.assertNotIn('user: "1000:1000"', compose)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,222 @@
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.datastructures import UploadFile
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base import views
|
||||
from apps.admin import dependencies as admin_dependencies
|
||||
from apps.admin.dependencies import create_token, verify_token
|
||||
from apps.admin.services import LocalFileClass
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from apps.base.schemas import CompleteUploadModel, InitChunkUploadModel
|
||||
from apps.base.utils import get_chunk_file_path_name
|
||||
from core.settings import data_root, settings
|
||||
from core.storage import SystemFileStorage
|
||||
from core.utils import hash_password, verify_password
|
||||
|
||||
|
||||
class PasswordCompareTests(unittest.TestCase):
|
||||
def test_verify_password_accepts_valid_hash(self):
|
||||
hashed = hash_password("s3cret-pass")
|
||||
self.assertTrue(verify_password("s3cret-pass", hashed))
|
||||
self.assertFalse(verify_password("wrong-pass", hashed))
|
||||
|
||||
def test_verify_password_supports_legacy_plaintext(self):
|
||||
self.assertTrue(verify_password("legacy", "legacy"))
|
||||
self.assertFalse(verify_password("legacy", "other"))
|
||||
|
||||
|
||||
class LocalFilePathTraversalTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmpdir = tempfile.TemporaryDirectory()
|
||||
self.local_root = Path(self._tmpdir.name) / "local"
|
||||
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(
|
||||
"core.settings.data_root", Path(self._tmpdir.name)
|
||||
)
|
||||
self._data_root_patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self._data_root_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_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.local_root / "safe.txt").resolve())
|
||||
|
||||
|
||||
class SystemStoragePathTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmpdir = tempfile.TemporaryDirectory()
|
||||
self.storage = SystemFileStorage()
|
||||
self.storage.root_path = Path(self._tmpdir.name)
|
||||
|
||||
def tearDown(self):
|
||||
self._tmpdir.cleanup()
|
||||
|
||||
def test_resolve_safe_path_blocks_escape(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.storage._resolve_safe_path("../etc/passwd")
|
||||
|
||||
def test_resolve_safe_path_blocks_internal_dotdot(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.storage._resolve_safe_path("share/data/2026/08/29/x/../../../../../../filecodebox.db")
|
||||
|
||||
def test_resolve_safe_path_blocks_windows_dotdot(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.storage._resolve_safe_path("share\\data\\..\\..\\filecodebox.db")
|
||||
|
||||
def test_resolve_safe_path_allows_nested(self):
|
||||
target = self.storage._resolve_safe_path("share/data/a/b.txt")
|
||||
self.assertTrue(str(target).startswith(str(Path(self._tmpdir.name).resolve())))
|
||||
|
||||
|
||||
class ChunkFileNameSanitizeTests(unittest.TestCase):
|
||||
def test_chunk_file_path_name_strips_traversal(self):
|
||||
path, _, _, filename, save_path = asyncio.run(
|
||||
get_chunk_file_path_name("../../../../../../filecodebox.db", "a" * 32)
|
||||
)
|
||||
self.assertNotIn("..", save_path)
|
||||
self.assertEqual(filename, "filecodebox.db")
|
||||
self.assertEqual(save_path, f"{path}/filecodebox.db")
|
||||
self.assertIn("a" * 32, path)
|
||||
|
||||
def test_chunk_file_path_name_strips_windows_traversal(self):
|
||||
_, _, _, filename, save_path = asyncio.run(
|
||||
get_chunk_file_path_name("..\\..\\..\\..\\..\\..\\evil.bin", "b" * 32)
|
||||
)
|
||||
self.assertNotIn("..", save_path)
|
||||
self.assertEqual(filename, "evil.bin")
|
||||
|
||||
def test_chunk_file_path_name_keeps_normal_name(self):
|
||||
_, _, _, filename, save_path = asyncio.run(
|
||||
get_chunk_file_path_name("safe.txt", "c" * 32)
|
||||
)
|
||||
self.assertEqual(filename, "safe.txt")
|
||||
self.assertTrue(save_path.endswith("/safe.txt"))
|
||||
|
||||
|
||||
class ChunkUploadMetadataTests(unittest.TestCase):
|
||||
def test_traversal_filename_remains_downloadable_after_completion(self):
|
||||
asyncio.run(self._run_traversal_upload())
|
||||
|
||||
async def _run_traversal_upload(self):
|
||||
original_config = dict(settings.user_config)
|
||||
tmpdir = tempfile.TemporaryDirectory()
|
||||
try:
|
||||
settings.file_storage = "local"
|
||||
settings.allowed_file_types = ["*"]
|
||||
with patch("core.storage.data_root", Path(tmpdir.name)):
|
||||
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()
|
||||
try:
|
||||
raw_name = "../../../../../../filecodebox.db"
|
||||
payload = b"chunk payload"
|
||||
init_result = await views.init_chunk_upload(
|
||||
InitChunkUploadModel(
|
||||
file_name=raw_name,
|
||||
file_size=len(payload),
|
||||
chunk_size=1024,
|
||||
file_hash="f" * 64,
|
||||
)
|
||||
)
|
||||
upload_id = init_result.detail["upload_id"]
|
||||
session = await UploadChunk.get(
|
||||
upload_id=upload_id, chunk_index=-1
|
||||
)
|
||||
self.assertEqual(session.file_name, "filecodebox.db")
|
||||
self.assertNotIn("..", session.save_path)
|
||||
|
||||
await views.upload_chunk(
|
||||
upload_id=upload_id,
|
||||
chunk_index=0,
|
||||
chunk=UploadFile(
|
||||
file=BytesIO(payload), filename="filecodebox.db"
|
||||
),
|
||||
)
|
||||
|
||||
# Simulate a legacy session whose display name was not sanitized.
|
||||
session.file_name = raw_name
|
||||
await session.save(update_fields=["file_name"])
|
||||
|
||||
complete_result = await views.complete_upload(
|
||||
upload_id=upload_id,
|
||||
data=CompleteUploadModel(
|
||||
expire_value=1, expire_style="day"
|
||||
),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
self.assertEqual(complete_result.detail["name"], "filecodebox.db")
|
||||
|
||||
file_code = await FileCodes.get(code=complete_result.detail["code"])
|
||||
expected_relative_path = session.save_path
|
||||
self.assertEqual(
|
||||
await file_code.get_file_path(), expected_relative_path
|
||||
)
|
||||
storage = views.storages[settings.file_storage]()
|
||||
resolved_path = storage._resolve_safe_path(
|
||||
await file_code.get_file_path()
|
||||
)
|
||||
self.assertEqual(
|
||||
resolved_path, Path(tmpdir.name).resolve() / expected_relative_path
|
||||
)
|
||||
self.assertEqual(resolved_path.read_bytes(), payload)
|
||||
finally:
|
||||
await Tortoise.close_connections()
|
||||
finally:
|
||||
settings.user_config = original_config
|
||||
tmpdir.cleanup()
|
||||
|
||||
|
||||
class AdminJwtUrlSafeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
settings.jwt_secret = "j" * 48
|
||||
|
||||
def test_create_and_verify_roundtrip(self):
|
||||
token = create_token({"is_admin": True}, expires_in=60)
|
||||
# urlsafe token 不应依赖标准 base64 填充字符
|
||||
self.assertNotIn("+", token)
|
||||
self.assertNotIn("/", token)
|
||||
payload = verify_token(token)
|
||||
self.assertTrue(payload["is_admin"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.admin.services import FileService
|
||||
from apps.base.models import FileCodes, ShareCodeReservations
|
||||
|
||||
|
||||
class ShareCodeReservationTests(unittest.TestCase):
|
||||
def test_restore_keeps_original_code_and_releases_own_reservation(self):
|
||||
asyncio.run(self.scenario())
|
||||
|
||||
async def scenario(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()
|
||||
try:
|
||||
item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text")
|
||||
service = FileService()
|
||||
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(
|
||||
code="MANUALOLD",
|
||||
defaults={"file_code_id": item.id, "reason": "manual_update"},
|
||||
)
|
||||
self.assertTrue(await ShareCodeReservations.filter(code="MANUALOLD").exists())
|
||||
finally:
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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)
|
||||
@@ -0,0 +1,40 @@
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from core.version import APP_VERSION, VERSION_FILE, load_app_version
|
||||
from main import app
|
||||
|
||||
|
||||
class ApplicationVersionTests(unittest.TestCase):
|
||||
def test_version_file_is_the_runtime_version_source(self):
|
||||
version = VERSION_FILE.read_text(encoding="utf-8").strip()
|
||||
|
||||
self.assertRegex(version, r"^\d+\.\d+\.\d+$")
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(load_app_version(), version)
|
||||
self.assertEqual(app.version, APP_VERSION)
|
||||
|
||||
def test_release_manifest_matches_version_file(self):
|
||||
manifest_file = VERSION_FILE.parent / ".release-please-manifest.json"
|
||||
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
|
||||
|
||||
self.assertEqual(manifest["."], VERSION_FILE.read_text(encoding="utf-8").strip())
|
||||
|
||||
def test_build_can_override_version_with_environment(self):
|
||||
for version in ("9.8.7", "9.8.7-dev+abc123"):
|
||||
with self.subTest(version=version):
|
||||
with patch.dict(os.environ, {"APP_VERSION": version}):
|
||||
self.assertEqual(load_app_version(), version)
|
||||
|
||||
def test_rejects_non_canonical_versions(self):
|
||||
for version in ("v2.4.0", "2.4", "2.4.0 beta"):
|
||||
with self.subTest(version=version):
|
||||
with patch.dict(os.environ, {"APP_VERSION": version}):
|
||||
with self.assertRaises(RuntimeError):
|
||||
load_app_version()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user