Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00f1f1d8da | ||
|
|
5a7195c5c7 | ||
|
|
da1dd06655 | ||
|
|
d510aa7f57 | ||
|
|
cebac32145 | ||
|
|
f76d1e9841 | ||
|
|
287b647da1 | ||
|
|
fbcd4a5b2b | ||
|
|
fc0cbeb4f0 | ||
|
|
24bf6e1a81 | ||
|
|
0ee2f046dd | ||
|
|
eda0a3127a |
No files matched your search
|
Before Width: | Height: | Size: 571 KiB |
|
Before Width: | Height: | Size: 557 KiB |
|
Before Width: | Height: | Size: 205 KiB |
|
Before Width: | Height: | Size: 679 KiB |
|
Before Width: | Height: | Size: 684 KiB |
|
Before Width: | Height: | Size: 411 KiB |
|
Before Width: | Height: | Size: 431 KiB |
|
Before Width: | Height: | Size: 579 KiB |
|
Before Width: | Height: | Size: 201 KiB |
|
Before Width: | Height: | Size: 254 KiB |
|
Before Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 514 KiB |
|
Before Width: | Height: | Size: 674 KiB |
|
Before Width: | Height: | Size: 678 KiB |
|
Before Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 233 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 138 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 68 KiB |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "2.5.2"
|
||||
".": "2.5.5"
|
||||
}
|
||||
@@ -1518,6 +1518,8 @@ class ConfigService:
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"openUpload",
|
||||
|
||||
@@ -38,6 +38,7 @@ from apps.admin.dependencies import (
|
||||
)
|
||||
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)]
|
||||
@@ -53,8 +54,10 @@ 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="密码错误")
|
||||
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""文件类型校验:扩展名 / MIME 白名单 + magic bytes 防伪造。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from fnmatch import fnmatchcase
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileKind:
|
||||
name: str
|
||||
extensions: tuple[str, ...]
|
||||
mimes: tuple[str, ...]
|
||||
signatures: tuple[bytes, ...]
|
||||
|
||||
|
||||
FILE_KINDS: tuple[FileKind, ...] = (
|
||||
FileKind("png", (".png",), ("image/png",), (b"\x89PNG\r\n\x1a\n",)),
|
||||
FileKind("jpg", (".jpg", ".jpeg"), ("image/jpeg",), (b"\xff\xd8\xff",)),
|
||||
FileKind("gif", (".gif",), ("image/gif",), (b"GIF87a", b"GIF89a")),
|
||||
FileKind("webp", (".webp",), ("image/webp",), ()),
|
||||
FileKind("bmp", (".bmp",), ("image/bmp", "image/x-ms-bmp"), (b"BM",)),
|
||||
FileKind("pdf", (".pdf",), ("application/pdf",), (b"%PDF",)),
|
||||
FileKind(
|
||||
"zip",
|
||||
(".zip", ".docx", ".xlsx", ".pptx", ".apk", ".jar"),
|
||||
(
|
||||
"application/zip",
|
||||
"application/x-zip-compressed",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"application/java-archive",
|
||||
"application/vnd.android.package-archive",
|
||||
),
|
||||
(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
|
||||
),
|
||||
FileKind(
|
||||
"rar",
|
||||
(".rar",),
|
||||
("application/x-rar-compressed", "application/vnd.rar"),
|
||||
(b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"),
|
||||
),
|
||||
FileKind("7z", (".7z",), ("application/x-7z-compressed",), (b"7z\xbc\xaf'\x1c",)),
|
||||
FileKind("gz", (".gz", ".tgz"), ("application/gzip", "application/x-gzip"), (b"\x1f\x8b",)),
|
||||
FileKind(
|
||||
"mp3",
|
||||
(".mp3",),
|
||||
("audio/mpeg",),
|
||||
(b"ID3", b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"),
|
||||
),
|
||||
FileKind("mp4", (".mp4", ".m4a", ".mov"), ("video/mp4", "audio/mp4", "video/quicktime"), ()),
|
||||
FileKind(
|
||||
"exe",
|
||||
(".exe", ".dll", ".sys"),
|
||||
("application/x-msdownload", "application/x-dosexec"),
|
||||
(b"MZ",),
|
||||
),
|
||||
FileKind("elf", (".elf", ".so", ".o"), ("application/x-executable",), (b"\x7fELF",)),
|
||||
)
|
||||
|
||||
KNOWN_EXTENSIONS = {ext for kind in FILE_KINDS for ext in kind.extensions}
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = [item.strip() for item in raw_value.split(",")]
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = [str(item).strip() for item in raw_value]
|
||||
else:
|
||||
values = []
|
||||
normalized = [item.lower() for item in values if item]
|
||||
return normalized or ["*"]
|
||||
|
||||
|
||||
def _extension_of(file_name: str) -> str:
|
||||
return Path(file_name or "").suffix.lower()
|
||||
|
||||
|
||||
def _match_allow_rule(rule: str, file_name: str, content_type: str) -> bool:
|
||||
if rule in {"*", "*/*"}:
|
||||
return True
|
||||
if "/" in rule:
|
||||
return fnmatchcase(content_type, rule)
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
return file_name.endswith(extension)
|
||||
|
||||
|
||||
def is_type_allowed(file_name: str, content_type: Optional[str] = None) -> bool:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if any(rule in {"*", "*/*"} for rule in allowed):
|
||||
return True
|
||||
normalized_name = (file_name or "").strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
return any(
|
||||
_match_allow_rule(rule, normalized_name, normalized_content_type)
|
||||
for rule in allowed
|
||||
)
|
||||
|
||||
|
||||
def detect_file_kind(header: bytes) -> Optional[FileKind]:
|
||||
if not header:
|
||||
return None
|
||||
|
||||
if len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "webp")
|
||||
|
||||
if len(header) >= 12 and header[4:8] == b"ftyp":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "mp4")
|
||||
|
||||
candidates: list[tuple[int, FileKind]] = []
|
||||
for kind in FILE_KINDS:
|
||||
for signature in kind.signatures:
|
||||
if signature and header.startswith(signature):
|
||||
candidates.append((len(signature), kind))
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: item[0], reverse=True)
|
||||
return candidates[0][1]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
if not is_type_allowed(file_name, content_type):
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
def _kind_matches_ext(kind: FileKind, extension: str) -> bool:
|
||||
return extension in kind.extensions
|
||||
|
||||
|
||||
def _kind_matches_mime(kind: FileKind, mime: str) -> bool:
|
||||
return mime in kind.mimes
|
||||
|
||||
|
||||
def validate_file_magic(
|
||||
file_name: str,
|
||||
content_type: Optional[str],
|
||||
header: Optional[bytes],
|
||||
) -> None:
|
||||
"""白名单通过后,用 magic bytes 防止扩展名 / MIME 伪造。"""
|
||||
validate_file_type(file_name, content_type)
|
||||
if not header:
|
||||
return
|
||||
|
||||
claimed_ext = _extension_of(file_name)
|
||||
claimed_mime = (content_type or "").strip().lower()
|
||||
detected = detect_file_kind(header)
|
||||
|
||||
if claimed_ext in KNOWN_EXTENSIONS:
|
||||
if detected is None or not _kind_matches_ext(detected, claimed_ext):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与扩展名不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
if claimed_mime and any(claimed_mime in kind.mimes for kind in FILE_KINDS):
|
||||
if detected is None or not _kind_matches_mime(detected, claimed_mime):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与 Content-Type 不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
allowed = normalize_allowed_file_types()
|
||||
if detected and not any(rule in {"*", "*/*"} for rule in allowed):
|
||||
allowed_by_detected = any(
|
||||
is_type_allowed(f"file{ext}", mime)
|
||||
for ext in detected.extensions
|
||||
for mime in (detected.mimes or (None,))
|
||||
)
|
||||
if not allowed_by_detected:
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def read_upload_header(file: UploadFile, size: int = 64) -> bytes:
|
||||
await file.seek(0)
|
||||
header = await file.read(size)
|
||||
await file.seek(0)
|
||||
return header or b""
|
||||
|
||||
|
||||
async def validate_upload_file(file: UploadFile) -> None:
|
||||
header = await read_upload_header(file)
|
||||
validate_file_magic(file.filename or "", file.content_type, header)
|
||||
|
||||
|
||||
def validate_header_bytes(
|
||||
file_name: str, content_type: Optional[str], header: bytes
|
||||
) -> None:
|
||||
validate_file_magic(file_name, content_type, header)
|
||||
@@ -43,6 +43,7 @@ async def get_chunk_file_path_name(
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
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}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(file_name)
|
||||
@@ -136,4 +137,5 @@ ip_limit = {
|
||||
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
|
||||
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import datetime
|
||||
from fnmatch import fnmatchcase
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
@@ -23,6 +22,7 @@ from apps.base.schemas import (
|
||||
CompleteUploadModel,
|
||||
PresignUploadInitRequest,
|
||||
)
|
||||
from apps.base.file_validation import validate_file_type, validate_upload_file, validate_header_bytes
|
||||
from apps.base.utils import (
|
||||
get_expire_info,
|
||||
get_file_path_name,
|
||||
@@ -106,36 +106,6 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
||||
return size
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = raw_value.replace(";", ",").split(",")
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = raw_value
|
||||
else:
|
||||
values = []
|
||||
|
||||
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
|
||||
return allowed or ["*"]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if "*" in allowed or "*/*" in allowed:
|
||||
return
|
||||
|
||||
normalized_name = file_name.strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
|
||||
for rule in allowed:
|
||||
if "/" in rule and fnmatchcase(normalized_content_type, rule):
|
||||
return
|
||||
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
if normalized_name.endswith(extension):
|
||||
return
|
||||
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def create_file_code(code, **kwargs):
|
||||
@@ -188,7 +158,7 @@ async def share_file(
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
validate_file_type(file.filename or "", file.content_type)
|
||||
await validate_upload_file(file)
|
||||
validate_expire_style(expire_style)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
|
||||
reservation_token = f"file:{uuid.uuid4().hex}"
|
||||
@@ -423,7 +393,8 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
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 = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
@@ -453,7 +424,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
chunk_hash=data.file_hash,
|
||||
chunk_index=-1,
|
||||
file_size=data.file_size,
|
||||
file_name=data.file_name,
|
||||
file_name=safe_file_name,
|
||||
).first()
|
||||
|
||||
if existing_session:
|
||||
@@ -489,7 +460,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
await reserve_storage(
|
||||
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:
|
||||
await UploadChunk.create(
|
||||
upload_id=upload_id,
|
||||
@@ -498,7 +471,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
file_size=data.file_size,
|
||||
chunk_size=data.chunk_size,
|
||||
chunk_hash=data.file_hash,
|
||||
file_name=data.file_name,
|
||||
file_name=safe_file_name,
|
||||
save_path=save_path,
|
||||
)
|
||||
except Exception:
|
||||
@@ -549,6 +522,8 @@ async def upload_chunk(
|
||||
|
||||
# 读取分片数据并计算哈希
|
||||
chunk_data = await chunk.read()
|
||||
if chunk_index == 0:
|
||||
validate_header_bytes(chunk_info.file_name, None, chunk_data[:64])
|
||||
chunk_size = len(chunk_data)
|
||||
|
||||
# 校验分片大小不超过声明的 chunk_size
|
||||
@@ -698,7 +673,8 @@ async def complete_upload(
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
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:
|
||||
# 合并文件并计算哈希
|
||||
@@ -717,7 +693,7 @@ async def complete_upload(
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
file_path=path,
|
||||
uuid_file_name=f"{prefix}{suffix}",
|
||||
uuid_file_name=safe_file_name,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
)
|
||||
@@ -727,7 +703,7 @@ async def complete_upload(
|
||||
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": chunk_info.file_name})
|
||||
return APIResponse(detail={"code": code, "name": safe_file_name})
|
||||
except ValueError as e:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except Exception as e:
|
||||
@@ -844,6 +820,7 @@ async def presign_upload_proxy(
|
||||
)
|
||||
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
await validate_upload_file(file)
|
||||
if abs(file_size - session.file_size) > 1024:
|
||||
raise HTTPException(400, "文件大小与声明不符")
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ SETUP_CONFIG_FIELDS = {
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"expireStyle",
|
||||
"max_save_seconds",
|
||||
"name",
|
||||
@@ -68,6 +70,8 @@ def _sync_ip_limits() -> None:
|
||||
ip_limit["metadata"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
ip_limit["login"].minutes = settings.loginMinute
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
|
||||
@@ -76,6 +76,8 @@ DEFAULT_CONFIG = {
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 10,
|
||||
"loginCount": 5,
|
||||
"loginMinute": 15,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
|
||||
@@ -116,6 +116,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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:2.5.2 # x-release-please-version
|
||||
image: lanol/filecodebox:2.5.5 # x-release-please-version
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
# Changelog
|
||||
|
||||
## [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)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* run Docker as root for volume compatibility ([fbcd4a5](https://github.com/vastsa/FileCodeBox/commit/fbcd4a5b2b788cdfc8e86d920f9c5a7299dc839a))
|
||||
* run Docker image as root for data volume compatibility ([fc0cbeb](https://github.com/vastsa/FileCodeBox/commit/fc0cbeb4f0c7485d2e7abc0501a5fd9b1456cc22))
|
||||
|
||||
## [2.5.3](https://github.com/vastsa/FileCodeBox/compare/v2.5.2...v2.5.3) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add magic-byte checks, login rate limits, and non-root Docker ([eda0a31](https://github.com/vastsa/FileCodeBox/commit/eda0a3127ab562b6a2cf828c0df4a93933c44526))
|
||||
* magic-byte file checks, admin login rate limit, non-root Docker ([0ee2f04](https://github.com/vastsa/FileCodeBox/commit/0ee2f046dd057fecceaee1059d72d67de3038f19))
|
||||
|
||||
## [2.5.2](https://github.com/vastsa/FileCodeBox/compare/v2.5.1...v2.5.2) (2026-07-23)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## [Unreleased]
|
||||
|
||||
<!-- Current release: 2.5.2 x-release-please-version -->
|
||||
<!-- Current release: 2.5.5 x-release-please-version -->
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
<img src="/screenshots/retrieve.webp" alt="FileCodeBox" width="860" />
|
||||
|
||||
<p><em>Share text and files anonymously with a passcode, like picking up a package</em></p>
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to
|
||||
|
||||
## Accessing the Admin Panel
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/login.webp" alt="Admin login" width="640" />
|
||||
</p>
|
||||
|
||||
### Login Method
|
||||
|
||||
The admin panel is located at the `/admin` path. Access method:
|
||||
@@ -39,6 +43,10 @@ The admin panel uses JWT (JSON Web Token) for authentication:
|
||||
|
||||
## Dashboard
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/dashboard.webp" alt="Dashboard" width="860" />
|
||||
</p>
|
||||
|
||||
After logging in, you first see the dashboard page, which displays the overall system status.
|
||||
|
||||
### Statistics
|
||||
@@ -67,6 +75,10 @@ Storage usage is displayed in bytes. For example, `10485760` represents approxim
|
||||
|
||||
## File Management
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/files.webp" alt="File management" width="860" />
|
||||
</p>
|
||||
|
||||
### File List
|
||||
|
||||
The file management page displays all shared files in the system, supporting pagination and search.
|
||||
@@ -200,6 +212,10 @@ Local file management is useful for:
|
||||
|
||||
## System Settings
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/settings.webp" alt="System settings" width="860" />
|
||||
</p>
|
||||
|
||||
### View Configuration
|
||||
|
||||
On the system settings page, you can view the current values of all configuration items. Configuration items are grouped by category:
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides simple and easy-to-use file and text sharing functionality.
|
||||
|
||||
## Sharing Methods
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Send page" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox supports two sharing methods:
|
||||
|
||||
1. **Text Sharing** - Share text content directly, suitable for code snippets, configuration files, etc.
|
||||
@@ -137,6 +141,10 @@ expire_value=5, expire_style=count
|
||||
|
||||
## Retrieving Files
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="Retrieve page" width="720" />
|
||||
</p>
|
||||
|
||||
### How to Use
|
||||
|
||||
1. Enter the extraction code in the "Retrieve File" area on the homepage
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides multiple flexible file upload methods, supporting both regu
|
||||
|
||||
## Upload Methods
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Upload and send page" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox supports the following upload methods:
|
||||
|
||||
### Drag and Drop Upload
|
||||
|
||||
@@ -38,7 +38,7 @@ docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v ./data:/app/data \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.5.2 # x-release-please-version
|
||||
lanol/filecodebox:2.5.5 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete the first-run setup.
|
||||
@@ -61,6 +61,26 @@ Open `http://localhost:12345` and complete the first-run setup.
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Interface preview
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="Retrieve files" width="860" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Send files" width="48%" />
|
||||
|
||||
<img src="/screenshots/dashboard.webp" alt="Admin dashboard" width="48%" />
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%"><img src="/screenshots/login.webp" alt="Admin login" /></td>
|
||||
<td width="33%"><img src="/screenshots/files.webp" alt="File management" /></td>
|
||||
<td width="33%"><img src="/screenshots/settings.webp" alt="System settings" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
::: warning Responsible use
|
||||
Use FileCodeBox only for lawful file and text sharing. Operators are responsible for deployment security, data compliance, and content moderation.
|
||||
:::
|
||||
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
<img src="/screenshots/retrieve.webp" alt="FileCodeBox" width="860" />
|
||||
|
||||
<p><em>匿名口令分享文本和文件,像拿快递一样取文件</em></p>
|
||||
|
||||
@@ -15,6 +15,28 @@
|
||||
</div>
|
||||
|
||||
|
||||
## 🖼️ 界面预览
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="提取文件" width="860" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="文件发送" width="48%" />
|
||||
|
||||
<img src="/screenshots/dashboard.webp" alt="管理仪表盘" width="48%" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/files.webp" alt="文件管理" width="48%" />
|
||||
|
||||
<img src="/screenshots/settings.webp" alt="系统设置" width="48%" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/login.webp" alt="管理登录" width="60%" />
|
||||
</p>
|
||||
|
||||
## 🚀 更新计划
|
||||
- [ ] 切片上传,同文件秒传,断点续传
|
||||
- [ ] 用户登录重构
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
|
||||
|
||||
## 访问管理面板
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/login.webp" alt="管理登录" width="640" />
|
||||
</p>
|
||||
|
||||
### 登录方式
|
||||
|
||||
管理面板位于 `/admin` 路径。访问方式:
|
||||
@@ -39,6 +43,10 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
|
||||
|
||||
## 仪表盘
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/dashboard.webp" alt="管理仪表盘" width="860" />
|
||||
</p>
|
||||
|
||||
登录后首先看到的是仪表盘页面,展示系统的整体运行状态。
|
||||
|
||||
### 统计指标
|
||||
@@ -67,6 +75,10 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
|
||||
|
||||
## 文件管理
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/files.webp" alt="文件管理" width="860" />
|
||||
</p>
|
||||
|
||||
### 文件列表
|
||||
|
||||
文件管理页面展示系统中所有已分享的文件,支持分页浏览和搜索。
|
||||
@@ -199,6 +211,10 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
|
||||
|
||||
## 系统设置
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/settings.webp" alt="系统设置" width="860" />
|
||||
</p>
|
||||
|
||||
### 查看配置
|
||||
|
||||
在系统设置页面可以查看当前所有配置项的值。配置项按类别分组显示:
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox 提供了简单易用的文件和文本分享功能。用户可以
|
||||
|
||||
## 分享方式
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="文件发送页面" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox 支持两种分享方式:
|
||||
|
||||
1. **文本分享** - 直接分享文本内容,适合代码片段、配置文件等
|
||||
@@ -136,6 +140,10 @@ expire_value=5, expire_style=count
|
||||
|
||||
## 提取文件
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="提取文件页面" width="720" />
|
||||
</p>
|
||||
|
||||
### 使用方法
|
||||
|
||||
1. 在首页的「提取文件」区域输入提取码
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox 提供了多种灵活的文件上传方式,支持普通上传和
|
||||
|
||||
## 上传方式
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="上传与发送页面" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox 支持以下几种上传方式:
|
||||
|
||||
### 拖拽上传
|
||||
|
||||
@@ -38,7 +38,7 @@ docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v ./data:/app/data \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.5.2 # x-release-please-version
|
||||
lanol/filecodebox:2.5.5 # x-release-please-version
|
||||
```
|
||||
|
||||
打开 `http://localhost:12345`,按引导完成首次初始化。
|
||||
@@ -61,6 +61,26 @@ docker run -d --restart unless-stopped \
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## 界面预览
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="提取文件" width="860" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="文件发送" width="48%" />
|
||||
|
||||
<img src="/screenshots/dashboard.webp" alt="管理仪表盘" width="48%" />
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%"><img src="/screenshots/login.webp" alt="管理登录" /></td>
|
||||
<td width="33%"><img src="/screenshots/files.webp" alt="文件管理" /></td>
|
||||
<td width="33%"><img src="/screenshots/settings.webp" alt="系统设置" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
::: warning 使用须知
|
||||
请仅将 FileCodeBox 用于合法的文件与文本分享。服务运营者应自行负责部署安全、数据合规和内容管理。
|
||||
:::
|
||||
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 68 KiB |
@@ -181,6 +181,12 @@ def parse_setup_options(data: dict) -> dict:
|
||||
"errorMinute": parse_int_field(
|
||||
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
|
||||
),
|
||||
"loginCount": parse_int_field(
|
||||
data, "loginCount", DEFAULT_CONFIG["loginCount"], "登录失败次数限制", 1
|
||||
),
|
||||
"loginMinute": parse_int_field(
|
||||
data, "loginMinute", DEFAULT_CONFIG["loginMinute"], "登录失败检测窗口", 1
|
||||
),
|
||||
"expireStyle": expire_styles,
|
||||
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
|
||||
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
|
||||
@@ -228,6 +234,12 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
error_count = html.escape(
|
||||
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
|
||||
)
|
||||
login_minute = html.escape(
|
||||
get_form_value(form, "loginMinute", str(DEFAULT_CONFIG["loginMinute"]))
|
||||
)
|
||||
login_count = html.escape(
|
||||
get_form_value(form, "loginCount", str(DEFAULT_CONFIG["loginCount"]))
|
||||
)
|
||||
open_upload_checked = (
|
||||
" checked" if normalize_bool_field(form, "openUpload", True) else ""
|
||||
)
|
||||
@@ -576,6 +588,12 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="loginCount">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="loginCount" name="loginCount" type="number" min="1" value="{login_count}" required>
|
||||
<input name="loginMinute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="save_time_value">最长保存时间</label>
|
||||
<div class="row">
|
||||
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
|
||||
@@ -744,6 +762,8 @@ async def load_config():
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
ip_limit["login"].minutes = settings.loginMinute
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
|
||||
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
|
||||
|
||||
|
||||
@@ -17,14 +17,14 @@
|
||||
|
||||
<br />
|
||||
|
||||
<img src="./.github/images/readme/retrieve-dark.png" alt="FileCodeBox 取件页面" width="860" />
|
||||
<img src="./.github/images/readme/banner_zh.webp" alt="FileCodeBox" width="100%" />
|
||||
|
||||
</div>
|
||||
|
||||
## 一条命令开始
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.2 # x-release-please-version
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.5 # x-release-please-version
|
||||
```
|
||||
|
||||
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
|
||||
@@ -43,18 +43,18 @@ docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%"><img src="./.github/images/readme/send.png" alt="文件发送页面" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/dashboard.png" alt="管理仪表盘" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/send.webp" alt="文件发送页面" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/dashboard.webp" alt="管理仪表盘" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/images/readme/mobile-retrieve.png" alt="移动端取件" width="29%" />
|
||||
|
||||
<img src="./.github/images/readme/mobile-send.png" alt="移动端发送" width="29%" />
|
||||
|
||||
<img src="./.github/images/readme/mobile-files.png" alt="移动端管理" width="29%" />
|
||||
</p>
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%"><img src="./.github/images/readme/login.webp" alt="管理登录" /></td>
|
||||
<td width="33%"><img src="./.github/images/readme/files.webp" alt="文件管理" /></td>
|
||||
<td width="33%"><img src="./.github/images/readme/settings.webp" alt="系统设置" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div align="center">
|
||||
|
||||
|
||||
@@ -17,14 +17,14 @@ A lightweight, modern, self-hosted file sharing service. No account required—u
|
||||
|
||||
<br />
|
||||
|
||||
<img src="./.github/images/readme/retrieve-dark.png" alt="FileCodeBox retrieval screen" width="860" />
|
||||
<img src="./.github/images/readme/banner_en.webp" alt="FileCodeBox" width="100%" />
|
||||
|
||||
</div>
|
||||
|
||||
## Start with one command
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.2 # x-release-please-version
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.5 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
|
||||
@@ -43,18 +43,18 @@ Open `http://localhost:12345` and complete first-run setup. Pin a version in pro
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%"><img src="./.github/images/readme/send.png" alt="File sharing screen" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/dashboard.png" alt="Admin dashboard" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/send.webp" alt="File sharing screen" /></td>
|
||||
<td width="50%"><img src="./.github/images/readme/dashboard.webp" alt="Admin dashboard" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/images/readme/mobile-retrieve.png" alt="Mobile retrieval" width="29%" />
|
||||
|
||||
<img src="./.github/images/readme/mobile-send.png" alt="Mobile sharing" width="29%" />
|
||||
|
||||
<img src="./.github/images/readme/mobile-files.png" alt="Mobile administration" width="29%" />
|
||||
</p>
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%"><img src="./.github/images/readme/login.webp" alt="Admin login" /></td>
|
||||
<td width="33%"><img src="./.github/images/readme/files.webp" alt="File management" /></td>
|
||||
<td width="33%"><img src="./.github/images/readme/settings.webp" alt="System settings" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div align="center">
|
||||
|
||||
|
||||
@@ -73,6 +73,8 @@ class SetupOptionTests(unittest.TestCase):
|
||||
"uploadMinute": "2",
|
||||
"errorCount": "5",
|
||||
"errorMinute": "1",
|
||||
"loginCount": "4",
|
||||
"loginMinute": "20",
|
||||
"openUpload": ["0", "1"],
|
||||
"enableChunk": "0",
|
||||
"code_generate_type": "secret",
|
||||
@@ -87,6 +89,8 @@ class SetupOptionTests(unittest.TestCase):
|
||||
self.assertEqual(options["uploadMinute"], 2)
|
||||
self.assertEqual(options["errorCount"], 5)
|
||||
self.assertEqual(options["errorMinute"], 1)
|
||||
self.assertEqual(options["loginCount"], 4)
|
||||
self.assertEqual(options["loginMinute"], 20)
|
||||
self.assertEqual(options["openUpload"], 1)
|
||||
self.assertEqual(options["enableChunk"], 0)
|
||||
self.assertEqual(options["code_generate_type"], "secret")
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.admin import views as admin_views
|
||||
from apps.admin.schemas import LoginData
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.file_validation import detect_file_kind, validate_file_magic, validate_file_type
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import settings
|
||||
from core.utils import hash_password
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_detects_common_signatures(self):
|
||||
self.assertEqual(detect_file_kind(b"\x89PNG\r\n\x1a\nxxxx").name, "png")
|
||||
self.assertEqual(detect_file_kind(b"\xff\xd8\xff\xe0xxxx").name, "jpg")
|
||||
self.assertEqual(detect_file_kind(b"%PDF-1.7").name, "pdf")
|
||||
self.assertEqual(detect_file_kind(b"PK\x03\x04xxxx").name, "zip")
|
||||
self.assertEqual(detect_file_kind(b"RIFF\x00\x00\x00\x00WEBPxxxx").name, "webp")
|
||||
self.assertEqual(detect_file_kind(b"\x00\x00\x00\x18ftypmp42").name, "mp4")
|
||||
|
||||
def test_rejects_extension_spoofing(self):
|
||||
settings.allowed_file_types = ["*"]
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_file_magic("photo.png", "image/png", b"MZ" + b"\x00" * 20)
|
||||
self.assertEqual(ctx.exception.status_code, 403)
|
||||
self.assertIn("扩展名", ctx.exception.detail)
|
||||
|
||||
def test_rejects_content_type_spoofing(self):
|
||||
settings.allowed_file_types = ["*"]
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_file_magic("blob.bin", "image/png", b"MZ" + b"\x00" * 20)
|
||||
self.assertEqual(ctx.exception.status_code, 403)
|
||||
|
||||
def test_accepts_matching_png(self):
|
||||
settings.allowed_file_types = [".png", "image/*"]
|
||||
validate_file_magic("a.png", "image/png", b"\x89PNG\r\n\x1a\nxxxx")
|
||||
|
||||
def test_whitelist_still_enforced(self):
|
||||
settings.allowed_file_types = [".png"]
|
||||
with self.assertRaises(HTTPException):
|
||||
validate_file_type("a.exe", "application/x-msdownload")
|
||||
|
||||
|
||||
class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
settings.admin_token = hash_password("correct-password-123")
|
||||
settings.jwt_secret = "j" * 48
|
||||
settings.loginCount = 3
|
||||
settings.loginMinute = 15
|
||||
self._original_login_limiter = ip_limit["login"]
|
||||
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
|
||||
|
||||
def tearDown(self):
|
||||
ip_limit["login"] = self._original_login_limiter
|
||||
super().tearDown()
|
||||
|
||||
def test_failed_logins_are_rate_limited(self):
|
||||
async def attempt(password: str):
|
||||
return await admin_views.login(
|
||||
data=LoginData(password=password), ip="203.0.113.10"
|
||||
)
|
||||
|
||||
for _ in range(3):
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
asyncio.run(attempt("wrong-password"))
|
||||
self.assertEqual(ctx.exception.status_code, 401)
|
||||
|
||||
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
|
||||
|
||||
def test_successful_login_does_not_consume_failure_quota(self):
|
||||
result = asyncio.run(
|
||||
admin_views.login(
|
||||
data=LoginData(password="correct-password-123"), ip="198.51.100.8"
|
||||
)
|
||||
)
|
||||
self.assertIn("token", result.detail)
|
||||
self.assertTrue(ip_limit["login"].check_ip("198.51.100.8"))
|
||||
|
||||
|
||||
class DockerRuntimeUserTests(unittest.TestCase):
|
||||
def test_dockerfile_defaults_to_root_for_volume_compatibility(self):
|
||||
# 默认 root:兼容已有 data 卷权限;如需非 root 可由编排层自行指定 user
|
||||
text = Path("Dockerfile").read_text()
|
||||
self.assertNotIn("USER appuser", text)
|
||||
compose = Path("docker-compose.yml").read_text()
|
||||
self.assertNotIn('user: "1000:1000"', compose)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -6,10 +7,16 @@ from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
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.dependencies import create_token, verify_token
|
||||
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.storage import SystemFileStorage
|
||||
from core.utils import hash_password, verify_password
|
||||
@@ -71,11 +78,133 @@ class SystemStoragePathTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
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):
|
||||
target = self.storage._resolve_safe_path("share/data/a/b.txt")
|
||||
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):
|
||||
def setUp(self):
|
||||
settings.jwt_secret = "j" * 48
|
||||
|
||||