feat: 整合官方 2.7.0 安全修复与本地文件分享

This commit is contained in:
orion committed 2026-09-18 10:08:42 +08:00
1 parent b10113e5ab
commit 9e9571b031
42 files changed
+2824 -268

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
"""Local NAS-style share helpers.
Files under ``data/local`` can be browsed by admin and turned into extract
codes without copying them into ``data/share``. The original file is never
deleted when a share expires or is removed from the file list.
``FileCodes.file_path`` is the sentinel ``local-ref``; ``uuid_file_name``
stores the posix relative path under ``data/local``. Accidental storage
deletes therefore look at ``data/local-ref/...`` and cannot touch the
original NAS file.
"""
from __future__ import annotations
import time
from pathlib import Path
from urllib.parse import quote
from fastapi import HTTPException
from starlette.responses import FileResponse
LOCAL_REF_MARKER = "local-ref"
MAX_RELPATH_LEN = 255
MAX_LIST_ENTRIES = 500
def is_local_ref(file_code) -> bool:
return (getattr(file_code, "file_path", None) or "") == LOCAL_REF_MARKER
def should_skip_storage_delete(file_code) -> bool:
return is_local_ref(file_code) or getattr(file_code, "text", None) is not None
def get_local_root() -> Path:
from core.settings import data_root
root = (Path(data_root) / "local").resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def normalize_local_relpath(raw: str, *, allow_empty: bool = False) -> str:
text = str(raw or "").replace("\\", "/")
if not text:
if allow_empty:
return ""
raise HTTPException(status_code=400, detail="非法文件名")
if (
text in {".", ".."}
or text.startswith("/")
or text.startswith("~")
or "\x00" in text
or ":" in text.split("/", 1)[0]
):
raise HTTPException(status_code=400, detail="非法文件名")
parts = [part for part in text.split("/") if part not in {"", "."}]
if not parts or any(part == ".." for part in parts):
raise HTTPException(status_code=400, detail="非法文件名")
relpath = "/".join(parts)
if len(relpath) > MAX_RELPATH_LEN:
raise HTTPException(status_code=400, detail="路径过长")
return relpath
def resolve_under_local(relpath: str) -> Path:
root = get_local_root()
if not relpath:
return root
candidate = (root / relpath).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise HTTPException(status_code=400, detail="非法文件路径") from exc
return candidate
def format_local_ctime(path: Path) -> str | None:
try:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(path.stat().st_ctime))
except OSError:
return None
def build_local_ref_download(file_code) -> FileResponse:
try:
relpath = normalize_local_relpath(getattr(file_code, "uuid_file_name", None) or "")
path = resolve_under_local(relpath)
except HTTPException as exc:
raise HTTPException(status_code=404, detail="文件已过期删除") from exc
if not path.is_file():
raise HTTPException(status_code=404, detail="文件已过期删除")
filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}"
if not filename:
filename = path.name
encoded_filename = quote(filename, safe="")
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}
try:
headers["Content-Length"] = str(path.stat().st_size)
except OSError:
pass
return FileResponse(path=path, filename=filename, headers=headers)
+1 -1
View File
@@ -22,7 +22,7 @@ class FileCodes(models.Model):
size = fields.BigIntField(default=0)
text = fields.TextField(null=True)
expired_at = fields.DatetimeField(null=True)
expired_count = fields.IntField(default=0)
expired_count = fields.IntField(default=-1)
used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True)
file_hash = fields.CharField(max_length=64, null=True)
+20 -7
View File
@@ -2,12 +2,24 @@ import datetime
from fastapi import HTTPException
from tortoise import connections
from tortoise.expressions import Q
from tortoise.functions import Sum
from apps.base.models import FileCodes, StorageReservation
from apps.base.local_share import LOCAL_REF_MARKER
from core.settings import settings
from core.utils import get_now
def owned_storage_queryset(queryset=None):
"""FileCodes that occupy FileCodeBox storage (exclude NAS local-ref rows).
SQL ``file_path != 'local-ref'`` drops NULLs, so keep null paths explicitly.
"""
qs = FileCodes.all() if queryset is None else queryset
return qs.filter(Q(file_path__isnull=True) | ~Q(file_path=LOCAL_REF_MARKER))
def _detect_sql_dialect() -> str:
"""识别当前默认连接的 SQL 方言。
@@ -54,13 +66,14 @@ def get_storage_limit() -> int:
async def get_storage_usage() -> dict[str, int | None]:
now = await get_now()
used = await FileCodes.all().values_list("size", flat=True)
reserved = await StorageReservation.filter(expires_at__gt=now).values_list(
"size", flat=True
)
# SQL 聚合:此函数在每次上传配额检查时调用,禁止全表拉取(D3)
used_rows = await owned_storage_queryset().annotate(total=Sum("size")).values("total")
reserved_rows = await StorageReservation.filter(expires_at__gt=now).annotate(
total=Sum("size")
).values("total")
limit = get_storage_limit()
used_bytes = sum(used)
reserved_bytes = sum(reserved)
used_bytes = used_rows[0]["total"] or 0
reserved_bytes = reserved_rows[0]["total"] or 0
return {
"limit": limit,
"used": used_bytes,
@@ -92,7 +105,7 @@ async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
INSERT INTO storagereservation (token, size, expires_at)
SELECT {ph[0]}, {ph[1]}, {ph[2]}
WHERE (
COALESCE((SELECT SUM(size) FROM filecodes), 0)
COALESCE((SELECT SUM(size) FROM filecodes WHERE file_path IS NULL OR file_path != '{LOCAL_REF_MARKER}'), 0)
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
+ {ph[4]}
) <= {ph[5]}
+4 -3
View File
@@ -31,6 +31,7 @@ from apps.base.utils import (
get_chunk_file_path_name,
validate_expire_style,
)
from apps.base.local_share import is_local_ref, build_local_ref_download
from core.response import APIResponse
from core.settings import settings
from core.storage import storages, FileStorageInterface
@@ -293,7 +294,7 @@ async def build_select_detail(
metadata = build_file_metadata(file_code)
if file_code.text is not None:
download_url = None
elif file_code.expired_count >= 0:
elif file_code.expired_count >= 0 or is_local_ref(file_code):
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
download_url = await get_proxy_file_url(file_code.code)
else:
@@ -357,7 +358,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
},
)
return await file_storage.get_file_response(file_code)
return (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
@share_api.post("/select/")
@@ -406,7 +407,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
return (
APIResponse(detail=file_code.text)
if file_code.text
else await file_storage.get_file_response(file_code)
else (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
)