diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 984e5f0..2b097b2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.7.1" + ".": "2.8.5" } diff --git a/Dockerfile b/Dockerfile index 41756dc..5ce34d2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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:-}\""] diff --git a/Dockerfile.release b/Dockerfile.release index 22b899a..5b798c2 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -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:-}\""] diff --git a/Dockerfile.upgrade b/Dockerfile.upgrade index 6f3904c..3a7d433 100644 --- a/Dockerfile.upgrade +++ b/Dockerfile.upgrade @@ -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:-}\""] diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index be7e401..c66af62 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -f2c5ad8a498c5bf5c07279d4fd33552e1ed6a316 +aacd017465e02181efde59050a23f81d0c8f3014 diff --git a/UPGRADE.md b/UPGRADE.md index 35a2f53..ff6a6f8 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -404,3 +404,39 @@ 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 清理异常传播,避免删除失败后误删重试会话。 + +最终 Python 3.12 镜像内 247 项测试与 42 个子场景全部通过,覆盖率 67%,无跳过项; +验证容器额外挂载源码 Compose、Dockerfile 和发布清单供部署契约检查。 +测试站 3MiB+17 字节(1MiB 分片)与 91MiB+17 字节(90MiB 分片)公网原生上传、 +首片重传、完整下载 SHA-256、回收/恢复/清理及取消清理全部通过,默认设置恢复 90MB。 +测试站后台确认版本 2.8.5,分片开关及大小设置仍可见;保留外部 cd2 HTTPS DAV 链路。 +前端正式 main 合并提交 aacd017465e02181efde59050a23f81d0c8f3014,固定为正式构建来源。 +升级前测试/生产数据库、Compose、CloudDrive 配置、镜像与 1Panel 数据库备份: +`/root/backups/filecodebox-285-20261029-163303`。 diff --git a/VERSION b/VERSION index 860487c..766d708 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.7.1 +2.8.5 diff --git a/apps/base/dependencies.py b/apps/base/dependencies.py index 7235bde..b130682 100644 --- a/apps/base/dependencies.py +++ b/apps/base/dependencies.py @@ -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(): - return False - self.ips.pop(ip) + 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, 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) diff --git a/apps/base/local_share.py b/apps/base/local_share.py index 8e67bc8..77583be 100644 --- a/apps/base/local_share.py +++ b/apps/base/local_share.py @@ -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: diff --git a/apps/base/migrations/migrations_011_query_indexes.py b/apps/base/migrations/migrations_011_query_indexes.py new file mode 100644 index 0000000..2405f82 --- /dev/null +++ b/apps/base/migrations/migrations_011_query_indexes.py @@ -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 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 - await UploadChunk.filter(upload_id=upload_id).delete() + 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) raise HTTPException( @@ -835,25 +849,31 @@ 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 ) - file_code = await FileCodes.create( - code=code, - file_hash=file_hash, # 使用合并后计算的哈希 - is_chunked=True, - upload_id=upload_id, - size=chunk_info.file_size, - expired_at=expired_at, - expired_count=expired_count, - used_count=used_count, - file_path=path, - uuid_file_name=safe_file_name, - prefix=prefix, - suffix=suffix, - ) + async with in_transaction() as connection: + file_code = await FileCodes.create( + using_db=connection, + code=code, + file_hash=file_hash, # 使用合并后计算的哈希 + is_chunked=True, + upload_id=upload_id, + size=chunk_info.file_size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + file_path=path, + uuid_file_name=safe_file_name, + 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) - # 清理临时文件 - await storage.clean_chunks(upload_id, save_path) - # 清理数据库中的分片记录 - await UploadChunk.filter(upload_id=upload_id).delete() + 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) return APIResponse(detail={"code": code, "name": safe_file_name}) diff --git a/core/database.py b/core/database.py index 1b04119..61251c4 100644 --- a/core/database.py +++ b/core/database.py @@ -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, }, } }, diff --git a/core/storage.py b/core/storage.py index 73c7b25..c9b714f 100644 --- a/core/storage.py +++ b/core/storage.py @@ -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: """ diff --git a/docker-compose.yml b/docker-compose.yml index a8626ca..a6432e3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 diff --git a/main.py b/main.py index 2cac92a..0fea5c4 100644 --- a/main.py +++ b/main.py @@ -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, diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..c8c9c75 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function diff --git a/requirements.txt b/requirements.txt index cd13a70..0f8e9e1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/tests/test_download_filename.py b/tests/test_download_filename.py new file mode 100644 index 0000000..f9888a2 --- /dev/null +++ b/tests/test_download_filename.py @@ -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 diff --git a/tests/test_index_cache.py b/tests/test_index_cache.py new file mode 100644 index 0000000..164dd5c --- /dev/null +++ b/tests/test_index_cache.py @@ -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}}" + '' + "
{{opacity}}
", + 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("New Site Name", 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}}

rebuilt

", 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("

rebuilt

", 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() diff --git a/tests/test_index_template_escaping.py b/tests/test_index_template_escaping.py new file mode 100644 index 0000000..3674558 --- /dev/null +++ b/tests/test_index_template_escaping.py @@ -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}}" + '' + "
{{opacity}}
" + ) + 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 = "" + settings.description = '">' + + html = self._render_index_html() + + self.assertNotIn("