fix: #465 restrict uploads by allowed file types
This commit is contained in:
1 parent
135dfdda9d
commit
aa6904a12c
4 files changed
+70
No files matched your search
@@ -1,4 +1,5 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
from fnmatch import fnmatchcase
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
@@ -96,6 +97,38 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
|||||||
return size
|
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):
|
async def create_file_code(code, **kwargs):
|
||||||
return await FileCodes.create(code=code, **kwargs)
|
return await FileCodes.create(code=code, **kwargs)
|
||||||
|
|
||||||
@@ -136,6 +169,7 @@ async def share_file(
|
|||||||
ip: str = Depends(ip_limit["upload"]),
|
ip: str = Depends(ip_limit["upload"]),
|
||||||
):
|
):
|
||||||
file_size = await validate_file_size(file, settings.uploadSize)
|
file_size = await validate_file_size(file, settings.uploadSize)
|
||||||
|
validate_file_type(file.filename or "", file.content_type)
|
||||||
if expire_style not in settings.expireStyle:
|
if expire_style not in settings.expireStyle:
|
||||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||||
@@ -305,6 +339,7 @@ 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)
|
||||||
# 服务端校验:根据 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
|
||||||
@@ -624,6 +659,7 @@ async def presign_upload_init(
|
|||||||
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
||||||
):
|
):
|
||||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||||
|
validate_file_type(data.file_name)
|
||||||
if data.file_size > settings.uploadSize:
|
if data.file_size > settings.uploadSize:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
403,
|
403,
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ DEFAULT_CONFIG = {
|
|||||||
"admin_token": "FileCodeBox2023",
|
"admin_token": "FileCodeBox2023",
|
||||||
"openUpload": 1,
|
"openUpload": 1,
|
||||||
"uploadSize": 1024 * 1024 * 10,
|
"uploadSize": 1024 * 1024 * 10,
|
||||||
|
"allowed_file_types": ["*"],
|
||||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||||
"uploadMinute": 1,
|
"uploadMinute": 1,
|
||||||
"enableChunk": 0,
|
"enableChunk": 0,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ def build_public_config() -> dict:
|
|||||||
"description": settings.description,
|
"description": settings.description,
|
||||||
"explain": settings.page_explain,
|
"explain": settings.page_explain,
|
||||||
"uploadSize": settings.uploadSize,
|
"uploadSize": settings.uploadSize,
|
||||||
|
"allowedFileTypes": settings.allowed_file_types,
|
||||||
"expireStyle": settings.expireStyle,
|
"expireStyle": settings.expireStyle,
|
||||||
"enableChunk": settings.enableChunk,
|
"enableChunk": settings.enableChunk,
|
||||||
"openUpload": settings.openUpload,
|
"openUpload": settings.openUpload,
|
||||||
@@ -59,6 +60,7 @@ def build_public_meta() -> dict:
|
|||||||
},
|
},
|
||||||
"limits": {
|
"limits": {
|
||||||
"uploadSize": settings.uploadSize,
|
"uploadSize": settings.uploadSize,
|
||||||
|
"allowedFileTypes": settings.allowed_file_types,
|
||||||
"maxSaveSeconds": settings.max_save_seconds,
|
"maxSaveSeconds": settings.max_save_seconds,
|
||||||
"uploadWindowMinutes": settings.uploadMinute,
|
"uploadWindowMinutes": settings.uploadMinute,
|
||||||
"uploadWindowCount": settings.uploadCount,
|
"uploadWindowCount": settings.uploadCount,
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from apps.base.views import validate_file_type
|
||||||
|
from core.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_allows_extensions_and_mime_patterns(self):
|
||||||
|
settings.allowed_file_types = ["rar", ".zip", "image/*"]
|
||||||
|
|
||||||
|
validate_file_type("backup.RAR")
|
||||||
|
validate_file_type("archive.zip")
|
||||||
|
validate_file_type("avatar.bin", "image/png")
|
||||||
|
|
||||||
|
def test_rejects_disallowed_file_type(self):
|
||||||
|
settings.allowed_file_types = ["rar"]
|
||||||
|
|
||||||
|
with self.assertRaises(HTTPException) as error:
|
||||||
|
validate_file_type("payload.exe", "application/octet-stream")
|
||||||
|
|
||||||
|
self.assertEqual(error.exception.status_code, 403)
|
||||||
Reference in new issue
Block a user