✨ feat: 整合 2.8.5 后端存储、安全与运行优化

* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理
* 保护上传终态与分享事务,清理失败保留会话并支持安全重试
* 统一下载响应头,兼容旧下载器并防止文件名注入
* 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略
* 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数
* 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置
* 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
This commit is contained in:
orion committed 2026-10-29 16:37:14 +08:00
1 parent b2a9aeddb3
commit 41519afb6a
29 files changed
+1033 -132

No files matched your search

+43 -39
View File
@@ -29,6 +29,27 @@ from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
def build_attachment_headers(filename: str, content_length=None) -> dict:
"""所有存储后端统一的下载响应头。
Content-Disposition: attachment 是防御存储型 XSS 的关键——同源下载路径
(/share/download)因此永不内联渲染 HTML/SVG。此函数是唯一构造点,
新增后端必须复用此响应头构造。
"""
# Older Android download managers ignore filename*. Keep an ASCII fallback
# with the extension, without allowing quoted-string/header injection.
fallback = re.sub(r"[^A-Za-z0-9._ -]", "_", filename).strip(" .") or "download"
encoded_filename = quote(filename, safe="")
headers = {
"Content-Disposition": (
f'attachment; filename="{fallback}"; filename*=UTF-8\'\'{encoded_filename}'
)
}
if content_length is not None:
headers["Content-Length"] = str(content_length)
return headers
class FileStorageInterface:
async def save_file(self, file: UploadFile, save_path: str):
@@ -176,11 +197,9 @@ class SystemFileStorage(FileStorageInterface):
if not file_path.exists():
return APIResponse(code=404, detail="文件已过期删除")
filename = f"{file_code.prefix}{file_code.suffix}"
encoded_filename = quote(filename, safe='')
content_disposition = f"attachment; filename*=UTF-8''{encoded_filename}"
# 尝试获取文件系统大小,如果成功则设置 Content-Length
headers = {"Content-Disposition": content_disposition}
headers = build_attachment_headers(filename)
try:
content_length = file_path.stat().st_size
headers["Content-Length"] = str(content_length)
@@ -280,6 +299,7 @@ class SystemFileStorage(FileStorageInterface):
shutil.rmtree(chunk_dir)
except Exception as e:
logger.warning(f"清理本地分片目录失败: {e}")
raise
# 清理父级 chunks 目录(如果为空)
chunks_parent = chunk_dir.parent
if chunks_parent.exists() and not any(chunks_parent.iterdir()):
@@ -324,7 +344,7 @@ class S3FileStorage(FileStorageInterface):
self.endpoint_url = settings.s3_endpoint_url
def _client_config(self) -> Config:
config = {"signature_version": self.signature_version}
config = {"signature_version": self.signature_version, "request_checksum_calculation": "when_required", "response_checksum_validation": "when_required"}
s3_config = {}
if self.addressing_style in {"path", "virtual", "auto"}:
s3_config["addressing_style"] = self.addressing_style
@@ -409,10 +429,7 @@ class S3FileStorage(FileStorageInterface):
await session.close()
from fastapi.responses import StreamingResponse
encoded_filename = quote(filename, safe='')
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
headers = build_attachment_headers(filename)
if content_length is not None:
headers["Content-Length"] = str(content_length)
return StreamingResponse(
@@ -547,21 +564,15 @@ class S3FileStorage(FileStorageInterface):
:param upload_id: 上传会话ID
:param save_path: 文件保存路径
"""
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
# 尾部斜杠防止误删 upload_id 相同前缀的其他会话。
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + "/"
async with self._client() as s3:
try:
# 列出并删除所有分片对象
paginator = s3.get_paginator('list_objects_v2')
async for page in paginator.paginate(Bucket=self.bucket_name, Prefix=chunk_dir):
objects = page.get('Contents', [])
if objects:
delete_objects = [{'Key': obj['Key']} for obj in objects]
await s3.delete_objects(
Bucket=self.bucket_name,
Delete={'Objects': delete_objects}
)
except Exception as e:
logger.warning(f"清理 S3 分片数据时出错: {e}")
paginator = s3.get_paginator("list_objects_v2")
async for page in paginator.paginate(Bucket=self.bucket_name, Prefix=chunk_dir):
for obj in page.get("Contents", []):
# OSS 批量删除要求 Content-MD5;单对象删除不依赖该扩展。
# 失败向调用方传播,保留会话供重试,不能当作清理成功。
await s3.delete_object(Bucket=self.bucket_name, Key=obj["Key"])
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
"""
@@ -753,10 +764,7 @@ class OneDriveFileStorage(FileStorageInterface):
finally:
await session.close()
encoded_filename = quote(filename, safe='')
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
headers = build_attachment_headers(filename)
if content_length is not None:
headers["Content-Length"] = str(content_length)
return StreamingResponse(
@@ -962,10 +970,7 @@ class OpenDALFileStorage(FileStorageInterface):
except AttributeError:
# 如果 reader 方法不存在,回退到全量读取(兼容旧版本)
content = await self.operator.read(await file_code.get_file_path())
encoded_filename = quote(filename, safe='')
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
headers = build_attachment_headers(filename)
if content_length is not None:
headers["Content-Length"] = str(content_length)
return Response(
@@ -980,10 +985,7 @@ class OpenDALFileStorage(FileStorageInterface):
break
yield chunk
encoded_filename = quote(filename, safe='')
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
headers = build_attachment_headers(filename)
if content_length is not None:
headers["Content-Length"] = str(content_length)
return StreamingResponse(
@@ -1050,6 +1052,7 @@ class OpenDALFileStorage(FileStorageInterface):
await self.operator.remove_all(chunk_dir)
except Exception as e:
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
raise
async def file_exists(self, save_path: str) -> bool:
"""
@@ -1245,7 +1248,7 @@ class WebDAVFileStorage(CloudDriveUploadMixin, WebDAVStreamMixin, WebDAVOffsetMi
upstream.release()
await session.close()
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"}
headers = build_attachment_headers(filename)
if upstream.content_length is not None:
headers["Content-Length"] = str(upstream.content_length)
return StreamingResponse(stream_generator(), media_type="application/octet-stream", headers=headers, background=BackgroundTask(session.close))
@@ -1382,16 +1385,17 @@ class WebDAVFileStorage(CloudDriveUploadMixin, WebDAVStreamMixin, WebDAVOffsetMi
file_url = self._build_url(file_path)
async with session.delete(file_url) as delete_resp:
if delete_resp.status not in (200, 204, 404):
logger.warning(f"删除分片文件失败: {file_path}")
raise HTTPException(503, "WebDAV 分片删除失败,请稍后重试")
# 删除分片目录
async with session.delete(chunk_dir_url) as delete_resp:
if delete_resp.status not in (200, 204, 404):
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
else:
logger.info(f"分片目录不存在: {chunk_dir_url}")
raise HTTPException(503, "WebDAV 分片目录删除失败,请稍后重试")
elif resp.status != 404:
raise HTTPException(503, "WebDAV 分片目录查询失败,请稍后重试")
except Exception as e:
logger.warning(f"清理 WebDAV 分片时出错: {e}")
raise
async def file_exists(self, save_path: str) -> bool:
"""