* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理 * 保护上传终态与分享事务,清理失败保留会话并支持安全重试 * 统一下载响应头,兼容旧下载器并防止文件名注入 * 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略 * 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数 * 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置 * 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
126 lines
7.5 KiB
Python
126 lines
7.5 KiB
Python
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()
|