🐛 fix: 整合官方 2.7.1 修复并升级定制版本

* 校验变更的出站地址并保留现有内部 CloudDrive 配置
* 修复未知长度上传、API 404 语义及下载令牌比较
* 合并 S3 小分片为符合最小尺寸要求的 multipart 部分
* 同步官方运行依赖、版本元数据和已推送前端版本
* 验证单元集成、覆盖率及定制上传下载兼容并记录整合范围
This commit is contained in:
orion committed 2026-10-07 00:16:11 +08:00
1 parent 9ce9810b3b
commit 3b6949d862
14 files changed
+355 -31

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "2.7.0"
".": "2.7.1"
}
+1 -1
View File
@@ -1 +1 @@
f238fe2908ef55afa3afcdf17e53f47f87e1d22b
ea8c52404dc567b959a259300cd2f132f1d12008
+27
View File
@@ -364,3 +364,30 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
重试、成功及新文件切换均符合预期;真实原生分片上传、重传已确认片、
完整下载 SHA-256 与取消清理通过。备份 `/root/backups/filecodebox-test-upload-20261006-144752`。
- 正式前端 main 合并版本 f238fe2;后端 master 从正式版本独立构建生产镜像。
## 2.7.1 官方差异整合(2026-10-07)
上游 `vastsa/FileCodeBox` v2.7.1(648d578d533557f43c6f72cb82835ed96b8fb376),
对比 v2.7.0 的全部三个提交,而非仅发布说明中的最后一个修复。
- 整合出站配置 SSRF 校验:生产只校验变化的 s3_endpoint_url、s3_hostname、webdav_url;
裸主机名独立校验,包含解析后的内网地址、IP 速记与 userinfo 绕过。
已保存的内部 CloudDrive/NAS 地址继续工作,无关设置保存不被拒绝。
DNS 校验在工作线程执行;环境为 development 时保留本地端点支持。
- 修复无声明长度上传调用 UploadFile.seek 的参数错误,在线程测量底层文件并复位。
- 区分 JSON API 404 与未知 HTML 导航的 SPA 首页;静态资源缺失仍为 404,
已匹配 API 自身抛出的 404 即使 Accept 为 HTML 也不会伪装为成功页面。
- 下载令牌按字节做常量时间比较,继续接受当前/前一时间窗,Unicode 错误令牌返回 403。
- S3 合并将小分片缓冲到至少 5 MiB 再提交非末尾 multipart 部分,保留逐片长度和
SHA-256 校验,失败中止 multipart;不修改 CloudDrive 原生写入链路。
- 同步官方 aiohttp 3.14.3、FastAPI 0.141.1、Starlette 1.6.0、Pydantic 2.13.5、
Uvicorn 0.53.0;保留 grpcio/protobuf 与现有其他依赖。
- 不机械移植官方 auth/admin/storage 模块拆分、蛇形接口和类型注解重构;
保留定制回收站、查件取件事件、八位码、手动检测、NAS 分页及上传状态。
WebDAV 在开始流式响应前校验上游状态及关闭会话的修复已存在;Docker 默认 root 已存在。
- 版本文件、发布清单、Compose 与前端包版本统一为 2.7.1;生产验证通过后同步
1Panel 对应安装记录的版本及 app_detail_id,继续保留未来版本的更新提醒。
- Python 3.12 部署环境与升级后的完整依赖下,202 项单元/集成及 42 个子场景通过,
apps/core/main 总覆盖率 65%;包括真实 Moto S3 multipart、gRPC/DAV、未知长度的
内存/落盘上传、HTTP 404、下载时间窗和 Unicode 令牌、保留内部 DAV 配置。
前端 81 项、覆盖率检查、类型/架构检查及构建通过(Node 原生覆盖率不包含 SSR 动态模块)。
+1 -1
View File
@@ -1 +1 @@
2.7.0
2.7.1
+15 -1
View File
@@ -20,7 +20,8 @@ from core.settings import (
settings,
)
from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from core.security import (INTERNAL_CONFIG_KEYS, generate_jwt_secret,
OUTBOUND_ENDPOINT_CONFIG_KEYS, validate_outbound_endpoint, validate_outbound_hostname)
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
from apps.base.utils import get_expire_info, get_random_code, validate_expire_style
@@ -1855,6 +1856,19 @@ class ConfigService:
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
# Existing internal NAS/CloudDrive endpoints remain valid for unrelated saves.
# Validate only changed destinations, matching upstream 2.7.1 semantics.
for endpoint_key in OUTBOUND_ENDPOINT_CONFIG_KEYS:
candidate = str(next_config.get(endpoint_key) or "")
current = str(current_config.get(endpoint_key) or "")
if candidate == current:
continue
validator = validate_outbound_hostname if endpoint_key == "s3_hostname" else validate_outbound_endpoint
try:
next_config[endpoint_key] = await asyncio.to_thread(validator, candidate)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
if admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
+11 -6
View File
@@ -1,5 +1,7 @@
import datetime
import asyncio
import hashlib
import hmac
from io import BytesIO
import os
import uuid
@@ -101,9 +103,12 @@ class FileUploadService:
async def validate_file_size(file: UploadFile, max_size: int) -> int:
size = file.size
if size is None:
await file.seek(0, 2) # type: ignore[arg-type]
size = file.file.tell()
await file.seek(0)
def measure():
file.file.seek(0, 2)
size = file.file.tell()
file.file.seek(0)
return size
size = await asyncio.to_thread(measure)
if size > max_size:
max_size_mb = max_size / (1024 * 1024)
raise HTTPException(
@@ -384,11 +389,11 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
file_storage: FileStorageInterface = storages[settings.file_storage]()
normalized_code = normalize_share_code(code)
# 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403
valid_keys = {
valid_keys = [
await get_select_token(normalized_code, offset=0),
await get_select_token(normalized_code, offset=1),
}
if key not in valid_keys:
]
if not any(hmac.compare_digest(key.encode(), candidate.encode()) for candidate in valid_keys):
ip_limit["error"].add_ip(ip)
raise HTTPException(status_code=403, detail="下载鉴权失败")
has, file_code = await get_code_file_by_code(normalized_code)
+103
View File
@@ -1,7 +1,11 @@
import copy
import ipaddress
import os
import socket
import secrets
from dataclasses import dataclass
from typing import Any
from urllib.parse import urlsplit
from core.utils import hash_password, is_password_hashed, verify_password
@@ -60,3 +64,102 @@ def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
result.changed = True
return result
# 出站端点白名单/黑名单(SSRF 防护)。
# 这些配置项会被服务器直接当作上游地址访问:被劫持的管理员会话可以把实例
# 变成内网代理跳板,或把数据发往任意地址。校验只在写入入口(update_config),
# 已存值不受影响;APP_ENV 非 production(本地开发,如 minio/webdav)时放行。
OUTBOUND_ENDPOINT_CONFIG_KEYS = ("s3_endpoint_url", "s3_hostname", "webdav_url")
_ENDPOINT_SCHEME_WHITELIST = {"http", "https"}
_ENDPOINT_HOST_DENY_SUFFIXES = (
".local",
".internal",
".lan",
".home.arpa",
".corp",
".localhost",
)
def _endpoint_ip_is_denied(ip_str: str) -> bool:
try:
ip = ipaddress.ip_address(ip_str)
except ValueError:
return False
return (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
)
def _endpoint_host_is_denied(host: str) -> bool:
host = host.strip("[]").lower()
if host in {"localhost"} or host.endswith(_ENDPOINT_HOST_DENY_SUFFIXES):
return True
# 字面 IP 直接判;非字面形态(速记 "127.1"、十进制 2130706433、十六进制、
# *.localhost、nip.io 类 DNS 映射)交给解析后逐 IP 复判——静态字符串
# 黑名单对它们全部失效,这是探测中实测确认的绕过面。
if _endpoint_ip_is_denied(host):
return True
try:
infos = socket.getaddrinfo(host, None)
except (socket.gaierror, UnicodeError, OSError):
return False
for info in infos:
# getaddrinfo 的 sockaddr 首元素在 IPv4/IPv6 下均为 str(int 仅出现在
# AF_UNIX 等异形族)——显式 str() 让类型检查器与运行时一致。
if _endpoint_ip_is_denied(str(info[4][0])):
return True
return False
def validate_outbound_endpoint(value: Any) -> str:
"""校验完整 URL 形态的出站端点(s3_endpoint_url / webdav_url)。"""
endpoint = str(value or "").strip()
if not endpoint:
return ""
if os.environ.get("APP_ENV", "development") != "production":
return endpoint
parts = urlsplit(endpoint)
if parts.scheme.lower() not in _ENDPOINT_SCHEME_WHITELIST:
raise ValueError(f"端点协议必须是 http(s):{endpoint}")
host = parts.hostname or ""
if not host:
raise ValueError(f"端点缺少主机名:{endpoint}")
if _endpoint_host_is_denied(host):
raise ValueError(f"端点不允许指向内网/保留地址:{endpoint}")
return endpoint
def validate_outbound_hostname(value: Any) -> str:
"""校验裸主机名形态的出站端点(s3_hostname,存储层拼接 https://{hostname})。"""
hostname = str(value or "").strip()
if not hostname:
return ""
if os.environ.get("APP_ENV", "development") != "production":
return hostname
if "://" in hostname or "/" in hostname or "@" in hostname:
raise ValueError(f"s3_hostname 应为裸主机名,不含协议、路径或 userinfo:{hostname}")
# 取主机部分:[v6] 形态取括号内;host:port 取冒号前;裸 IPv6(多个冒号)整体
if "[" in hostname:
host = hostname.split("[", 1)[1].split("]", 1)[0]
rest = hostname.split("]", 1)[1] if "]" in hostname else ""
if rest and not rest.startswith(":"):
raise ValueError(f"s3_hostname 的 IPv6 括号后只允许端口:{hostname}")
elif hostname.count(":") == 1:
host = hostname.split(":")[0]
else:
host = hostname
if not host or _endpoint_host_is_denied(host):
raise ValueError(f"端点不允许指向内网/保留地址:{hostname}")
return hostname
+18 -15
View File
@@ -481,7 +481,20 @@ class S3FileStorage(FileStorageInterface):
parts = []
try:
# 按顺序读取、验证并上传每个分片
# S3 requires every non-final part to contain at least 5 MiB.
part_buffer = bytearray()
part_number = 0
async def flush_part():
nonlocal part_number
if not part_buffer:
return
part_number += 1
response = await s3.upload_part(Bucket=self.bucket_name, Key=save_path,
UploadId=mpu_id, PartNumber=part_number, Body=bytes(part_buffer))
parts.append({'PartNumber': part_number, 'ETag': response['ETag']})
part_buffer.clear()
for i in range(chunk_info.total_chunks):
chunk_key = f"{chunk_dir}/{i}.part"
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
@@ -504,21 +517,11 @@ class S3FileStorage(FileStorageInterface):
file_sha256.update(chunk_data)
# 上传分片到 multipart upload
part_response = await s3.upload_part(
Bucket=self.bucket_name,
Key=save_path,
UploadId=mpu_id,
PartNumber=i + 1, # S3 part numbers start at 1
Body=chunk_data
)
parts.append({
'PartNumber': i + 1,
'ETag': part_response['ETag']
})
# 释放内存
part_buffer.extend(chunk_data)
del chunk_data
if len(part_buffer) >= 5 * 1024 * 1024:
await flush_part()
await flush_part()
# 完成 multipart upload
await s3.complete_multipart_upload(
+1 -1
View File
@@ -1,7 +1,7 @@
version: "3"
services:
file-code-box:
image: local/filecodebox:2.7.0 # x-release-please-version
image: local/filecodebox:2.7.1 # x-release-please-version
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
+5
View File
@@ -1,5 +1,10 @@
# Changelog
## 2.7.1 定制整合(2026-10-07)
* 整合出站地址校验、未知长度上传、API 404、下载令牌和 S3 小分片合并修复。
* 升级官方运行依赖,保留 CloudDrive 与定制管理功能。
## [2.5.6](https://github.com/vastsa/FileCodeBox/compare/v2.5.5...v2.5.6) (2026-09-01)
+5
View File
@@ -1,5 +1,10 @@
## [Unreleased]
## 2.7.1 Custom integration (2026-10-07)
* Integrate outbound endpoint validation, unknown-size uploads, API 404 responses, download tokens and small S3 multipart chunks.
* Update upstream runtime dependencies while preserving CloudDrive and custom administration features.
<!-- Current release: 2.5.6 x-release-please-version -->
### Added
+13
View File
@@ -892,6 +892,19 @@ async def theme_asset(asset_path: str):
@app.exception_handler(404)
async def not_found_handler(request, exc=None):
if request.url.path.startswith(("/assets/", "/theme-assets/")):
return PlainTextResponse("Not found", status_code=404)
# An API-raised 404 stays JSON even when a browser asks for HTML.
if (request.scope.get("route") is None and request.method in {"GET", "HEAD"}
and "text/html" in request.headers.get("accept", "")):
try:
return await index(request, exc)
except HTTPException:
pass
return JSONResponse(status_code=404, content={"code": 404, "message": "Not Found", "msg": "Not Found", "detail": "资源不存在"})
@app.get("/")
async def index(request=None, exc=None):
if request is not None and request.url.path.startswith(("/assets/", "/theme-assets/")):
+5 -5
View File
@@ -1,10 +1,10 @@
aioboto3==15.5.0
aiohttp==3.14.2
aiohttp==3.14.3
aiofiles==25.1.0
fastapi==0.139.2
starlette==1.3.1
pydantic==2.12.5
uvicorn==0.51.0
fastapi==0.141.1
starlette==1.6.0
pydantic==2.13.5
uvicorn==0.53.0
tortoise-orm==0.25.3
python-multipart==0.0.32
grpcio==1.80.0
+149
View File
@@ -0,0 +1,149 @@
import hashlib
import io
import os
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import httpx
from fastapi import HTTPException
from starlette.datastructures import UploadFile
from apps.admin.services import ConfigService
from apps.base.models import KeyValue, UploadChunk
from apps.base.views import validate_file_size
from core.security import validate_outbound_endpoint, validate_outbound_hostname
from core.settings import settings
from tests.helpers import init_memory_db, close_db
class EndpointValidationTests(unittest.TestCase):
def test_production_rejects_internal_urls_and_hostname_bypasses(self):
dns = [(None, None, None, None, ('127.0.0.1', 0))]
with patch.dict(os.environ, {'APP_ENV': 'production'}), patch('core.security.socket.getaddrinfo', return_value=dns):
for value in ['http://127.0.0.1', 'http://169.254.169.254', 'http://clouddrive:19798/dav', 'http://127.1', 'http://2130706433', 'https://dns-trick.example', 'file:///etc/passwd', 'gopher://127.0.0.1']:
with self.subTest(value=value), self.assertRaises(ValueError):
validate_outbound_endpoint(value)
for value in ['localhost', '127.1', '[::1]:9000', 'evil.example@127.0.0.1', 'https://public.example', 'nas.local', 'dns-trick.example']:
with self.subTest(value=value), self.assertRaises(ValueError):
validate_outbound_hostname(value)
def test_public_endpoints_normalize_and_development_keeps_internal_support(self):
dns = [(None, None, None, None, ('8.8.8.8', 0))]
with patch.dict(os.environ, {'APP_ENV': 'production'}), patch('core.security.socket.getaddrinfo', return_value=dns):
self.assertEqual(validate_outbound_endpoint(' https://public.example:9000 '), 'https://public.example:9000')
self.assertEqual(validate_outbound_hostname(' public.example:9000 '), 'public.example:9000')
self.assertEqual(validate_outbound_endpoint(''), '')
with patch.dict(os.environ, {'APP_ENV': 'development'}):
self.assertEqual(validate_outbound_endpoint('http://clouddrive:19798/dav'), 'http://clouddrive:19798/dav')
self.assertEqual(validate_outbound_hostname('127.0.0.1:9000'), '127.0.0.1:9000')
class Upgrade271IntegrationTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.original = dict(settings.user_config)
await init_memory_db()
async def asyncTearDown(self):
settings.user_config = self.original
await close_db()
async def test_existing_internal_dav_survives_unrelated_settings_save(self):
config = {**settings.default_config, 'webdav_url': 'http://clouddrive:19798/dav', 's3_hostname': 'nas.local'}
await KeyValue.create(key='settings', value=config)
with patch.dict(os.environ, {'APP_ENV': 'production'}):
await ConfigService().update_config({'name': 'new title', 'webdav_url': config['webdav_url']})
stored = (await KeyValue.get(key='settings')).value
self.assertEqual(stored['webdav_url'], config['webdav_url'])
self.assertEqual(stored['name'], 'new title')
for update in [{'webdav_url': 'http://127.0.0.1'}, {'s3_hostname': 'evil.example@127.0.0.1'}, {'s3_endpoint_url': 'http://169.254.169.254'}]:
with self.subTest(update=update), self.assertRaises(HTTPException) as error:
await ConfigService().update_config(update)
self.assertEqual(error.exception.status_code, 400)
self.assertEqual((await KeyValue.get(key='settings')).value, stored)
async def test_unknown_upload_size_measures_and_resets_file(self):
for spool in [False, True]:
file_obj = tempfile.SpooledTemporaryFile(max_size=2) if spool else io.BytesIO()
file_obj.write(b'payload');file_obj.seek(3)
file = UploadFile(file=file_obj, filename='size.bin', size=None)
try:
self.assertEqual(await validate_file_size(file, 7), 7)
self.assertEqual(await file.read(), b'payload')
with self.assertRaises(HTTPException) as error:
await validate_file_size(file, 6)
self.assertEqual(error.exception.status_code, 403)
finally:
await file.close()
async def test_api_404_is_json_and_unknown_html_navigation_keeps_spa(self):
from main import app
from core.utils import hash_password
await KeyValue.create(key='settings', value={**settings.default_config, 'admin_token': hash_password('test-271'), 'jwt_secret': 's'*48})
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, 'index.html').write_text('<html>test SPA</html>')
with patch('main.resolve_theme_root', return_value=Path(tmp)), patch('main.resolve_theme_file', return_value=Path(tmp, 'index.html')):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
missing = await client.get('/no-such-api', headers={'Accept': 'application/json'})
self.assertEqual(missing.status_code, 404);self.assertEqual(missing.json()['code'], 404)
endpoint404 = await client.get('/chunk/upload/status/not-present', headers={'Accept':'text/html'})
self.assertEqual(endpoint404.status_code,404);self.assertIn('application/json',endpoint404.headers['content-type'])
navigation = await client.get('/some/spa/path', headers={'Accept': 'text/html'})
self.assertEqual(navigation.status_code, 200);self.assertIn('test SPA', navigation.text)
# A matched endpoint's HTTPException must never become a successful HTML page.
from main import not_found_handler
request = SimpleNamespace(url=SimpleNamespace(path='/share/file'),method='GET',headers={'accept':'text/html'},scope={'route':object()})
self.assertEqual((await not_found_handler(request)).status_code, 404)
async def test_download_accepts_time_windows_and_rejects_wrong_or_unicode_keys(self):
from fastapi import FastAPI
from apps.base.views import share_api
from core.utils import get_select_token
from apps.base.utils import ip_limit
settings.user_config = {**settings.default_config, 'file_storage': 'local', 'jwt_secret': 'test-271-key-'*4}
for limiter in ip_limit.values():
limiter.ips.clear()
app = FastAPI();app.include_router(share_api)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
uploaded = await client.post('/share/text/',data={'text':'boundary test','expire_style':'day'})
self.assertEqual(uploaded.status_code,200,uploaded.text)
code = uploaded.json()['detail']['code']
for offset in (0,1):
token = await get_select_token(code,offset=offset)
response = await client.get('/share/download',params={'code':code,'key':token})
self.assertEqual(response.status_code,200,response.text)
for key in ('wrong','密钥'*32,await get_select_token('other-code')):
response = await client.get('/share/download',params={'code':code,'key':key})
self.assertEqual(response.status_code,403,response.text)
async def test_s3_small_chunks_merge_with_legal_parts_and_abort_corruption(self):
from moto.server import ThreadedMotoServer
from core.storage import S3FileStorage
server = ThreadedMotoServer('127.0.0.1', 0);server.start()
endpoint = f'http://127.0.0.1:{server._server.server_port}'
settings.user_config = {**self.original, 's3_endpoint_url': endpoint, 's3_access_key_id': 'testing', 's3_secret_access_key': 'testing', 's3_bucket_name': 'test-271-bucket', 's3_region_name': 'us-east-1', 's3_signature_version': 's3v4'}
try:
storage = S3FileStorage()
async with storage._client() as s3:
await s3.create_bucket(Bucket=storage.bucket_name)
chunks = [b'a'*(2*1024*1024), b'b'*(2*1024*1024), b'c'*(2*1024*1024), b'last']
info = SimpleNamespace(total_chunks=len(chunks), chunk_size=2*1024*1024, file_size=sum(map(len,chunks)))
path = 'share/data/271/combined.bin'
for index, data in enumerate(chunks):
await storage.save_chunk('s3-271', index, data, hashlib.sha256(data).hexdigest(), path)
await UploadChunk.create(upload_id='s3-271', chunk_index=index, chunk_hash=hashlib.sha256(data).hexdigest(), completed=True, total_chunks=info.total_chunks, file_size=info.file_size, chunk_size=info.chunk_size, file_name='combined.bin', save_path=path)
_, digest = await storage.merge_chunks('s3-271', info, path)
self.assertEqual(digest, hashlib.sha256(b''.join(chunks)).hexdigest())
async with storage._client() as s3:
response = await s3.get_object(Bucket=storage.bucket_name, Key=path)
self.assertEqual(await response['Body'].read(), b''.join(chunks))
await UploadChunk.filter(upload_id='s3-271',chunk_index=2).update(chunk_hash='invalid')
with self.assertRaises(ValueError):
await storage.merge_chunks('s3-271', info, path)
async with storage._client() as s3:
pending = await s3.list_multipart_uploads(Bucket=storage.bucket_name)
self.assertFalse(pending.get('Uploads'))
finally:
server.stop()