🔀 合并 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

+1 -1
View File
@@ -1,3 +1,3 @@
{ {
".": "2.5.4" ".": "2.5.6"
} }
+6 -3
View File
@@ -89,11 +89,14 @@ RUN apt-get update \
ENV HOST="0.0.0.0" \ ENV HOST="0.0.0.0" \
PORT=12345 \ PORT=12345 \
WORKERS=1 \ WORKERS=1 \
LOG_LEVEL="info" \ APP_ENV="production" \
LOG_LEVEL="warning" \
ACCESS_LOG="false" \
FORWARDED_ALLOW_IPS="" FORWARDED_ALLOW_IPS=""
EXPOSE 12345 EXPOSE 12345
# 生产环境启动命令 # 生产环境启动命令
# FORWARDED_ALLOW_IPS 由部署环境显式指定,避免任意客户端伪造 X-Forwarded-*。 # FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""] # 若前面有反向代理,请显式设置为代理网段,例如 "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:-}\""]
+1 -1
View File
@@ -1 +1 @@
2.5.4 2.5.6
+1
View File
@@ -43,6 +43,7 @@ async def get_chunk_file_path_name(
) -> Tuple[str, str, str, str, str]: ) -> Tuple[str, str, str, str, str]:
today = await get_now() today = await get_now()
storage_path = settings.storage_path.strip("/") storage_path = settings.storage_path.strip("/")
file_name = await sanitize_filename(unquote(file_name or ""))
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}" base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
path = f"{storage_path}/{base_path}" if storage_path else base_path path = f"{storage_path}/{base_path}" if storage_path else base_path
prefix, suffix = os.path.splitext(file_name) prefix, suffix = os.path.splitext(file_name)
+11 -7
View File
@@ -437,7 +437,8 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel:
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)]) @chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)): async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
validate_file_type(data.file_name) safe_file_name = await sanitize_filename(unquote(data.file_name or ""))
validate_file_type(safe_file_name)
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量 # 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
max_possible_size = total_chunks * data.chunk_size max_possible_size = total_chunks * data.chunk_size
@@ -467,7 +468,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
chunk_hash=data.file_hash, chunk_hash=data.file_hash,
chunk_index=-1, chunk_index=-1,
file_size=data.file_size, file_size=data.file_size,
file_name=data.file_name, file_name=safe_file_name,
).first() ).first()
if existing_session: if existing_session:
@@ -503,7 +504,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
await reserve_storage( await reserve_storage(
reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds
) )
_, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id) _, _, _, safe_file_name, save_path = await get_chunk_file_path_name(
data.file_name, upload_id
)
try: try:
await UploadChunk.create( await UploadChunk.create(
upload_id=upload_id, upload_id=upload_id,
@@ -512,7 +515,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
file_size=data.file_size, file_size=data.file_size,
chunk_size=data.chunk_size, chunk_size=data.chunk_size,
chunk_hash=data.file_hash, chunk_hash=data.file_hash,
file_name=data.file_name, file_name=safe_file_name,
save_path=save_path, save_path=save_path,
) )
except Exception: except Exception:
@@ -714,7 +717,8 @@ async def complete_upload(
save_path = chunk_info.save_path save_path = chunk_info.save_path
path = os.path.dirname(save_path) if save_path else "" path = os.path.dirname(save_path) if save_path else ""
prefix, suffix = os.path.splitext(chunk_info.file_name) safe_file_name = os.path.basename(save_path) if save_path else ""
prefix, suffix = os.path.splitext(safe_file_name)
try: try:
# 合并文件并计算哈希 # 合并文件并计算哈希
@@ -733,7 +737,7 @@ async def complete_upload(
expired_count=expired_count, expired_count=expired_count,
used_count=used_count, used_count=used_count,
file_path=path, file_path=path,
uuid_file_name=f"{prefix}{suffix}", uuid_file_name=safe_file_name,
prefix=prefix, prefix=prefix,
suffix=suffix, suffix=suffix,
) )
@@ -744,7 +748,7 @@ async def complete_upload(
await UploadChunk.filter(upload_id=upload_id).delete() await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}") await release_storage(f"chunk:{upload_id}")
ip_limit["upload"].add_ip(ip) ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": chunk_info.file_name}) return APIResponse(detail={"code": code, "name": safe_file_name})
except ValueError as e: except ValueError as e:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e)) raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
except Exception as e: except Exception as e:
+46 -12
View File
@@ -1,26 +1,60 @@
import logging import logging
import os
import sys 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(): def setup_logger():
# 创建logger对象 _logger = logging.getLogger("FileCodeBox")
_logger = logging.getLogger('FileCodeBox') level = get_log_level()
_logger.setLevel(logging.INFO) _logger.setLevel(level)
_logger.propagate = False
# 创建控制台处理器 if not _logger.handlers:
console_handler = logging.StreamHandler(sys.stdout) console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO) _logger.addHandler(console_handler)
else:
console_handler = _logger.handlers[0]
console_handler.setLevel(level)
# 设置日志格式
formatter = logging.Formatter( formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt='%Y-%m-%d %H:%M:%S' datefmt="%Y-%m-%d %H:%M:%S",
) )
console_handler.setFormatter(formatter) console_handler.setFormatter(formatter)
# 添加处理器到logger
_logger.addHandler(console_handler)
return _logger return _logger
+10 -8
View File
@@ -120,6 +120,8 @@ class SystemFileStorage(FileStorageInterface):
"""将相对路径解析到数据根目录内,阻止路径穿越。""" """将相对路径解析到数据根目录内,阻止路径穿越。"""
root = self.root_path.resolve() root = self.root_path.resolve()
raw = str(relative_path or "").replace("\\", "/").lstrip("/") raw = str(relative_path or "").replace("\\", "/").lstrip("/")
if any(part == ".." for part in raw.split("/")):
raise ValueError("非法文件路径")
candidate = (root / raw).resolve() candidate = (root / raw).resolve()
try: try:
candidate.relative_to(root) candidate.relative_to(root)
@@ -269,14 +271,14 @@ class SystemFileStorage(FileStorageInterface):
try: try:
shutil.rmtree(chunk_dir) shutil.rmtree(chunk_dir)
except Exception as e: except Exception as e:
logger.info(f"清理本地分片目录失败: {e}") logger.warning(f"清理本地分片目录失败: {e}")
# 清理父级 chunks 目录(如果为空) # 清理父级 chunks 目录(如果为空)
chunks_parent = chunk_dir.parent chunks_parent = chunk_dir.parent
if chunks_parent.exists() and not any(chunks_parent.iterdir()): if chunks_parent.exists() and not any(chunks_parent.iterdir()):
try: try:
chunks_parent.rmdir() chunks_parent.rmdir()
except Exception as e: except Exception as e:
logger.info(f"清理 chunks 父目录失败: {e}") logger.warning(f"清理 chunks 父目录失败: {e}")
async def file_exists(self, save_path: str) -> bool: async def file_exists(self, save_path: str) -> bool:
""" """
@@ -547,7 +549,7 @@ class S3FileStorage(FileStorageInterface):
Delete={'Objects': delete_objects} Delete={'Objects': delete_objects}
) )
except Exception as e: 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]: async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
""" """
@@ -875,7 +877,7 @@ class OneDriveFileStorage(FileStorageInterface):
try: try:
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir) await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
except Exception as e: except Exception as e:
logger.info(f"清理 OneDrive 分片时出错: {e}") logger.warning(f"清理 OneDrive 分片时出错: {e}")
def _file_exists(self, save_path: str) -> bool: def _file_exists(self, save_path: str) -> bool:
"""同步检查文件是否存在""" """同步检查文件是否存在"""
@@ -1033,7 +1035,7 @@ class OpenDALFileStorage(FileStorageInterface):
# OpenDAL 支持递归删除 # OpenDAL 支持递归删除
await self.operator.remove_all(chunk_dir) await self.operator.remove_all(chunk_dir)
except Exception as e: except Exception as e:
logger.info(f"清理 OpenDAL 分片时出错: {e}") logger.warning(f"清理 OpenDAL 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool: async def file_exists(self, save_path: str) -> bool:
""" """
@@ -1361,16 +1363,16 @@ class WebDAVFileStorage(FileStorageInterface):
file_url = self._build_url(file_path) file_url = self._build_url(file_path)
async with session.delete(file_url) as delete_resp: async with session.delete(file_url) as delete_resp:
if delete_resp.status not in (200, 204, 404): 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: async with session.delete(chunk_dir_url) as delete_resp:
if delete_resp.status not in (200, 204, 404): if delete_resp.status not in (200, 204, 404):
logger.info(f"删除分片目录失败: {chunk_dir_url}") logger.warning(f"删除分片目录失败: {chunk_dir_url}")
else: else:
logger.info(f"分片目录不存在: {chunk_dir_url}") logger.info(f"分片目录不存在: {chunk_dir_url}")
except Exception as e: except Exception as e:
logger.info(f"清理 WebDAV 分片时出错: {e}") logger.warning(f"清理 WebDAV 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool: async def file_exists(self, save_path: str) -> bool:
""" """
+10 -10
View File
@@ -4,7 +4,6 @@
# @Software: PyCharm # @Software: PyCharm
import asyncio import asyncio
import datetime import datetime
import logging
import os import os
from tortoise.expressions import Q from tortoise.expressions import Q
@@ -18,6 +17,7 @@ from apps.base.models import (
from apps.admin.services import FileService from apps.admin.services import FileService
from apps.base.utils import ip_limit, get_chunk_file_path_name from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings from core.config import refresh_settings
from core.logger import logger
from core.settings import settings, data_root from core.settings import settings, data_root
from core.storage import FileStorageInterface, storages from core.storage import FileStorageInterface, storages
from core.utils import get_now from core.utils import get_now
@@ -45,7 +45,7 @@ async def delete_expire_files():
try: try:
await file_service.move_to_trash(exp, reason="expired") await file_service.move_to_trash(exp, reason="expired")
except Exception as e: except Exception as e:
logging.error(f"移入过期文件回收站失败 code={exp.code}: {e}") logger.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
expired_trash = await FileCodes.filter( expired_trash = await FileCodes.filter(
is_trashed=True, is_trashed=True,
trash_expires_at__isnull=False, trash_expires_at__isnull=False,
@@ -55,9 +55,9 @@ async def delete_expire_files():
try: try:
await file_service.purge_trashed_file(item) await file_service.purge_trashed_file(item)
except Exception as e: except Exception as e:
logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}") logger.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
except Exception as e: except Exception as e:
logging.error(e) logger.error(e)
finally: finally:
await asyncio.sleep(600) await asyncio.sleep(600)
@@ -83,7 +83,7 @@ async def clean_incomplete_uploads():
) )
await file_storage.clean_chunks(session.upload_id, save_path) await file_storage.clean_chunks(session.upload_id, save_path)
except Exception as e: except Exception as e:
logging.error( logger.error(
f"清理分片文件失败 upload_id={session.upload_id}: {e}" f"清理分片文件失败 upload_id={session.upload_id}: {e}"
) )
@@ -92,14 +92,14 @@ async def clean_incomplete_uploads():
await StorageReservation.filter( await StorageReservation.filter(
token=f"chunk:{session.upload_id}" token=f"chunk:{session.upload_id}"
).delete() ).delete()
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}") logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
except Exception as e: except Exception as e:
logging.error( logger.error(
f"删除分片记录失败 upload_id={session.upload_id}: {e}" f"删除分片记录失败 upload_id={session.upload_id}: {e}"
) )
except Exception as e: except Exception as e:
logging.error(f"清理未完成上传任务异常: {e}") logger.error(f"清理未完成上传任务异常: {e}")
finally: finally:
await asyncio.sleep(3600) await asyncio.sleep(3600)
@@ -124,7 +124,7 @@ async def clean_expired_presign_sessions():
) )
) )
except Exception as e: except Exception as e:
logging.error( logger.error(
"清理过期直传文件失败 " "清理过期直传文件失败 "
f"upload_id={session.upload_id}: {e}" f"upload_id={session.upload_id}: {e}"
) )
@@ -133,6 +133,6 @@ async def clean_expired_presign_sessions():
).delete() ).delete()
await session.delete() await session.delete()
except Exception as e: except Exception as e:
logging.error(f"清理过期预签名会话异常: {e}") logger.error(f"清理过期预签名会话异常: {e}")
finally: finally:
await asyncio.sleep(900) await asyncio.sleep(900)
+11 -1
View File
@@ -1,12 +1,22 @@
version: "3" version: "3"
services: services:
file-code-box: file-code-box:
image: lanol/filecodebox:2.5.4 # x-release-please-version image: lanol/filecodebox:2.5.6 # x-release-please-version
volumes: volumes:
- fcb-data:/app/data:rw - fcb-data:/app/data:rw
restart: unless-stopped restart: unless-stopped
ports: ports:
- "12345:12345" - "12345:12345"
environment:
- APP_ENV=production
- LOG_LEVEL=warning
- ACCESS_LOG=false
- WORKERS=1
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes: volumes:
fcb-data: fcb-data:
external: false external: false
+16
View File
@@ -1,5 +1,21 @@
# Changelog # Changelog
## [2.5.6](https://github.com/vastsa/FileCodeBox/compare/v2.5.5...v2.5.6) (2026-09-01)
### Bug Fixes
* **logging:** reduce production log noise ([5537f56](https://github.com/vastsa/FileCodeBox/commit/5537f56b884a15eda015665c67c3f8469e4e9d89))
## [2.5.5](https://github.com/vastsa/FileCodeBox/compare/v2.5.4...v2.5.5) (2026-08-29)
### Bug Fixes
* **chunk-upload:** persist sanitized filenames ([da1dd06](https://github.com/vastsa/FileCodeBox/commit/da1dd066551cc7cc9a631a0c982b5675bd4b1967))
* harden chunk upload filename metadata ([5a7195c](https://github.com/vastsa/FileCodeBox/commit/5a7195c5c7d1028500b0e363c6b47130d260e11c))
* sanitize chunk upload file_name to prevent path traversal ([cebac32](https://github.com/vastsa/FileCodeBox/commit/cebac32145f948bfca7c44c663a0bcdcd9c56830))
## [2.5.4](https://github.com/vastsa/FileCodeBox/compare/v2.5.3...v2.5.4) (2026-07-23) ## [2.5.4](https://github.com/vastsa/FileCodeBox/compare/v2.5.3...v2.5.4) (2026-07-23)
+1 -1
View File
@@ -1,6 +1,6 @@
## [Unreleased] ## [Unreleased]
<!-- Current release: 2.5.4 x-release-please-version --> <!-- Current release: 2.5.6 x-release-please-version -->
### Added ### Added
+9 -1
View File
@@ -21,6 +21,10 @@ FileCodeBox is a simple and efficient file sharing tool that supports temporary
docker run -d --restart unless-stopped \ docker run -d --restart unless-stopped \
-p 12345:12345 \ -p 12345:12345 \
-v fcb-data:/app/data \ -v fcb-data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \ --name filecodebox \
lanol/filecodebox:latest lanol/filecodebox:latest
``` ```
@@ -32,7 +36,11 @@ The named volume persists configuration and uploaded files across container upgr
| `HOST` | `0.0.0.0` | Service listening address | | `HOST` | `0.0.0.0` | Service listening address |
| `PORT` | `12345` | Service port | | `PORT` | `12345` | Service port |
| `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments | | `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, or `error` | | `APP_ENV` | `production` (Docker) | Runtime environment; production disables HTTP access logs by default |
| `LOG_LEVEL` | `warning` (Docker) | `debug`, `info`, `warning`, or `error` |
| `ACCESS_LOG` | `false` (production) | Enable HTTP access logs; set to `true` when debugging requests |
Production deployments output only warning, error, and other key events by default. Docker retains at most three 10 MB log files.
### Manual Deployment ### Manual Deployment
+9 -1
View File
@@ -136,7 +136,15 @@ Command-line download
### Docker Deployment ### Docker Deployment
```bash ```bash
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest docker run -d --restart unless-stopped \
-p 12345:12345 \
-v fcb-data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \
lanol/filecodebox:latest
``` ```
### Manual Deployment ### Manual Deployment
+5 -1
View File
@@ -37,8 +37,12 @@ features:
docker run -d --restart unless-stopped \ docker run -d --restart unless-stopped \
-p 12345:12345 \ -p 12345:12345 \
-v ./data:/app/data \ -v ./data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \ --name filecodebox \
lanol/filecodebox:2.5.4 # x-release-please-version lanol/filecodebox:2.5.6 # x-release-please-version
``` ```
Open `http://localhost:12345` and complete the first-run setup. Open `http://localhost:12345` and complete the first-run setup.
+20 -2
View File
@@ -23,6 +23,10 @@ FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中
docker run -d --restart unless-stopped \ docker run -d --restart unless-stopped \
-p 12345:12345 \ -p 12345:12345 \
-v fcb-data:/app/data \ -v fcb-data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \ --name filecodebox \
lanol/filecodebox:latest lanol/filecodebox:latest
``` ```
@@ -40,8 +44,15 @@ services:
ports: ports:
- "12345:12345" - "12345:12345"
environment: environment:
- APP_ENV=production
- WORKERS=1 - WORKERS=1
- LOG_LEVEL=info - LOG_LEVEL=warning
- ACCESS_LOG=false
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes: volumes:
fcb-data: fcb-data:
external: false external: false
@@ -54,7 +65,11 @@ volumes:
| `HOST` | `0.0.0.0` | 服务监听地址 | | `HOST` | `0.0.0.0` | 服务监听地址 |
| `PORT` | `12345` | 服务端口 | | `PORT` | `12345` | 服务端口 |
| `WORKERS` | `1` | 工作进程数;SQLite 部署建议保持单进程 | | `WORKERS` | `1` | 工作进程数;SQLite 部署建议保持单进程 |
| `LOG_LEVEL` | `info` | 日志级别:debug/info/warning/error | | `APP_ENV` | `production`(Docker) | 运行环境;生产环境默认关闭 HTTP 访问日志 |
| `LOG_LEVEL` | `warning`(Docker) | 日志级别:debug/info/warning/error |
| `ACCESS_LOG` | `false`(生产环境) | 是否启用 HTTP 访问日志;调试请求时可设为 `true` |
生产环境默认只输出 warning、error 等关键日志,并限制 Docker 日志最多保留 3 个 10 MB 文件。
#### 自定义配置示例 #### 自定义配置示例
@@ -63,8 +78,11 @@ docker run -d --restart=always \
-p 12345:12345 \ -p 12345:12345 \
-v fcb-data:/app/data \ -v fcb-data:/app/data \
-e WORKERS=1 \ -e WORKERS=1 \
-e APP_ENV=production \
-e LOG_LEVEL=warning \ -e LOG_LEVEL=warning \
--name filecodebox \ --name filecodebox \
--log-opt max-size=10m \
--log-opt max-file=3 \
lanol/filecodebox:latest lanol/filecodebox:latest
``` ```
+9 -1
View File
@@ -150,7 +150,15 @@ FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具
### Docker 部署 ### Docker 部署
```bash ```bash
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest docker run -d --restart unless-stopped \
-p 12345:12345 \
-v fcb-data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \
lanol/filecodebox:latest
``` ```
### 手动部署 ### 手动部署
+5 -1
View File
@@ -37,8 +37,12 @@ features:
docker run -d --restart unless-stopped \ docker run -d --restart unless-stopped \
-p 12345:12345 \ -p 12345:12345 \
-v ./data:/app/data \ -v ./data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \ --name filecodebox \
lanol/filecodebox:2.5.4 # x-release-please-version lanol/filecodebox:2.5.6 # x-release-please-version
``` ```
打开 `http://localhost:12345`,按引导完成首次初始化。 打开 `http://localhost:12345`,按引导完成首次初始化。
+3 -1
View File
@@ -30,7 +30,7 @@ from core.config import (
refresh_settings, refresh_settings,
) )
from core.database import db_startup_lock, get_db_config, init_db from core.database import db_startup_lock, get_db_config, init_db
from core.logger import logger from core.logger import get_log_level_name, is_access_log_enabled, logger
from core.response import APIResponse from core.response import APIResponse
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
from core.tasks import ( from core.tasks import (
@@ -961,4 +961,6 @@ if __name__ == "__main__":
port=settings.serverPort, port=settings.serverPort,
reload=False, reload=False,
workers=settings.serverWorkers, workers=settings.serverWorkers,
log_level=get_log_level_name(),
access_log=is_access_log_enabled(),
) )
+9 -1
View File
@@ -24,7 +24,15 @@
## 一条命令开始 ## 一条命令开始
```bash ```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.4 # x-release-please-version docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \
lanol/filecodebox:2.5.6 # x-release-please-version
``` ```
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。 访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
+9 -1
View File
@@ -24,7 +24,15 @@ A lightweight, modern, self-hosted file sharing service. No account required—u
## Start with one command ## Start with one command
```bash ```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.4 # x-release-please-version docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
-e APP_ENV=production \
-e LOG_LEVEL=warning \
--log-opt max-size=10m \
--log-opt max-file=3 \
--name filecodebox \
lanol/filecodebox:2.5.6 # x-release-please-version
``` ```
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release. Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
+60
View File
@@ -0,0 +1,60 @@
import importlib
import logging
import os
import unittest
from pathlib import Path
from unittest.mock import patch
import core.logger as logger_module
class LoggingConfigurationTests(unittest.TestCase):
def setUp(self):
self.environment_patch = None
def tearDown(self):
if self.environment_patch is not None:
self.environment_patch.stop()
importlib.reload(logger_module)
def reload_with_environment(self, values):
self.environment_patch = patch.dict(os.environ, values, clear=True)
self.environment_patch.start()
return importlib.reload(logger_module)
def test_production_defaults_to_warning_and_disables_access_logs(self):
module = self.reload_with_environment({"APP_ENV": "production"})
self.assertEqual(module.get_log_level_name(), "warning")
self.assertEqual(module.logger.level, logging.WARNING)
self.assertFalse(module.is_access_log_enabled())
def test_development_defaults_to_info_and_keeps_access_logs(self):
module = self.reload_with_environment({"APP_ENV": "development"})
self.assertEqual(module.get_log_level_name(), "info")
self.assertEqual(module.logger.level, logging.INFO)
self.assertTrue(module.is_access_log_enabled())
def test_explicit_log_and_access_settings_override_environment_defaults(self):
module = self.reload_with_environment(
{"APP_ENV": "production", "LOG_LEVEL": "error", "ACCESS_LOG": "true"}
)
self.assertEqual(module.get_log_level_name(), "error")
self.assertEqual(module.logger.level, logging.ERROR)
self.assertTrue(module.is_access_log_enabled())
def test_log_file_configuration_is_bounded_in_docker_compose(self):
compose = Path("docker-compose.yml").read_text(encoding="utf-8")
dockerfile = Path("Dockerfile").read_text(encoding="utf-8")
self.assertIn('max-size: "10m"', compose)
self.assertIn('max-file: "3"', compose)
self.assertIn('APP_ENV="production"', dockerfile)
self.assertIn('LOG_LEVEL="warning"', dockerfile)
self.assertIn("--no-access-log", dockerfile)
if __name__ == "__main__":
unittest.main()
+129
View File
@@ -1,4 +1,5 @@
import asyncio import asyncio
from io import BytesIO
import os import os
import tempfile import tempfile
import unittest import unittest
@@ -6,10 +7,16 @@ from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
from fastapi import HTTPException from fastapi import HTTPException
from starlette.datastructures import UploadFile
from tortoise import Tortoise
from apps.base import views
from apps.admin import dependencies as admin_dependencies from apps.admin import dependencies as admin_dependencies
from apps.admin.dependencies import create_token, verify_token from apps.admin.dependencies import create_token, verify_token
from apps.admin.services import LocalFileClass from apps.admin.services import LocalFileClass
from apps.base.models import FileCodes, UploadChunk
from apps.base.schemas import CompleteUploadModel, InitChunkUploadModel
from apps.base.utils import get_chunk_file_path_name
from core.settings import data_root, settings from core.settings import data_root, settings
from core.storage import SystemFileStorage from core.storage import SystemFileStorage
from core.utils import hash_password, verify_password from core.utils import hash_password, verify_password
@@ -71,11 +78,133 @@ class SystemStoragePathTests(unittest.TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
self.storage._resolve_safe_path("../etc/passwd") self.storage._resolve_safe_path("../etc/passwd")
def test_resolve_safe_path_blocks_internal_dotdot(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("share/data/2026/08/29/x/../../../../../../filecodebox.db")
def test_resolve_safe_path_blocks_windows_dotdot(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("share\\data\\..\\..\\filecodebox.db")
def test_resolve_safe_path_allows_nested(self): def test_resolve_safe_path_allows_nested(self):
target = self.storage._resolve_safe_path("share/data/a/b.txt") target = self.storage._resolve_safe_path("share/data/a/b.txt")
self.assertTrue(str(target).startswith(str(Path(self._tmpdir.name).resolve()))) self.assertTrue(str(target).startswith(str(Path(self._tmpdir.name).resolve())))
class ChunkFileNameSanitizeTests(unittest.TestCase):
def test_chunk_file_path_name_strips_traversal(self):
path, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("../../../../../../filecodebox.db", "a" * 32)
)
self.assertNotIn("..", save_path)
self.assertEqual(filename, "filecodebox.db")
self.assertEqual(save_path, f"{path}/filecodebox.db")
self.assertIn("a" * 32, path)
def test_chunk_file_path_name_strips_windows_traversal(self):
_, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("..\\..\\..\\..\\..\\..\\evil.bin", "b" * 32)
)
self.assertNotIn("..", save_path)
self.assertEqual(filename, "evil.bin")
def test_chunk_file_path_name_keeps_normal_name(self):
_, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("safe.txt", "c" * 32)
)
self.assertEqual(filename, "safe.txt")
self.assertTrue(save_path.endswith("/safe.txt"))
class ChunkUploadMetadataTests(unittest.TestCase):
def test_traversal_filename_remains_downloadable_after_completion(self):
asyncio.run(self._run_traversal_upload())
async def _run_traversal_upload(self):
original_config = dict(settings.user_config)
tmpdir = tempfile.TemporaryDirectory()
try:
settings.file_storage = "local"
settings.allowed_file_types = ["*"]
with patch("core.storage.data_root", Path(tmpdir.name)):
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
raw_name = "../../../../../../filecodebox.db"
payload = b"chunk payload"
init_result = await views.init_chunk_upload(
InitChunkUploadModel(
file_name=raw_name,
file_size=len(payload),
chunk_size=1024,
file_hash="f" * 64,
)
)
upload_id = init_result.detail["upload_id"]
session = await UploadChunk.get(
upload_id=upload_id, chunk_index=-1
)
self.assertEqual(session.file_name, "filecodebox.db")
self.assertNotIn("..", session.save_path)
await views.upload_chunk(
upload_id=upload_id,
chunk_index=0,
chunk=UploadFile(
file=BytesIO(payload), filename="filecodebox.db"
),
)
# Simulate a legacy session whose display name was not sanitized.
session.file_name = raw_name
await session.save(update_fields=["file_name"])
complete_result = await views.complete_upload(
upload_id=upload_id,
data=CompleteUploadModel(
expire_value=1, expire_style="day"
),
ip="127.0.0.1",
)
self.assertEqual(complete_result.detail["name"], "filecodebox.db")
file_code = await FileCodes.get(code=complete_result.detail["code"])
expected_relative_path = session.save_path
self.assertEqual(
await file_code.get_file_path(), expected_relative_path
)
storage = views.storages[settings.file_storage]()
resolved_path = storage._resolve_safe_path(
await file_code.get_file_path()
)
self.assertEqual(
resolved_path, Path(tmpdir.name).resolve() / expected_relative_path
)
self.assertEqual(resolved_path.read_bytes(), payload)
finally:
await Tortoise.close_connections()
finally:
settings.user_config = original_config
tmpdir.cleanup()
class AdminJwtUrlSafeTests(unittest.TestCase): class AdminJwtUrlSafeTests(unittest.TestCase):
def setUp(self): def setUp(self):
settings.jwt_secret = "j" * 48 settings.jwt_secret = "j" * 48