🔀 合并 FileCodeBox 2.5.6 官方修复

在保留现有 2026 主题、管理后台与存储定制的基础上,同步官方 2.5.5/2.5.6 的安全修复与生产日志优化。

- 合入分片上传文件名清理与路径穿越防护
- 合入生产日志降噪、访问日志开关和回收站处理修复
- 保留现有前端主题、WebDAV 和管理后台定制
This commit is contained in:
orion committed 2026-09-11 07:37:37 +08:00
commit 67a4fd894c
22 files changed
+381 -54

No files matched your search

+46 -12
View File
@@ -1,26 +1,60 @@
import logging
import os
import sys
PRODUCTION_ENVIRONMENTS = {"production", "prod"}
LOG_LEVELS = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
def is_production_environment() -> bool:
environment = os.getenv("APP_ENV", "development").strip().lower()
return environment in PRODUCTION_ENVIRONMENTS
def get_log_level_name() -> str:
configured_level = os.getenv("LOG_LEVEL", "").strip().lower()
if configured_level in LOG_LEVELS:
return configured_level
return "warning" if is_production_environment() else "info"
def get_log_level() -> int:
return LOG_LEVELS[get_log_level_name()]
def is_access_log_enabled() -> bool:
configured_value = os.getenv("ACCESS_LOG")
if configured_value is not None:
return configured_value.strip().lower() in {"1", "true", "yes", "on"}
return not is_production_environment()
def setup_logger():
# 创建logger对象
_logger = logging.getLogger('FileCodeBox')
_logger.setLevel(logging.INFO)
_logger = logging.getLogger("FileCodeBox")
level = get_log_level()
_logger.setLevel(level)
_logger.propagate = False
# 创建控制台处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
if not _logger.handlers:
console_handler = logging.StreamHandler(sys.stdout)
_logger.addHandler(console_handler)
else:
console_handler = _logger.handlers[0]
console_handler.setLevel(level)
# 设置日志格式
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
console_handler.setFormatter(formatter)
# 添加处理器到logger
_logger.addHandler(console_handler)
return _logger
+10 -8
View File
@@ -120,6 +120,8 @@ class SystemFileStorage(FileStorageInterface):
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
root = self.root_path.resolve()
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
if any(part == ".." for part in raw.split("/")):
raise ValueError("非法文件路径")
candidate = (root / raw).resolve()
try:
candidate.relative_to(root)
@@ -269,14 +271,14 @@ class SystemFileStorage(FileStorageInterface):
try:
shutil.rmtree(chunk_dir)
except Exception as e:
logger.info(f"清理本地分片目录失败: {e}")
logger.warning(f"清理本地分片目录失败: {e}")
# 清理父级 chunks 目录(如果为空)
chunks_parent = chunk_dir.parent
if chunks_parent.exists() and not any(chunks_parent.iterdir()):
try:
chunks_parent.rmdir()
except Exception as e:
logger.info(f"清理 chunks 父目录失败: {e}")
logger.warning(f"清理 chunks 父目录失败: {e}")
async def file_exists(self, save_path: str) -> bool:
"""
@@ -547,7 +549,7 @@ class S3FileStorage(FileStorageInterface):
Delete={'Objects': delete_objects}
)
except Exception as e:
logger.info(f"清理 S3 分片数据时出错: {e}")
logger.warning(f"清理 S3 分片数据时出错: {e}")
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
"""
@@ -875,7 +877,7 @@ class OneDriveFileStorage(FileStorageInterface):
try:
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
except Exception as e:
logger.info(f"清理 OneDrive 分片时出错: {e}")
logger.warning(f"清理 OneDrive 分片时出错: {e}")
def _file_exists(self, save_path: str) -> bool:
"""同步检查文件是否存在"""
@@ -1033,7 +1035,7 @@ class OpenDALFileStorage(FileStorageInterface):
# OpenDAL 支持递归删除
await self.operator.remove_all(chunk_dir)
except Exception as e:
logger.info(f"清理 OpenDAL 分片时出错: {e}")
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool:
"""
@@ -1361,16 +1363,16 @@ class WebDAVFileStorage(FileStorageInterface):
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.info(f"删除分片文件失败: {file_path}")
logger.warning(f"删除分片文件失败: {file_path}")
# 删除分片目录
async with session.delete(chunk_dir_url) as delete_resp:
if delete_resp.status not in (200, 204, 404):
logger.info(f"删除分片目录失败: {chunk_dir_url}")
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
else:
logger.info(f"分片目录不存在: {chunk_dir_url}")
except Exception as e:
logger.info(f"清理 WebDAV 分片时出错: {e}")
logger.warning(f"清理 WebDAV 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool:
"""
+10 -10
View File
@@ -4,7 +4,6 @@
# @Software: PyCharm
import asyncio
import datetime
import logging
import os
from tortoise.expressions import Q
@@ -18,6 +17,7 @@ from apps.base.models import (
from apps.admin.services import FileService
from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings
from core.logger import logger
from core.settings import settings, data_root
from core.storage import FileStorageInterface, storages
from core.utils import get_now
@@ -45,7 +45,7 @@ async def delete_expire_files():
try:
await file_service.move_to_trash(exp, reason="expired")
except Exception as e:
logging.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
logger.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
expired_trash = await FileCodes.filter(
is_trashed=True,
trash_expires_at__isnull=False,
@@ -55,9 +55,9 @@ async def delete_expire_files():
try:
await file_service.purge_trashed_file(item)
except Exception as e:
logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
logger.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
except Exception as e:
logging.error(e)
logger.error(e)
finally:
await asyncio.sleep(600)
@@ -83,7 +83,7 @@ async def clean_incomplete_uploads():
)
await file_storage.clean_chunks(session.upload_id, save_path)
except Exception as e:
logging.error(
logger.error(
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
)
@@ -92,14 +92,14 @@ async def clean_incomplete_uploads():
await StorageReservation.filter(
token=f"chunk:{session.upload_id}"
).delete()
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
except Exception as e:
logging.error(
logger.error(
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
)
except Exception as e:
logging.error(f"清理未完成上传任务异常: {e}")
logger.error(f"清理未完成上传任务异常: {e}")
finally:
await asyncio.sleep(3600)
@@ -124,7 +124,7 @@ async def clean_expired_presign_sessions():
)
)
except Exception as e:
logging.error(
logger.error(
"清理过期直传文件失败 "
f"upload_id={session.upload_id}: {e}"
)
@@ -133,6 +133,6 @@ async def clean_expired_presign_sessions():
).delete()
await session.delete()
except Exception as e:
logging.error(f"清理过期预签名会话异常: {e}")
logger.error(f"清理过期预签名会话异常: {e}")
finally:
await asyncio.sleep(900)