🔀 合并 FileCodeBox 2.5.4 安全更新
同步官方 2.5.4 的初始化、安全、容量控制与上传校验,并保留 2026 主题、动态资源缓存和管理后台统计能力。 - 使用原子领取和容量预留,补齐文件校验、限流、令牌轮换与路径防护 - 保留三主题构建、2026 静态资源隔离及 TransferStats 生命周期记录 - 已通过容器生产镜像构建、23 项安全与分享回归测试、Python 编译检查和 Dockerfile 检查
This commit is contained in:
commit
0be5a31a59
121 files changed
+5302
-34718
No files matched your search
+54
-14
@@ -8,27 +8,60 @@ import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import settings
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
||||
def _get_jwt_secret() -> bytes:
|
||||
secret = getattr(settings, "jwt_secret", "")
|
||||
if not secret:
|
||||
raise RuntimeError("JWT签名密钥未初始化")
|
||||
return secret.encode()
|
||||
|
||||
|
||||
def get_admin_session_expire_seconds() -> int:
|
||||
try:
|
||||
expires_in = int(
|
||||
getattr(settings, "adminSessionExpire", ADMIN_SESSION_EXPIRE_DEFAULT)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= expires_in <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or expires_in % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
return expires_in
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int | None = None) -> str:
|
||||
"""
|
||||
创建JWT token
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
token_lifetime = (
|
||||
get_admin_session_expire_seconds() if expires_in is None else expires_in
|
||||
)
|
||||
header = base64.urlsafe_b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps(
|
||||
{**data, "exp": int(time.time()) + token_lifetime},
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
).decode().rstrip("=")
|
||||
|
||||
signature = hmac.new(
|
||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
||||
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
signature = base64.urlsafe_b64encode(signature).decode().rstrip("=")
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
|
||||
@@ -44,17 +77,24 @@ def verify_token(token: str) -> dict:
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
_get_jwt_secret(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
expected_signature_b64 = (
|
||||
base64.urlsafe_b64encode(expected_signature).decode().rstrip("=")
|
||||
)
|
||||
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
payload = json.loads(base64.b64decode(payload_b64))
|
||||
# 解码payload(兼容历史标准 base64 与 urlsafe base64)
|
||||
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
|
||||
try:
|
||||
payload_bytes = base64.urlsafe_b64decode(padded)
|
||||
except Exception:
|
||||
payload_bytes = base64.b64decode(padded)
|
||||
payload = json.loads(payload_bytes)
|
||||
|
||||
# 检查是否过期
|
||||
if payload.get("exp", 0) < time.time():
|
||||
|
||||
+130
-28
@@ -1,16 +1,26 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from core.response import APIResponse
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.settings import settings
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from core.config import refresh_settings
|
||||
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic
|
||||
|
||||
from apps.base.utils import get_expire_info, get_file_path_name
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
from fastapi import HTTPException
|
||||
from core.settings import data_root
|
||||
from core.utils import get_now, hash_password, is_password_hashed
|
||||
@@ -594,8 +604,23 @@ class FileService:
|
||||
remaining_downloads = (
|
||||
max(file_code.expired_count, 0) if file_code.expired_count >= 0 else None
|
||||
)
|
||||
item = await file_codes_pydantic.from_tortoise_orm(file_code)
|
||||
data = item.model_dump()
|
||||
data = {
|
||||
"id": file_code.id,
|
||||
"code": file_code.code,
|
||||
"prefix": file_code.prefix,
|
||||
"suffix": file_code.suffix,
|
||||
"uuid_file_name": file_code.uuid_file_name,
|
||||
"file_path": file_code.file_path,
|
||||
"size": file_code.size or 0,
|
||||
"text": file_code.text,
|
||||
"expired_at": file_code.expired_at,
|
||||
"expired_count": file_code.expired_count,
|
||||
"used_count": file_code.used_count,
|
||||
"created_at": file_code.created_at,
|
||||
"file_hash": file_code.file_hash,
|
||||
"is_chunked": file_code.is_chunked,
|
||||
"upload_id": file_code.upload_id,
|
||||
}
|
||||
data.update(
|
||||
{
|
||||
"name": name,
|
||||
@@ -1512,25 +1537,36 @@ class FileService:
|
||||
if not await local_file.exists():
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
|
||||
text = await local_file.read()
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
item.expire_value, item.expire_style
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(item)
|
||||
|
||||
await self.file_storage.save_file(text, save_path)
|
||||
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=uuid_file_name,
|
||||
file_path=path,
|
||||
size=local_file.size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
reservation_token = f"local:{uuid.uuid4().hex}"
|
||||
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600)
|
||||
try:
|
||||
text = await local_file.read()
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
item.expire_value, item.expire_style
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(
|
||||
item
|
||||
)
|
||||
await self.file_storage.save_file(text, save_path)
|
||||
try:
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=uuid_file_name,
|
||||
file_path=path,
|
||||
size=local_file.size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
except Exception:
|
||||
await self.file_storage.delete_file(
|
||||
FileCodes(file_path=path, uuid_file_name=uuid_file_name)
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
await release_storage(reservation_token)
|
||||
|
||||
return {
|
||||
"code": code,
|
||||
@@ -1540,9 +1576,12 @@ class FileService:
|
||||
|
||||
class ConfigService:
|
||||
INT_FIELDS = {
|
||||
"adminSessionExpire",
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"openUpload",
|
||||
@@ -1551,6 +1590,7 @@ class ConfigService:
|
||||
"serverPort",
|
||||
"serverWorkers",
|
||||
"showAdminAddr",
|
||||
"storageLimit",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
@@ -1559,20 +1599,30 @@ class ConfigService:
|
||||
FLOAT_FIELDS = {"opacity"}
|
||||
|
||||
def get_config(self):
|
||||
return dict(settings.items())
|
||||
config = dict(settings.items())
|
||||
config["admin_token"] = ""
|
||||
for key in INTERNAL_CONFIG_KEYS:
|
||||
config.pop(key, None)
|
||||
return config
|
||||
|
||||
async def update_config(self, data: dict):
|
||||
current_config = dict(settings.items())
|
||||
next_config = dict(current_config)
|
||||
update_data = {
|
||||
key: value for key, value in data.items() if key in settings.default_config
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
||||
}
|
||||
|
||||
admin_token = update_data.get("admin_token")
|
||||
admin_password_changed = False
|
||||
if admin_token is None or admin_token == "":
|
||||
update_data.pop("admin_token", None)
|
||||
elif not is_password_hashed(admin_token):
|
||||
update_data["admin_token"] = hash_password(admin_token)
|
||||
admin_password_changed = True
|
||||
else:
|
||||
admin_password_changed = True
|
||||
|
||||
for key, value in update_data.items():
|
||||
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
|
||||
@@ -1588,6 +1638,32 @@ class ConfigService:
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
|
||||
|
||||
try:
|
||||
session_expire = int(next_config.get("adminSessionExpire"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 配置值格式错误",
|
||||
)
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["adminSessionExpire"] = session_expire
|
||||
|
||||
if int(next_config.get("storageLimit", 0)) < 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="storageLimit 不能小于 0",
|
||||
)
|
||||
|
||||
if admin_password_changed:
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings()
|
||||
|
||||
@@ -1616,9 +1692,35 @@ class LocalFileService:
|
||||
|
||||
class LocalFileClass:
|
||||
def __init__(self, file):
|
||||
self.file = file
|
||||
self.path = data_root / "local" / file
|
||||
if os.path.exists(self.path):
|
||||
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。
|
||||
raw_name = str(file or "")
|
||||
normalized = Path(raw_name).as_posix()
|
||||
# 输入本身不得包含路径分隔符或绝对路径形态。
|
||||
if (
|
||||
not raw_name
|
||||
or raw_name in {".", ".."}
|
||||
or normalized in {".", ".."}
|
||||
or "/" in normalized
|
||||
or normalized.startswith("~")
|
||||
or Path(raw_name).is_absolute()
|
||||
or Path(raw_name).name != raw_name
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
safe_name = Path(raw_name).name
|
||||
if not safe_name or safe_name in {".", ".."}:
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
local_root = (data_root / "local").resolve()
|
||||
candidate = (local_root / safe_name).resolve()
|
||||
try:
|
||||
candidate.relative_to(local_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="非法文件路径")
|
||||
|
||||
self.file = safe_name
|
||||
self.path = candidate
|
||||
if self.path.is_file():
|
||||
self.ctime = time.strftime(
|
||||
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
|
||||
)
|
||||
@@ -1638,4 +1740,4 @@ class LocalFileClass:
|
||||
os.remove(self.path)
|
||||
|
||||
async def exists(self):
|
||||
return os.path.exists(self.path)
|
||||
return self.path.is_file()
|
||||
+22
-4
@@ -31,9 +31,15 @@ from apps.admin.schemas import (
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats
|
||||
from apps.admin.dependencies import create_token
|
||||
from apps.admin.dependencies import (
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
verify_token,
|
||||
)
|
||||
|
||||
from core.settings import settings
|
||||
from core.utils import get_now, verify_password
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
@@ -49,12 +55,24 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
|
||||
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
token = create_token({"is_admin": True})
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
|
||||
Reference in new issue
Block a user