✨ 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
+1012 -111

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "2.7.1"
".": "2.8.5"
}
+3 -1
View File
@@ -92,6 +92,8 @@ ENV HOST="0.0.0.0" \
APP_ENV="production" \
LOG_LEVEL="warning" \
ACCESS_LOG="false" \
TIMEOUT_KEEP_ALIVE=5 \
MALLOC_TRIM_THRESHOLD_=65536 \
FORWARDED_ALLOW_IPS=""
EXPOSE 12345
@@ -99,4 +101,4 @@ EXPOSE 12345
# 生产环境启动命令
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --timeout-keep-alive \"${TIMEOUT_KEEP_ALIVE:-5}\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
+3
View File
@@ -28,3 +28,6 @@ COPY scripts ./scripts
RUN pip install --no-cache-dir -r requirements.txt
COPY --from=frontend /build/dist ./themes/2026
ENV APP_VERSION="${APP_VERSION}"
ENV TIMEOUT_KEEP_ALIVE=5 MALLOC_TRIM_THRESHOLD_=65536
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --timeout-keep-alive \"${TIMEOUT_KEEP_ALIVE:-5}\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
+3
View File
@@ -13,3 +13,6 @@ COPY core ./core
COPY scripts ./scripts
RUN pip install --no-cache-dir -r requirements.txt
ENV APP_VERSION="${APP_VERSION}"
ENV TIMEOUT_KEEP_ALIVE=5 MALLOC_TRIM_THRESHOLD_=65536
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --timeout-keep-alive \"${TIMEOUT_KEEP_ALIVE:-5}\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
+1 -1
View File
@@ -1 +1 @@
f2c5ad8a498c5bf5c07279d4fd33552e1ed6a316
02093230e14d9ba39637d726ff1c62822ea90f18
+27
View File
@@ -404,3 +404,30 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
- 操作按钮允许换行,避免挤压卡片;保留现有回收、清理及时间格式逻辑。
- 前端 81 项单元/集成测试、覆盖率检查、类型/架构检查及构建通过;
Node 原生覆盖率不包含 Vite SSR 动态模块,CSS 另经深浅主题及 320–1920 像素六档浏览器验证。
## 2.8.5 官方差异整合(2026-10-29)
上游 vastsa/FileCodeBox v2.8.5(8d3e4ad904c289c1852f08c3424ae370642c58c3),
比较 v2.7.1 至 v2.8.5 全部变更,保留现有定制接口和 CloudDrive 原生上传。
- OSS/S3 禁用非必需 flexible checksum trailer,清理使用精确会话前缀与单对象删除。
清理失败保留会话并重试,已生成的分享继续成功返回;会话终态与分享事务提交,
失败清理后的会话不能复活,也不把元记录计入上传进度。
- 下载统一提供安全 ASCII filename 和 UTF-8 filename*,兼容旧安卓下载器。
- 限流使用单调时钟,每种限流器最多保留 10000 个 IP;首页按模板元数据与配置缓存,
站点内容转义后插入,保留定制主题资源路径。指纹资源长缓存,普通资源一天缓存。
- 只由 init_db 初始化 ORM,保留 ORM 异常处理;增加过期时间、创建时间和分片复合索引,
新迁移使用 011 编号,保留定制 008/009/010 迁移。SQLite 增加 NORMAL/MEMORY/8MiB 设置。
- 增加 uvloop/httptools 固定依赖、可配置 keep-alive 和 glibc 内存回收阈值,
三种 Docker 构建入口采用相同运行参数。
- 不引入 MCP 新入口、已被官方移除的 HTML 预览和不适用的上游模块重构。
- 分片开关与大小配置已存在,CloudDrive 原生协议已解决大文件完整 PUT 的公网限制;
本次保持原生写入与外部 HTTPS DAV 校验、下载、移动、清理的现有链路。
- VERSION、发布清单、Compose 和前端包版本同步为 2.8.5。
验证及部署结果在实际完成后追加,不以历史结果代替本轮验证。
本地本轮后端 245 项单元/集成与 42 个子场景通过,apps/core/main 覆盖率 67%;
两项需要主题资源的测试待最终镜像补跑。前端 81 项及覆盖率检查通过,类型、架构与构建通过。
独立审查补齐本地、OpenDAL、旧 DAV 清理异常传播,避免删除失败后误删重试会话。
+1 -1
View File
@@ -1 +1 @@
2.7.1
2.8.5
+54 -19
View File
@@ -1,3 +1,6 @@
import time
from collections import OrderedDict
from typing import TypedDict
from ipaddress import ip_address, ip_network
from typing import Dict, Iterable, Union
from datetime import datetime, timedelta
@@ -65,36 +68,68 @@ def get_client_ip(request: Request) -> str:
return client_host
class _IPRecord(TypedDict):
count: int
last_seen: float
# Upper bound for tracked source IPs per limiter. Without it a scan using
# spoofed/rotating addresses grows the dict forever on a small VPS.
DEFAULT_MAX_TRACKED_IPS = 10_000
class IPRateLimit:
def __init__(self, count: int, minutes: int):
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
def __init__(
self,
count: int,
minutes: int,
max_ips: int = DEFAULT_MAX_TRACKED_IPS,
):
# Ordered by last activity (oldest first) so capacity eviction and the
# periodic cleanup are both O(1)/O(expired) instead of a full rebuild.
self.ips: OrderedDict[str, _IPRecord] = OrderedDict()
self.count = count
self.minutes = minutes
self.max_ips = max(1, max_ips)
def _window_seconds(self) -> float:
# minutes is mutable at runtime via apps.base.config._sync_ip_limits.
return float(self.minutes) * 60
def check_ip(self, ip: str) -> bool:
if ip in self.ips:
ip_info = self.ips[ip]
if ip_info["count"] >= self.count:
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
record = self.ips.get(ip)
if record is None:
return True
if record["count"] >= self.count:
if record["last_seen"] + self._window_seconds() > time.monotonic():
return False
self.ips.pop(ip)
self.ips.pop(ip, None)
return True
def add_ip(self, ip: str) -> int:
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
ip_info["count"] += 1
ip_info["time"] = datetime.now()
self.ips[ip] = ip_info
return ip_info["count"]
now = time.monotonic()
record = self.ips.get(ip)
if record is None:
record = {"count": 0, "last_seen": now}
self.ips[ip] = record
else:
self.ips.move_to_end(ip)
record["count"] += 1
record["last_seen"] = now
while len(self.ips) > self.max_ips:
# Evict the least recently active IP; fail-open for the evicted
# address is preferable to unbounded memory growth.
self.ips.popitem(last=False)
return record["count"]
async def remove_expired_ip(self) -> None:
now = datetime.now()
expiration = timedelta(minutes=self.minutes)
self.ips = {
ip: info
for ip, info in self.ips.items()
if info["time"] + expiration >= now
}
now = time.monotonic()
window = self._window_seconds()
while self.ips:
_, record = next(iter(self.ips.items()))
if record["last_seen"] + window >= now:
break
self.ips.popitem(last=False)
def __call__(self, request: Request) -> str:
ip = get_client_ip(request)
+2 -3
View File
@@ -13,7 +13,7 @@ from __future__ import annotations
import time
from pathlib import Path
from urllib.parse import quote
from core.storage import build_attachment_headers
from fastapi import HTTPException
@@ -96,8 +96,7 @@ def build_local_ref_download(file_code) -> FileResponse:
filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}"
if not filename:
filename = path.name
encoded_filename = quote(filename, safe="")
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}
headers = build_attachment_headers(filename)
try:
headers["Content-Length"] = str(path.stat().st_size)
except OSError:
@@ -0,0 +1,26 @@
from tortoise import connections
# 高频查询字段索引。真实部署的 schema 全部由迁移建立
# (init_db 不调用 generate_schemas),因此索引必须写在迁移里;
# apps/base/models.py 中的 index/Meta 仅用于测试的 generate_schemas 路径。
#
# - filecodes(expired_at):过期扫描(delete_expire_files)与后台过期统计。
# - filecodes(created_at):后台默认倒序列表、首页最近记录、今日/昨日统计。
# - uploadchunk(upload_id, chunk_index):分片状态检查与合并;其前缀同时
# 覆盖仅按 upload_id 的删除/清理查询(原先没有对应索引)。
# 已知缺口:clean_incomplete_uploads 的 chunk_index=-1 AND created_at<? 用不上
# 该复合索引,待清理任务改为分批查询后再评估。
async def migrate():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE INDEX IF NOT EXISTS idx_filecodes_expired_at
ON filecodes (expired_at);
CREATE INDEX IF NOT EXISTS idx_filecodes_created_at
ON filecodes (created_at);
CREATE INDEX IF NOT EXISTS idx_uploadchunk_upload_chunk
ON uploadchunk (upload_id, chunk_index);
"""
)
+6 -3
View File
@@ -21,10 +21,10 @@ class FileCodes(models.Model):
file_path = fields.CharField(max_length=255, null=True)
size = fields.BigIntField(default=0)
text = fields.TextField(null=True)
expired_at = fields.DatetimeField(null=True)
expired_at = fields.DatetimeField(null=True, index=True)
expired_count = fields.IntField(default=-1)
used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True)
created_at = fields.DatetimeField(auto_now_add=True, index=True)
file_hash = fields.CharField(max_length=64, null=True)
is_chunked = fields.BooleanField(default=False)
upload_id = fields.CharField(max_length=36, null=True)
@@ -61,7 +61,7 @@ class ShareCodeReservations(models.Model):
class UploadChunk(models.Model):
id = fields.IntField(pk=True)
upload_id = fields.CharField(max_length=36, index=True)
upload_id = fields.CharField(max_length=36)
chunk_index = fields.IntField()
chunk_hash = fields.CharField(max_length=64)
total_chunks = fields.IntField()
@@ -73,6 +73,9 @@ class UploadChunk(models.Model):
completed = fields.BooleanField(default=False)
storage_mode = fields.CharField(max_length=32, default="legacy")
class Meta:
indexes = [("upload_id", "chunk_index")]
class TransferStats(models.Model):
id = fields.IntField(pk=True)
+32 -12
View File
@@ -1,3 +1,6 @@
from core.logger import logger
from tortoise.transactions import in_transaction
from core.storage import build_attachment_headers
import datetime
import asyncio
import hashlib
@@ -301,7 +304,7 @@ async def build_download_response(file_code: FileCodes, file_storage: FileStorag
return Response(
content=file_code.text,
media_type="text/plain",
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"},
headers=build_attachment_headers(filename),
)
if is_local_ref(file_code):
return build_local_ref_download(file_code)
@@ -471,6 +474,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
existing_session = await UploadChunk.filter(
chunk_hash=data.file_hash,
chunk_index=-1,
completed=False,
file_size=data.file_size,
file_name=safe_file_name,
).first()
@@ -488,7 +492,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
"uploaded_chunks":list(range(existing_session.total_chunks)),"processing":True,
})
async with upload_lock(existing_session.upload_id):
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1).first()
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1, completed=False).first()
if existing_session:
if not existing_session.save_path:
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
@@ -504,7 +508,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
)
await UploadChunk.filter(id=existing_session.id).update(created_at=await get_now())
uploaded_chunks = await UploadChunk.filter(
upload_id=existing_session.upload_id, completed=True
upload_id=existing_session.upload_id, completed=True, chunk_index__gte=0
).values_list("chunk_index", flat=True)
return APIResponse(
detail={
@@ -567,6 +571,8 @@ async def upload_chunk(
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
if not chunk_info:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
if chunk_info.completed:
raise HTTPException(409, "上传会话已完成,仅待清理")
await reserve_storage(
f"chunk:{upload_id}",
chunk_info.file_size,
@@ -601,7 +607,7 @@ async def upload_chunk(
# 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算)
uploaded_count = await UploadChunk.filter(
upload_id=upload_id, completed=True
upload_id=upload_id, completed=True, chunk_index__gte=0
).count()
# 已上传分片的最大可能大小 + 当前分片
max_uploaded_size = chunk_info.file_size
@@ -714,9 +720,8 @@ async def _cancel_upload(upload_id):
try:
await storage.clean_chunks(upload_id, save_path)
except Exception as e:
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}:
raise
pass
logger.warning("取消上传清理失败,保留会话: %s", upload_id, exc_info=True)
raise HTTPException(503, "分片清理失败,请稍后重试") from e
# 清理数据库记录
await UploadChunk.filter(upload_id=upload_id).delete()
@@ -736,7 +741,7 @@ async def get_upload_status(upload_id: str):
# 获取已上传的分片列表
uploaded_chunks = await UploadChunk.filter(
upload_id=upload_id, completed=True
upload_id=upload_id, completed=True, chunk_index__gte=0
).values_list("chunk_index", flat=True)
return APIResponse(
@@ -782,7 +787,11 @@ async def _complete_upload(upload_id, data, ip):
published = await FileCodes.filter(upload_id=upload_id, is_trashed=False).first()
if published:
storage = storages[settings.file_storage]()
try:
await storage.clean_chunks(upload_id, await published.get_file_path())
except Exception:
logger.warning("已发布上传清理失败,保留会话: %s", upload_id, exc_info=True)
else:
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
return APIResponse(detail={"code":published.code,"name":published.prefix+published.suffix})
@@ -790,6 +799,8 @@ async def _complete_upload(upload_id, data, ip):
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
if not chunk_info:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
if chunk_info.completed:
raise HTTPException(409, "上传会话已完成,仅待清理")
validate_expire_style(data.expire_style)
await reserve_storage(
f"chunk:{upload_id}",
@@ -800,7 +811,7 @@ async def _complete_upload(upload_id, data, ip):
storage = storages[settings.file_storage]()
# 验证所有分片
completed_chunks_list = await UploadChunk.filter(
upload_id=upload_id, completed=True
upload_id=upload_id, completed=True, chunk_index__gte=0
).all()
if len(completed_chunks_list) != chunk_info.total_chunks:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
@@ -809,13 +820,16 @@ async def _complete_upload(upload_id, data, ip):
max_total_size = chunk_info.file_size
if max_total_size > settings.uploadSize:
save_path = chunk_info.save_path
cleanup_ok = True
if save_path:
try:
await storage.clean_chunks(upload_id, save_path)
except Exception:
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}:
raise
pass
cleanup_ok = False
logger.warning("超限上传清理失败,保留会话: %s", upload_id, exc_info=True)
if cleanup_ok:
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
max_size_mb = settings.uploadSize / (1024 * 1024)
@@ -835,7 +849,9 @@ async def _complete_upload(upload_id, data, ip):
expired_at, expired_count, used_count, code = await get_expire_info(
data.expire_value, data.expire_style
)
async with in_transaction() as connection:
file_code = await FileCodes.create(
using_db=connection,
code=code,
file_hash=file_hash, # 使用合并后计算的哈希
is_chunked=True,
@@ -849,10 +865,14 @@ async def _complete_upload(upload_id, data, ip):
prefix=prefix,
suffix=suffix,
)
chunk_info.completed = True
await chunk_info.save(using_db=connection, update_fields=["completed"])
await record_transfer_stat("upload", file_code, chunk_info.file_size, ip)
# 清理临时文件
try:
await storage.clean_chunks(upload_id, save_path)
# 清理数据库中的分片记录
except Exception:
logger.warning("上传已发布,临时分片等待重试清理: %s", upload_id, exc_info=True)
else:
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
ip_limit["upload"].add_ip(ip)
+3
View File
@@ -25,6 +25,9 @@ def get_db_config() -> dict:
"journal_mode": "WAL",
"busy_timeout": 10000,
"foreign_keys": "ON",
"synchronous": "NORMAL",
"temp_store": "MEMORY",
"cache_size": -8000,
},
}
},
+42 -38
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')
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}")
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:
"""
+1 -1
View File
@@ -1,7 +1,7 @@
version: "3"
services:
file-code-box:
image: local/filecodebox:2.7.1 # x-release-please-version
image: local/filecodebox:2.8.5 # x-release-please-version
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
+60 -30
View File
@@ -1,3 +1,5 @@
from functools import lru_cache
from pathlib import Path
# @Time : 2023/8/9 23:23
# @Author : Lan
# @File : main.py
@@ -16,7 +18,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTex
from starlette.middleware.gzip import GZipMiddleware
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.fastapi import tortoise_exception_handlers
from apps.admin.views import admin_api
from apps.base.models import KeyValue
@@ -29,7 +31,7 @@ from core.config import (
is_runtime_initialized,
refresh_settings,
)
from core.database import db_startup_lock, get_db_config, init_db
from core.database import db_startup_lock, init_db
from core.logger import get_log_level_name, is_access_log_enabled, logger
from core.response import APIResponse
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
@@ -772,7 +774,7 @@ async def load_config():
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
app = FastAPI(lifespan=lifespan, version=APP_VERSION, exception_handlers=tortoise_exception_handlers())
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)
@@ -803,14 +805,6 @@ app.add_middleware(
allow_headers=["*"],
)
# 使用 register_tortoise 来添加异常处理器
register_tortoise(
app,
config=get_db_config(),
generate_schemas=False,
add_exception_handlers=True,
)
app.include_router(share_api)
app.include_router(chunk_api)
app.include_router(presign_api)
@@ -880,13 +874,60 @@ def resolve_theme_file(*parts: str):
return file_path
_HASHED_ASSET_RE = re.compile(
r"-[A-Za-z0-9_-]{8,}\.(?:js|mjs|css|map|woff2?|ttf|otf|eot|svg|png|jpe?g|gif|webp|avif|ico)$",
re.IGNORECASE,
)
_IMMUTABLE_ASSET_CACHE = "public, max-age=31536000, immutable"
_DEFAULT_ASSET_CACHE = "public, max-age=86400"
def _asset_cache_control(asset_path: str) -> str:
if _HASHED_ASSET_RE.search(asset_path):
return _IMMUTABLE_ASSET_CACHE
return _DEFAULT_ASSET_CACHE
@lru_cache(maxsize=8)
def _render_index_html(
template_path: str,
inode: int,
mtime_ns: int,
size: int,
title: str,
description: str,
keywords: str,
opacity: str,
background: str,
) -> str:
"""Render index.html once per (theme file version, site config) pair.
The stat fields keep the cache honest when a theme is replaced in place;
config values are part of the key so admin edits are visible immediately
without any cross-module invalidation hook.
"""
content = (
Path(template_path)
.read_text(encoding="utf-8")
.replace("{{title}}", html.escape(title))
.replace("{{description}}", html.escape(description))
.replace("{{keywords}}", html.escape(keywords))
.replace("{{opacity}}", html.escape(opacity))
.replace("{{background}}", html.escape(background))
.replace('"/assets/', '"/theme-assets/')
.replace('"assets/', '"/theme-assets/')
)
return re.sub(r'((?:theme-)?assets/[^"\']+\.(?:css|js|json|png))(["\'])', rf"\1?v={mtime_ns}\2", content)
@app.get("/theme-assets/{asset_path:path}", include_in_schema=False)
@app.get("/assets/{asset_path:path}", include_in_schema=False)
async def theme_asset(asset_path: str):
normalized_asset_path = asset_path.removeprefix("assets/")
return FileResponse(
resolve_theme_file("assets", normalized_asset_path),
headers={"Cache-Control": "public, max-age=31536000, immutable"},
headers={"Cache-Control": _asset_cache_control(normalized_asset_path)},
)
@@ -909,25 +950,14 @@ async def not_found_handler(request, exc=None):
async def index(request=None, exc=None):
if request is not None and request.url.path.startswith(("/assets/", "/theme-assets/")):
return PlainTextResponse("Not found", status_code=404)
theme_dir = resolve_theme_root()
index_file = resolve_theme_file("index.html")
asset_version = str(int(index_file.stat().st_mtime))
content = (
index_file.read_text(encoding="utf-8")
.replace("{{title}}", str(settings.name))
.replace("{{description}}", str(settings.description))
.replace("{{keywords}}", str(settings.keywords))
.replace("{{opacity}}", str(settings.opacity))
.replace('"/assets/', '"/theme-assets/')
.replace('"assets/', '"/theme-assets/')
.replace("{{background}}", str(settings.background))
)
content = re.sub(
r'((?:theme-)?assets/[^"\']+\.(?:css|js|json|png))(["\'])',
rf"\1?v={asset_version}\2",
content,
)
try:
stat = index_file.stat()
except OSError:
raise HTTPException(404, "资源不存在")
content = _render_index_html(str(index_file), stat.st_ino, stat.st_mtime_ns, stat.st_size,
str(settings.name), str(settings.description), str(settings.keywords),
str(settings.opacity), str(settings.background))
return HTMLResponse(
content=content,
+3
View File
@@ -0,0 +1,3 @@
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
+2
View File
@@ -9,3 +9,5 @@ tortoise-orm==0.25.3
python-multipart==0.0.32
grpcio==1.80.0
protobuf==6.33.6
uvloop==0.23.0; sys_platform != "win32"
httptools==0.9.0
+49
View File
@@ -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
+82
View File
@@ -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()
+70
View File
@@ -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("&lt;script&gt;", 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()
+1 -1
View File
@@ -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)
+81
View File
@@ -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
+81
View File
@@ -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()
+81
View File
@@ -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/")
+50
View File
@@ -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
+68
View File
@@ -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()
+54
View File
@@ -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()
+125
View File
@@ -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()