✨ feat: 整合 2.8.5 后端存储、安全与运行优化
* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理 * 保护上传终态与分享事务,清理失败保留会话并支持安全重试 * 统一下载响应头,兼容旧下载器并防止文件名注入 * 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略 * 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数 * 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置 * 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
This commit is contained in:
1 parent
b2a9aeddb3
commit
41519afb6a
29 files changed
+1033
-132
No files matched your search
@@ -0,0 +1,49 @@
|
||||
"""Issue #531: keep a legacy filename alongside the RFC 5987 UTF-8 name."""
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.base import local_share, views
|
||||
from apps.base.models import FileCodes
|
||||
from core.settings import settings
|
||||
from core.storage import build_attachment_headers
|
||||
|
||||
|
||||
def legacy_filename(disposition):
|
||||
match = re.search(r'(?:^|;\s*)filename="([^"]+)"', disposition)
|
||||
assert match is not None, "legacy download clients cannot read filename*"
|
||||
return match.group(1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("filename", "fallback"),
|
||||
[
|
||||
("report.pdf", "report.pdf"),
|
||||
("my archive.tar.gz", "my archive.tar.gz"),
|
||||
("报告.pdf", "__.pdf"),
|
||||
("图像 🖼.png", "__ _.png"),
|
||||
("", "download"),
|
||||
],
|
||||
)
|
||||
def test_attachment_has_legacy_and_utf8_filenames(filename, fallback):
|
||||
headers = build_attachment_headers(filename, 42)
|
||||
disposition = headers["Content-Disposition"]
|
||||
assert disposition.startswith("attachment;")
|
||||
assert legacy_filename(disposition) == fallback
|
||||
assert disposition.endswith("filename*=UTF-8''" + quote(filename, safe=""))
|
||||
assert headers["Content-Length"] == "42"
|
||||
assert disposition.isascii()
|
||||
|
||||
|
||||
def test_legacy_fallback_cannot_inject_parameters_headers_or_paths():
|
||||
filename = '../bad\\name"; inline;\r\nX-Evil: true\x00%20.html'
|
||||
disposition = build_attachment_headers(filename)["Content-Disposition"]
|
||||
fallback = legacy_filename(disposition)
|
||||
assert re.fullmatch(r"[A-Za-z0-9._ -]+", fallback)
|
||||
assert not fallback.startswith(".")
|
||||
assert fallback.endswith(".html")
|
||||
assert "\r" not in disposition and "\n" not in disposition and "\x00" not in disposition
|
||||
assert len(disposition.split(";")) == 3
|
||||
assert unquote(disposition.split("filename*=UTF-8''", 1)[1]) == filename
|
||||
@@ -0,0 +1,82 @@
|
||||
"""index.html render cache must stay correct across config/theme changes."""
|
||||
import asyncio
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
import main as pages
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class IndexRenderCacheTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
self._original_resolve_theme_file = pages.resolve_theme_file
|
||||
self._tmpdir = tempfile.TemporaryDirectory()
|
||||
self.template = Path(self._tmpdir.name) / "index.html"
|
||||
self.template.write_text(
|
||||
"<title>{{title}}</title>"
|
||||
'<meta name="description" content="{{description}}">'
|
||||
"<div>{{opacity}}</div>",
|
||||
encoding="utf-8",
|
||||
)
|
||||
pages.resolve_theme_file = lambda *args, **kwargs: self.template
|
||||
pages._render_index_html.cache_clear()
|
||||
|
||||
def tearDown(self):
|
||||
pages.resolve_theme_file = self._original_resolve_theme_file
|
||||
settings.user_config = self._original_user_config
|
||||
pages._render_index_html.cache_clear()
|
||||
self._tmpdir.cleanup()
|
||||
|
||||
def _render(self) -> str:
|
||||
return asyncio.run(pages.index()).body.decode("utf-8")
|
||||
|
||||
def test_repeated_requests_hit_the_render_cache(self):
|
||||
first = self._render()
|
||||
second = self._render()
|
||||
|
||||
self.assertEqual(first, second)
|
||||
info = pages._render_index_html.cache_info()
|
||||
self.assertEqual(info.misses, 1)
|
||||
self.assertEqual(info.hits, 1)
|
||||
|
||||
def test_site_config_change_invalidates_cache(self):
|
||||
self._render()
|
||||
|
||||
settings.name = "New Site Name"
|
||||
html = self._render()
|
||||
|
||||
self.assertIn("<title>New Site Name</title>", html)
|
||||
self.assertEqual(pages._render_index_html.cache_info().misses, 2)
|
||||
|
||||
def test_template_replacement_invalidates_cache(self):
|
||||
self._render()
|
||||
old_stat = self.template.stat()
|
||||
|
||||
self.template.write_text(
|
||||
"<title>{{title}}</title><p>rebuilt</p>", encoding="utf-8"
|
||||
)
|
||||
os.utime(
|
||||
self.template,
|
||||
ns=(old_stat.st_atime_ns, old_stat.st_mtime_ns + 1_000_000),
|
||||
)
|
||||
|
||||
html = self._render()
|
||||
self.assertIn("<p>rebuilt</p>", html)
|
||||
self.assertEqual(pages._render_index_html.cache_info().misses, 2)
|
||||
|
||||
def test_missing_template_still_404s_instead_of_serving_cache(self):
|
||||
self._render()
|
||||
self.template.unlink()
|
||||
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
asyncio.run(pages.index())
|
||||
self.assertEqual(ctx.exception.status_code, 404)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,70 @@
|
||||
import asyncio
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import main as pages
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class IndexTemplateEscapingTests(unittest.TestCase):
|
||||
"""Regression: site config must be html.escape-d before template injection
|
||||
(stored XSS prevention).
|
||||
|
||||
Uses a temp file as a stand-in for themes/*/index.html so the test also
|
||||
runs in a bare checkout without built frontends.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
self._original_resolve_theme_file = pages.resolve_theme_file
|
||||
pages._render_index_html.cache_clear()
|
||||
tmp = tempfile.NamedTemporaryFile(
|
||||
"w", suffix=".html", delete=False, encoding="utf-8"
|
||||
)
|
||||
tmp.write(
|
||||
"<title>{{title}}</title>"
|
||||
'<meta name="description" content="{{description}}">'
|
||||
"<div>{{opacity}}</div>"
|
||||
)
|
||||
tmp.close()
|
||||
self._template_path = Path(tmp.name)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
pages.resolve_theme_file = self._original_resolve_theme_file
|
||||
pages._render_index_html.cache_clear()
|
||||
self._template_path.unlink()
|
||||
|
||||
def _patch_template(self):
|
||||
pages.resolve_theme_file = lambda *args, **kwargs: self._template_path
|
||||
|
||||
def _render_index_html(self) -> str:
|
||||
return asyncio.run(pages.index()).body.decode("utf-8")
|
||||
|
||||
def test_malicious_site_config_is_escaped(self):
|
||||
self._patch_template()
|
||||
settings.name = "<script>alert(1)</script>"
|
||||
settings.description = '"><img src=x onerror=alert(2)>'
|
||||
|
||||
html = self._render_index_html()
|
||||
|
||||
self.assertNotIn("<script>alert", html)
|
||||
self.assertNotIn("<img", html)
|
||||
self.assertIn("<script>", html)
|
||||
|
||||
def test_plain_site_config_renders_unchanged(self):
|
||||
self._patch_template()
|
||||
settings.name = "FileCodeBox"
|
||||
settings.description = "A simple file share service"
|
||||
settings.opacity = 0.9
|
||||
|
||||
html = self._render_index_html()
|
||||
|
||||
self.assertIn("<title>FileCodeBox</title>", html)
|
||||
self.assertIn('content="A simple file share service"', html)
|
||||
self.assertIn("<div>0.9</div>", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -176,7 +176,7 @@ class ShareUsageSecurityTests(unittest.TestCase):
|
||||
self.assertEqual(response.media_type, "text/plain")
|
||||
self.assertEqual(
|
||||
response.headers["content-disposition"],
|
||||
"attachment; filename*=UTF-8''TAG.txt",
|
||||
'attachment; filename="TAG.txt"; filename*=UTF-8\'\'TAG.txt',
|
||||
)
|
||||
await record.refresh_from_db()
|
||||
self.assertEqual(record.used_count, 1)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""迁移 008 建立的索引存在且被查询计划实际选用。
|
||||
|
||||
跑真实迁移链(不 generate_schemas),与部署升级形态一致;用
|
||||
EXPLAIN QUERY PLAN 断言索引名出现在执行计划中,避免"建了索引但查询用不上"。
|
||||
"""
|
||||
import pytest
|
||||
from tortoise import Tortoise
|
||||
|
||||
import core.config as config_module
|
||||
from core.database import execute_migrations
|
||||
from tests.helpers import MEMORY_DB_CONFIG, close_db
|
||||
|
||||
INDEXES = {
|
||||
"idx_filecodes_expired_at",
|
||||
"idx_filecodes_created_at",
|
||||
"idx_uploadchunk_upload_chunk",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def migrated_db():
|
||||
config_module._config_cached_until = 0.0
|
||||
if Tortoise._inited:
|
||||
await Tortoise.close_connections()
|
||||
await Tortoise.init(config=MEMORY_DB_CONFIG)
|
||||
conn = Tortoise.get_connection("default")
|
||||
await conn.execute_script(
|
||||
"CREATE TABLE IF NOT EXISTS migrates ("
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"migration_file VARCHAR(255) NOT NULL UNIQUE, "
|
||||
"executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
|
||||
)
|
||||
await execute_migrations()
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
await close_db()
|
||||
|
||||
|
||||
async def _plan(conn, sql: str) -> str:
|
||||
_, rows = await conn.execute_query(f"EXPLAIN QUERY PLAN {sql}")
|
||||
return " | ".join(str(row["detail"]) for row in rows)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestMigrationIndexes:
|
||||
async def test_indexes_exist(self, migrated_db):
|
||||
_, rows = await migrated_db.execute_query(
|
||||
"SELECT name FROM sqlite_master WHERE type='index'"
|
||||
)
|
||||
names = {row["name"] for row in rows}
|
||||
assert INDEXES <= names
|
||||
|
||||
async def test_expiry_scan_uses_index(self, migrated_db):
|
||||
plan = await _plan(
|
||||
migrated_db,
|
||||
"SELECT id FROM filecodes WHERE expired_at < '2024-01-01 00:00:00'",
|
||||
)
|
||||
assert "idx_filecodes_expired_at" in plan
|
||||
|
||||
async def test_recent_listing_uses_created_at_index(self, migrated_db):
|
||||
plan = await _plan(
|
||||
migrated_db,
|
||||
"SELECT id FROM filecodes ORDER BY created_at DESC LIMIT 8",
|
||||
)
|
||||
assert "idx_filecodes_created_at" in plan
|
||||
|
||||
async def test_chunk_lookup_uses_composite_index(self, migrated_db):
|
||||
plan = await _plan(
|
||||
migrated_db,
|
||||
"SELECT chunk_index FROM uploadchunk "
|
||||
"WHERE upload_id = 'abc' AND chunk_index = 3",
|
||||
)
|
||||
assert "idx_uploadchunk_upload_chunk" in plan
|
||||
|
||||
async def test_chunk_cleanup_uses_upload_id_prefix(self, migrated_db):
|
||||
plan = await _plan(
|
||||
migrated_db,
|
||||
"DELETE FROM uploadchunk WHERE upload_id = 'abc'",
|
||||
)
|
||||
assert "idx_uploadchunk_upload_chunk" in plan
|
||||
@@ -0,0 +1,81 @@
|
||||
"""IPRateLimit is bounded and uses a monotonic clock."""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
|
||||
|
||||
class FakeClock:
|
||||
def __init__(self, now: float = 1000.0):
|
||||
self.now = now
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.now
|
||||
|
||||
|
||||
class IPRateLimitBoundsTests(unittest.TestCase):
|
||||
def test_first_add_returns_one(self):
|
||||
limiter = IPRateLimit(count=3, minutes=1)
|
||||
|
||||
self.assertEqual(limiter.add_ip("203.0.113.1"), 1)
|
||||
self.assertEqual(limiter.add_ip("203.0.113.1"), 2)
|
||||
|
||||
def test_capacity_evicts_least_recently_active_ip(self):
|
||||
limiter = IPRateLimit(count=10, minutes=1, max_ips=3)
|
||||
|
||||
for ip in ("a", "b", "c", "d"):
|
||||
limiter.add_ip(ip)
|
||||
|
||||
self.assertEqual(len(limiter.ips), 3)
|
||||
self.assertEqual(list(limiter.ips), ["b", "c", "d"])
|
||||
|
||||
def test_activity_refreshes_recency(self):
|
||||
limiter = IPRateLimit(count=10, minutes=1, max_ips=2)
|
||||
|
||||
limiter.add_ip("a")
|
||||
limiter.add_ip("b")
|
||||
limiter.add_ip("a")
|
||||
limiter.add_ip("c")
|
||||
|
||||
self.assertEqual(list(limiter.ips), ["a", "c"])
|
||||
|
||||
def test_window_blocks_then_resets(self):
|
||||
clock = FakeClock()
|
||||
with mock.patch("time.monotonic", clock):
|
||||
limiter = IPRateLimit(count=3, minutes=1)
|
||||
for _ in range(3):
|
||||
limiter.add_ip("198.51.100.9")
|
||||
|
||||
self.assertFalse(limiter.check_ip("198.51.100.9"))
|
||||
clock.now += 30
|
||||
self.assertFalse(limiter.check_ip("198.51.100.9"))
|
||||
clock.now += 31
|
||||
self.assertTrue(limiter.check_ip("198.51.100.9"))
|
||||
self.assertNotIn("198.51.100.9", limiter.ips)
|
||||
|
||||
def test_remove_expired_compacts_old_entries_only(self):
|
||||
clock = FakeClock()
|
||||
with mock.patch("time.monotonic", clock):
|
||||
limiter = IPRateLimit(count=10, minutes=1)
|
||||
limiter.add_ip("old")
|
||||
clock.now += 30
|
||||
limiter.add_ip("fresh")
|
||||
clock.now += 31
|
||||
|
||||
import asyncio
|
||||
|
||||
asyncio.run(limiter.remove_expired_ip())
|
||||
|
||||
self.assertEqual(list(limiter.ips), ["fresh"])
|
||||
|
||||
def test_record_count_is_bounded_under_ip_scan(self):
|
||||
limiter = IPRateLimit(count=10, minutes=1, max_ips=10_000)
|
||||
|
||||
for i in range(50_000):
|
||||
limiter.add_ip(f"10.0.{i // 256}.{i % 256}")
|
||||
|
||||
self.assertEqual(len(limiter.ips), 10_000)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,81 @@
|
||||
"""OSS compatibility regressions: real SDK request preparation, no external I/O."""
|
||||
from datetime import timedelta
|
||||
from unittest.mock import AsyncMock
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import aioboto3
|
||||
import pytest
|
||||
from botocore.exceptions import ClientError
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
from apps.base.models import FileCodes, StorageReservation, UploadChunk
|
||||
from core.settings import settings
|
||||
from core.storage import S3FileStorage
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage(monkeypatch):
|
||||
monkeypatch.setattr(settings, "user_config", {
|
||||
**settings.user_config, "file_storage": "s3", "uploadSize": 1024,
|
||||
"chunk_expire_hours": 24,
|
||||
})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "virtual"
|
||||
storage.bucket_name = "test-bucket"
|
||||
# Reserved .invalid domain; before-send hooks stop requests before any I/O.
|
||||
storage.endpoint_url = "https://oss-cn-hangzhou.example.invalid"
|
||||
storage.region_name = "oss-cn-hangzhou"
|
||||
storage.aws_session_token = None
|
||||
storage.session = aioboto3.Session(
|
||||
aws_access_key_id="testing", aws_secret_access_key="testing"
|
||||
)
|
||||
return storage
|
||||
|
||||
|
||||
def test_checksum_config_preserves_signature_and_addressing(storage):
|
||||
config = storage._client_config()
|
||||
assert config.request_checksum_calculation == "when_required"
|
||||
assert config.response_checksum_validation == "when_required"
|
||||
assert config.signature_version == "s3v4"
|
||||
assert config.s3["addressing_style"] == "virtual"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("operation", ["PutObject", "UploadPart"])
|
||||
async def test_sdk_upload_has_no_flexible_checksum_trailer(storage, monkeypatch, operation):
|
||||
monkeypatch.setenv("AWS_REQUEST_CHECKSUM_CALCULATION", "when_supported")
|
||||
monkeypatch.setenv("AWS_RESPONSE_CHECKSUM_VALIDATION", "when_supported")
|
||||
captured = []
|
||||
|
||||
class RequestCaptured(Exception):
|
||||
pass
|
||||
|
||||
def intercept(request, **kwargs):
|
||||
captured.append(request)
|
||||
raise RequestCaptured
|
||||
|
||||
# Register on the session so save_chunk's real _client() inherits the hook.
|
||||
storage.session.events.register(f"before-send.s3.{operation}", intercept)
|
||||
with pytest.raises(RequestCaptured):
|
||||
if operation == "PutObject":
|
||||
await storage.save_chunk("up", 0, b"payload", "hash", "share/file.bin")
|
||||
else:
|
||||
async with storage._client() as client:
|
||||
assert client.meta.config.response_checksum_validation == "when_required"
|
||||
await client.upload_part(
|
||||
Bucket=storage.bucket_name, Key="share/file.bin", UploadId="up",
|
||||
PartNumber=1, Body=b"payload",
|
||||
)
|
||||
assert len(captured) == 1
|
||||
request = captured[0]
|
||||
headers = {key.lower(): value for key, value in request.headers.items()}
|
||||
assert "x-amz-trailer" not in headers
|
||||
assert not any(key.startswith("x-amz-checksum-") for key in headers)
|
||||
assert "x-amz-sdk-checksum-algorithm" not in headers
|
||||
assert b"aws-chunked" not in headers.get("content-encoding", b"")
|
||||
assert b"TRAILER" not in headers.get("x-amz-content-sha256", b"")
|
||||
assert urlsplit(request.url).hostname == "test-bucket.oss-cn-hangzhou.example.invalid"
|
||||
assert not urlsplit(request.url).path.startswith("/test-bucket/")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""SQLite 连接 PRAGMA 生效性验证。
|
||||
|
||||
不 mock 配置字典,而是用 get_db_config() 真起一个文件库读取 PRAGMA——
|
||||
Tortoise 的 SqliteClient 在 create_connection() 时逐条执行 credentials 中的
|
||||
PRAGMA,只有真实连接才能验证这一点。
|
||||
"""
|
||||
import pytest
|
||||
from tortoise import Tortoise
|
||||
|
||||
import core.database as database
|
||||
from tests.helpers import close_db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def file_db(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(database, "_DB_FILE", str(tmp_path / "pragma.db"))
|
||||
if Tortoise._inited:
|
||||
await Tortoise.close_connections()
|
||||
await Tortoise.init(config=database.get_db_config())
|
||||
try:
|
||||
yield Tortoise.get_connection("default")
|
||||
finally:
|
||||
await close_db()
|
||||
|
||||
|
||||
async def _pragma(conn, statement: str):
|
||||
rows = await conn.execute_query_dict(statement)
|
||||
return next(iter(rows[0].values()))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestSqlitePragmas:
|
||||
async def test_wal_and_busy_timeout_kept(self, file_db):
|
||||
assert str(await _pragma(file_db, "PRAGMA journal_mode")).lower() == "wal"
|
||||
assert await _pragma(file_db, "PRAGMA busy_timeout") == 10000
|
||||
|
||||
async def test_synchronous_normal(self, file_db):
|
||||
# 1 = NORMAL(WAL 下省 fsync),2 = FULL
|
||||
assert await _pragma(file_db, "PRAGMA synchronous") == 1
|
||||
|
||||
async def test_temp_store_memory(self, file_db):
|
||||
# 0 = DEFAULT,1 = FILE,2 = MEMORY
|
||||
assert await _pragma(file_db, "PRAGMA temp_store") == 2
|
||||
|
||||
async def test_cache_size_8mb(self, file_db):
|
||||
# 负值单位为 KiB
|
||||
assert await _pragma(file_db, "PRAGMA cache_size") == -8000
|
||||
|
||||
async def test_foreign_keys_on(self, file_db):
|
||||
assert await _pragma(file_db, "PRAGMA foreign_keys") == 1
|
||||
@@ -0,0 +1,68 @@
|
||||
"""One Tortoise init path; ORM exception mappings still registered."""
|
||||
import asyncio
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from tortoise.exceptions import DoesNotExist, IntegrityError
|
||||
|
||||
import main
|
||||
|
||||
|
||||
async def _idle_task():
|
||||
# Stand-in for the real background loops; the lifespan cancels it on exit.
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
class StartupSingleInitTests(unittest.TestCase):
|
||||
def test_orm_exception_handlers_are_registered(self):
|
||||
# Behavior pinned by test_admin_write_paths: DoesNotExist -> 404 JSON.
|
||||
# IntegrityError -> 422 must stay available too.
|
||||
self.assertIn(DoesNotExist, main.app.exception_handlers)
|
||||
self.assertIn(IntegrityError, main.app.exception_handlers)
|
||||
|
||||
def test_register_tortoise_is_not_used(self):
|
||||
# register_tortoise merges another lifespan that calls Tortoise.init
|
||||
# before init_db(); batch 4 (SQLite PRAGMAs) needs a single init path.
|
||||
source = Path("main.py").read_text(encoding="utf-8")
|
||||
self.assertNotIn("import register_tortoise", source)
|
||||
self.assertNotIn("register_tortoise(", source)
|
||||
|
||||
def test_lifespan_does_not_initialize_tortoise_outside_init_db(self):
|
||||
async def scenario():
|
||||
init_db_calls = []
|
||||
|
||||
async def fake_init_db():
|
||||
init_db_calls.append(True)
|
||||
|
||||
async def fake_load_config():
|
||||
return None
|
||||
|
||||
with (
|
||||
mock.patch.object(main, "init_db", fake_init_db),
|
||||
mock.patch.object(main, "load_config", fake_load_config),
|
||||
mock.patch.object(main, "delete_expire_files", _idle_task),
|
||||
mock.patch.object(main, "clean_incomplete_uploads", _idle_task),
|
||||
mock.patch.object(
|
||||
main, "clean_expired_presign_sessions", _idle_task
|
||||
),
|
||||
mock.patch.object(main.Tortoise, "init") as tortoise_init,
|
||||
mock.patch.object(
|
||||
main.Tortoise, "close_connections"
|
||||
),
|
||||
):
|
||||
# FastAPI merges the lifespan of every included router, so use
|
||||
# the installed context rather than main.lifespan directly.
|
||||
async with main.app.router.lifespan_context(main.app):
|
||||
pass
|
||||
|
||||
return init_db_calls, tortoise_init
|
||||
|
||||
init_db_calls, tortoise_init = asyncio.run(scenario())
|
||||
|
||||
self.assertEqual(init_db_calls, [True])
|
||||
tortoise_init.assert_not_awaited()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Theme assets get a safe Cache-Control policy.
|
||||
|
||||
Fingerprinted (Vite) filenames can be cached immutably; public assets whose
|
||||
names do not change must use a short TTL so in-place upgrades are picked up.
|
||||
"""
|
||||
import asyncio
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import main as pages
|
||||
|
||||
|
||||
class ThemeAssetCacheTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._original_resolve_theme_file = pages.resolve_theme_file
|
||||
self._tmpdir = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self._tmpdir.name)
|
||||
(self.root / "assets").mkdir()
|
||||
pages.resolve_theme_file = lambda *parts: self.root.joinpath(*parts)
|
||||
|
||||
def tearDown(self):
|
||||
pages.resolve_theme_file = self._original_resolve_theme_file
|
||||
self._tmpdir.cleanup()
|
||||
|
||||
def _asset_response(self, name: str):
|
||||
(self.root / "assets" / name).write_bytes(b"x")
|
||||
return asyncio.run(pages.theme_asset(name))
|
||||
|
||||
def test_fingerprinted_asset_is_immutable(self):
|
||||
response = self._asset_response("index-BX2s1QqP.js")
|
||||
|
||||
self.assertIn("max-age=31536000", response.headers["cache-control"])
|
||||
self.assertIn("immutable", response.headers["cache-control"])
|
||||
|
||||
def test_plain_asset_gets_short_cache(self):
|
||||
response = self._asset_response("logo.png")
|
||||
|
||||
self.assertIn("max-age=86400", response.headers["cache-control"])
|
||||
self.assertNotIn("immutable", response.headers["cache-control"])
|
||||
|
||||
def test_short_hash_is_not_treated_as_fingerprint(self):
|
||||
self.assertEqual(
|
||||
pages._asset_cache_control("logo-2024.png"),
|
||||
pages._DEFAULT_ASSET_CACHE,
|
||||
)
|
||||
self.assertEqual(
|
||||
pages._asset_cache_control("index-BX2s1QqP.css"),
|
||||
pages._IMMUTABLE_ASSET_CACHE,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,125 @@
|
||||
import hashlib
|
||||
import io
|
||||
import unittest
|
||||
from contextlib import asynccontextmanager
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from apps.base import views
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from apps.base.schemas import CompleteUploadModel
|
||||
from core.settings import settings
|
||||
from core.storage import S3FileStorage, SystemFileStorage
|
||||
from tests.helpers import init_memory_db, close_db
|
||||
|
||||
class Upgrade285Tests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.original=dict(settings.user_config)
|
||||
settings.user_config={**settings.default_config,'file_storage':'local','uploadSize':1024}
|
||||
await init_memory_db()
|
||||
for limiter in views.ip_limit.values(): limiter.ips.clear()
|
||||
async def asyncTearDown(self):
|
||||
settings.user_config=self.original
|
||||
await close_db()
|
||||
async def seed(self):
|
||||
values=dict(upload_id='oss285',chunk_hash='a'*64,total_chunks=1,file_size=4,chunk_size=4,file_name='file.bin',save_path='share/file.bin')
|
||||
info=await UploadChunk.create(chunk_index=-1,**values)
|
||||
await UploadChunk.create(chunk_index=0,completed=True,**values)
|
||||
return info
|
||||
async def test_cancel_cleanup_failure_preserves_session(self):
|
||||
await self.seed()
|
||||
storage=SimpleNamespace(clean_chunks=AsyncMock(side_effect=RuntimeError('offline')))
|
||||
with patch.dict(views.storages,{'local':lambda:storage}):
|
||||
with self.assertRaises(HTTPException) as caught: await views.cancel_upload('oss285')
|
||||
self.assertEqual(caught.exception.status_code,503)
|
||||
self.assertEqual(await UploadChunk.filter(upload_id='oss285').count(),2)
|
||||
async def test_published_upload_returns_code_on_cleanup_failure_and_cannot_revive(self):
|
||||
await self.seed()
|
||||
storage=SimpleNamespace(clean_chunks=AsyncMock(side_effect=RuntimeError('offline')),merge_chunks=AsyncMock(return_value=('share/file.bin','a'*64)))
|
||||
with patch.dict(views.storages,{'local':lambda:storage}):
|
||||
result=await views._complete_upload('oss285',CompleteUploadModel(expire_value=1,expire_style='day'),'127.0.0.1')
|
||||
self.assertEqual(result.code,200)
|
||||
record=await FileCodes.get(upload_id='oss285')
|
||||
self.assertEqual(result.detail['code'],record.code)
|
||||
result=await views._complete_upload('oss285',CompleteUploadModel(expire_value=1,expire_style='day'),'127.0.0.1')
|
||||
self.assertEqual(result.detail['code'],record.code)
|
||||
self.assertEqual(storage.merge_chunks.await_count,1)
|
||||
self.assertTrue((await UploadChunk.get(upload_id='oss285',chunk_index=-1)).completed)
|
||||
await record.delete()
|
||||
with self.assertRaises(HTTPException) as caught:
|
||||
await views._complete_upload('oss285',CompleteUploadModel(expire_value=1,expire_style='day'),'127.0.0.1')
|
||||
self.assertEqual(caught.exception.status_code,409)
|
||||
with self.assertRaises(HTTPException) as caught:
|
||||
await views.upload_chunk('oss285',0,UploadFile(file=io.BytesIO(b'data'),filename='file.bin'))
|
||||
self.assertEqual(caught.exception.status_code,409)
|
||||
status=await views.get_upload_status('oss285')
|
||||
self.assertEqual(status.detail['uploaded_chunks'],[0])
|
||||
async def test_s3_cleanup_keeps_neighbor_and_surfaces_failure(self):
|
||||
storage=S3FileStorage()
|
||||
keys={'share/chunks/up/0.part','share/chunks/up-other/0.part','share/file.bin'}
|
||||
class Client:
|
||||
def get_paginator(self,name):return self
|
||||
async def paginate(self,**kw):
|
||||
yield {'Contents':[{'Key':k} for k in sorted(keys) if k.startswith(kw['Prefix'])]}
|
||||
async def delete_object(self,**kw):keys.remove(kw['Key'])
|
||||
@asynccontextmanager
|
||||
async def client():yield Client()
|
||||
with patch.object(storage,'_client',client): await storage.clean_chunks('up','share/file.bin')
|
||||
self.assertEqual(keys,{'share/chunks/up-other/0.part','share/file.bin'})
|
||||
class BadClient(Client):
|
||||
async def paginate(self,**kw):
|
||||
raise RuntimeError('offline')
|
||||
yield
|
||||
@asynccontextmanager
|
||||
async def bad_client():yield BadClient()
|
||||
with patch.object(storage,'_client',bad_client),self.assertRaises(RuntimeError):await storage.clean_chunks('up','share/file.bin')
|
||||
async def test_s3_config_avoids_unsupported_checksums(self):
|
||||
config=S3FileStorage()._client_config()
|
||||
self.assertEqual(config.request_checksum_calculation,'when_required')
|
||||
self.assertEqual(config.response_checksum_validation,'when_required')
|
||||
async def test_download_legacy_name_preserves_extension(self):
|
||||
from tempfile import TemporaryDirectory
|
||||
from pathlib import Path
|
||||
with TemporaryDirectory() as tmp:
|
||||
Path(tmp,'报告.apk').write_bytes(b'apk')
|
||||
storage=SystemFileStorage();storage.root_path=Path(tmp)
|
||||
response=await storage.get_file_response(FileCodes(file_path='',uuid_file_name='报告.apk',prefix='报告',suffix='.apk'))
|
||||
disposition=response.headers['content-disposition']
|
||||
self.assertIn('filename="__.apk"',disposition)
|
||||
self.assertIn("filename*=UTF-8''%E6%8A%A5%E5%91%8A.apk",disposition)
|
||||
|
||||
class LocalCleanupFailureTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_actual_storage_cleanup_propagates_failure(self):
|
||||
from tempfile import TemporaryDirectory
|
||||
from pathlib import Path
|
||||
with TemporaryDirectory() as tmp:
|
||||
storage=SystemFileStorage();storage.root_path=Path(tmp)
|
||||
Path(tmp,'share/chunks/up').mkdir(parents=True)
|
||||
with patch('core.storage.shutil.rmtree',side_effect=PermissionError('read only')):
|
||||
with self.assertRaises(PermissionError): await storage.clean_chunks('up','share/file.bin')
|
||||
async def test_opendal_cleanup_propagates_failure(self):
|
||||
from core.storage import OpenDALFileStorage
|
||||
storage=OpenDALFileStorage.__new__(OpenDALFileStorage)
|
||||
storage.operator=SimpleNamespace(remove_all=AsyncMock(side_effect=PermissionError('read only')))
|
||||
with self.assertRaises(PermissionError): await storage.clean_chunks('up','share/file.bin')
|
||||
|
||||
class LegacyDavCleanupTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_http_delete_failure_keeps_retry_error(self):
|
||||
from aiohttp import web
|
||||
from core.storage import WebDAVFileStorage
|
||||
old=dict(settings.user_config)
|
||||
app=web.Application()
|
||||
async def handle(request):
|
||||
if request.method=='PROPFIND':return web.Response(status=207,text='<D:href>/dav/share/chunks/up/0.part</D:href>')
|
||||
return web.Response(status=503)
|
||||
app.router.add_route('*','/dav/{path:.*}',handle)
|
||||
runner=web.AppRunner(app);await runner.setup();site=web.TCPSite(runner,'127.0.0.1',0);await site.start()
|
||||
port=site._server.sockets[0].getsockname()[1]
|
||||
settings.user_config={**settings.default_config,'webdav_url':f'http://127.0.0.1:{port}/dav','webdav_username':'test','webdav_password':'test'}
|
||||
storage=WebDAVFileStorage()
|
||||
try:
|
||||
with patch.object(storage,'_native_session',AsyncMock(return_value=None)),patch.object(storage,'_stream_session',AsyncMock(return_value=None)),patch.object(storage,'_offset_session',AsyncMock(return_value=None)):
|
||||
with self.assertRaises(HTTPException):await storage.clean_chunks('up','share/file.bin')
|
||||
finally:
|
||||
settings.user_config=old;await runner.cleanup()
|
||||
Reference in new issue
Block a user