fix(chunk-upload): persist sanitized filenames
This commit is contained in:
1 parent
d510aa7f57
commit
da1dd06655
2 files changed
+106
-7
No files matched your search
+11
-7
@@ -393,7 +393,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
|
||||||
@@ -423,7 +424,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:
|
||||||
@@ -459,7 +460,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,
|
||||||
@@ -468,7 +471,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:
|
||||||
@@ -670,7 +673,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:
|
||||||
# 合并文件并计算哈希
|
# 合并文件并计算哈希
|
||||||
@@ -689,7 +693,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,
|
||||||
)
|
)
|
||||||
@@ -699,7 +703,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:
|
||||||
|
|||||||
@@ -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,15 @@ 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 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
|
||||||
@@ -110,6 +116,95 @@ class ChunkFileNameSanitizeTests(unittest.TestCase):
|
|||||||
self.assertTrue(save_path.endswith("/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
|
||||||
|
|||||||
Reference in new issue
Block a user