🔀 merge: 合并 2.7.0 后端并固定新版管理前端构建
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
Create release / release-please (push) Canceled after 0s
Build and push Docker image / buildx (push) Canceled after 0s

This commit is contained in:
orion committed 2026-09-18 10:30:39 +08:00
commit 96e8eeac39
34 files changed
+1725 -336

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
{ {
".": "2.5.6" ".": "2.7.0"
} }
+30
View File
@@ -0,0 +1,30 @@
# Build the exact reviewed 2026 frontend while preserving the existing legacy themes.
ARG BASE_IMAGE
FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend
ARG FRONTEND_2026_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2026.git
ARG FRONTEND_2026_REF
RUN apk add --no-cache git && corepack enable && corepack prepare pnpm@9.15.9 --activate
WORKDIR /build
RUN test -n "$FRONTEND_2026_REF" && \
git init . && git remote add origin "$FRONTEND_2026_REPO" && \
git fetch --depth 1 origin "$FRONTEND_2026_REF" && git checkout --detach FETCH_HEAD && \
test "$(git rev-parse HEAD)" = "$FRONTEND_2026_REF" && \
pnpm install --frozen-lockfile --prod=false && \
node --experimental-strip-types --test --experimental-test-coverage tests/*.test.mjs && \
pnpm run build
FROM ${BASE_IMAGE}
ARG APP_VERSION
ARG VCS_REF
ARG FRONTEND_2026_REF
LABEL org.opencontainers.image.version="${APP_VERSION}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
LABEL org.opencontainers.image.filecodebox.frontend-2026-revision="${FRONTEND_2026_REF}"
WORKDIR /app
COPY VERSION requirements.txt main.py ./
COPY apps ./apps
COPY core ./core
COPY scripts ./scripts
RUN pip install --no-cache-dir -r requirements.txt
COPY --from=frontend /build/dist ./themes/2026
ENV APP_VERSION="${APP_VERSION}"
+15
View File
@@ -0,0 +1,15 @@
# Upgrade the backend while retaining the deployment's verified frontend themes.
# BASE_IMAGE must be a locally pinned backup of the existing deployment image.
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
ARG APP_VERSION
ARG VCS_REF
LABEL org.opencontainers.image.version="${APP_VERSION}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
WORKDIR /app
COPY VERSION requirements.txt main.py ./
COPY apps ./apps
COPY core ./core
COPY scripts ./scripts
RUN pip install --no-cache-dir -r requirements.txt
ENV APP_VERSION="${APP_VERSION}"
+1
View File
@@ -0,0 +1 @@
7f9aaf8a4d8045a807b97c87ed54954fea062e43
+77
View File
@@ -0,0 +1,77 @@
# 官方版本整合与发布
后续官方更新沿用本流程:比较源码并选择有用改动,保留定制功能和兼容接口;
先升级测试实例,验证后再升级正式实例;最后同步 1Panel 安装版本。
不直接点击应用商店升级覆盖定制镜像,也不永久关闭更新提醒。
## 2.7.0 整合范围
上游:`vastsa/FileCodeBox`,`v2.7.0`,提交 `82555c08edc4e5a2fa92d7ae12ea0e95d52aebaa`。
- scrypt 密码哈希、旧密码登录时自动迁移、初始化探测避免慢哈希。
- 背景 URL 校验;未修改的历史背景值不阻塞其他设置保存。
- 配置读取缓存 2 秒,写后立即刷新;管理配置、审计、预设的并发写保护。
- 存储配额改用 SQL 聚合;按时间有效的文件默认不耗尽下载次数。
- `data/local` 文件直接生成取件码,支持子目录;不复制到 WebDAV/S3,
不占上传配额。分享删除、到期、回收站清理均不删除 NAS 原件。
- 修复密码修改与并发登录的竞争,以及旧文件列表在大目录下漏项。
保留现有 camelCase/兼容别名、八位取件码、恢复原码、回收站及审计。
未引入官方全量 snake_case 迁移和模块重构,以避免破坏定制主题和数据。
仪表盘仍使用定制健康规则;没有照搬上游整套统计重构。
`GET /admin/local/lists` 保留旧数组响应;显式 `?path=` 返回目录对象,
含 `items/path/parent/truncated`,目录浏览最多返回 500 项。
`POST /admin/local/share` 的 `filename` 可传相对路径。
管理端“删除本地文件”接口仍会删除指定原件;这与删除分享记录不同。
## 版本与构建
同步 `VERSION`、`.release-please-manifest.json`、前端包元数据和 Compose 镜像版本。
运行时 `APP_VERSION` 必须是正式版本号(本次 `2.7.0`),源码提交单独记录在
`org.opencontainers.image.revision`,不把提交后缀混入 1Panel 安装版本。
前端没有改动时,使用 `Dockerfile.upgrade` 保留每个实例已经验证的主题。
先将原镜像 ID 固定为独立备份标签,再从远端 Git 获取已验证的精确提交构建:
```sh
docker build -f Dockerfile.upgrade \
--build-arg BASE_IMAGE=local/filecodebox:pre-upgrade-test \
--build-arg APP_VERSION="$(cat VERSION)" \
--build-arg VCS_REF="$(git rev-parse HEAD)" \
-t local/filecodebox:2.7.0-test .
```
正式实例用其原镜像作为基础,确保前端与测试实例差异不会被意外覆盖。
需要更新 2026 主题时使用 `Dockerfile.release`:额外传入
`--build-arg FRONTEND_2026_REF="$(cat FRONTEND_2026_REVISION)"`。该构建在镜像内执行前端
单测、SSR 集成、覆盖率、类型检查及生产构建,替换 2026 主题并保留原 2023/2024 主题。
前端提交独立记录在 `org.opencontainers.image.filecodebox.frontend-2026-revision`。
同时更新其他主题时才使用主 Dockerfile,并固定各主题提交。
## 验证与部署
1. 前端与后端分别维护在 `FileCodeBoxFronted2026` 和 `filecodebox` 仓库。
测试分支均为 `test/custom-admin-ui`;验证后分别合并到前端 `main`、后端 `master`。
沿用 emoji + 中文提交说明。后端测试分支存在独立历史和旧前端副本,首次合并仅
整合 apps/core/main/版本/部署/后端测试,保留正式仓库文档、许可证、发布配置。
2. 单元及集成:`python -m pytest -q`;覆盖率:
`python -m pytest --cov=apps --cov=core --cov=main --cov-report=term`。
3. 在独立前端仓库运行:
`node --experimental-strip-types --test --experimental-test-coverage tests/*.test.mjs`,
再运行 `npm run build`;另验证清理失败弹窗的 500/断网场景。
后端本地未生成主题时,两个主题测试会跳过,必须在最终镜像中补跑。
4. 备份原镜像、Compose、容器配置;使用 SQLite backup API 备份应用数据库和
`/opt/1panel/db/agent.db`,不能直接复制正在写入的 WAL 数据库。
5. 测试实例 `filecodebox-test`(40158)先更新,保留独立数据目录。
验证首页/静态资源、版本、鉴权、上传下载、NAS 分享和回收站。
6. 正式实例 `filecodebox`(40157)使用相同源码提交,保留正式数据及主题,
更新后再验证接口、日志、容器状态。失败时恢复原镜像/Compose,必要时恢复数据库备份。
7. 验证运行时与镜像确为目标版本后,在事务中仅更新对应 `app_installs` 的
`version`、同 `app_id` 下目标版本的 `app_detail_id`、实际 `docker_compose` 和时间戳。
同步磁盘 Compose。保留 `app_id` 和官方商店关联,不改全局 `app_details.update`,
不把新版本加入忽略列表。测试实例目前不在 1Panel `app_installs` 中,不伪造安装记录。
8. 重新读取安装记录、容器及 HTTP 版本;核对 1Panel 升级候选列表不再包含已安装版本。
官方发布更高版本后仍应提示,再重复本流程。
生产按单 worker 运行。配置/审计写锁为进程内锁;多 worker 需要跨进程并发控制后再启用。
+1 -1
View File
@@ -1 +1 @@
2.5.6 2.7.0
+24 -3
View File
@@ -1,7 +1,7 @@
import datetime import datetime
from typing import Any, Optional, Union from typing import Annotated, Any, Literal, Optional, Union
from pydantic import BaseModel from pydantic import BaseModel, Field, model_validator
class IDData(BaseModel): class IDData(BaseModel):
@@ -59,7 +59,28 @@ class BatchFilePolicyActionData(BaseModel):
class TrashRetentionData(BaseModel): class TrashRetentionData(BaseModel):
id: int id: int
retentionDays: int retentionDays: Optional[int] = Field(default=None, ge=0, le=365)
expiresAt: Optional[datetime.datetime] = None
@model_validator(mode="after")
def one_deadline(self):
if (self.retentionDays is None) == (self.expiresAt is None):
raise ValueError("请选择保留天数或自动清理时间")
return self
class BatchTrashData(BaseModel):
ids: list[Annotated[int, Field(strict=True, gt=0)]] = Field(min_length=1, max_length=100)
action: Literal["restore", "purge", "retention"]
retentionDays: Optional[int] = Field(default=None, ge=0, le=365)
expiresAt: Optional[datetime.datetime] = None
@model_validator(mode="after")
def validate_action_payload(self):
provided = int(self.retentionDays is not None) + int(self.expiresAt is not None)
if (self.action == "retention" and provided != 1) or (self.action != "retention" and provided):
raise ValueError("清理时间参数与操作不匹配")
return self
class FileMetadataData(BaseModel): class FileMetadataData(BaseModel):
+263 -262
View File
@@ -1,13 +1,17 @@
import asyncio
import hashlib import hashlib
import json import json
from pathlib import Path from pathlib import Path
import os import os
import time
import uuid
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from apps.base.local_share import (
LOCAL_REF_MARKER, MAX_LIST_ENTRIES, build_local_ref_download,
format_local_ctime, get_local_root, is_local_ref, normalize_local_relpath,
resolve_under_local, should_skip_storage_delete,
)
from core.response import APIResponse from core.response import APIResponse
from core.storage import FileStorageInterface, storages from core.storage import FileStorageInterface, storages
from core.settings import ( from core.settings import (
@@ -19,14 +23,19 @@ from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
from apps.base.utils import get_expire_info, get_file_path_name, get_random_code from apps.base.utils import get_expire_info, get_random_code
from apps.base.quota import release_storage, reserve_storage
from fastapi import HTTPException from fastapi import HTTPException
from core.settings import data_root from core.utils import get_now, hash_password, is_password_hashed, validate_background_url
from core.utils import get_now, hash_password, is_password_hashed
class FileService: from apps.admin.trash_management import TrashManagementMixin
# Single-worker deployments serialize JSON read/modify/write operations.
keyvalue_write_lock = asyncio.Lock()
class FileService(TrashManagementMixin):
FILE_METADATA_KEY_PREFIX = "admin_file_metadata:" FILE_METADATA_KEY_PREFIX = "admin_file_metadata:"
FILE_VIEW_PRESETS_KEY = "admin_file_view_presets" FILE_VIEW_PRESETS_KEY = "admin_file_view_presets"
ADMIN_ACTIVITY_KEY = "admin_activity_events" ADMIN_ACTIVITY_KEY = "admin_activity_events"
@@ -107,8 +116,8 @@ class FileService:
deduped.append(stat) deduped.append(stat)
return deduped return deduped
async def _delete_file_code(self, file_code: FileCodes): async def _delete_file_code(self, file_code: FileCodes, reason: str = "manual"):
await self.move_to_trash(file_code, reason="manual") await self.move_to_trash(file_code, reason=reason)
@staticmethod @staticmethod
def _trash_path(file_code: FileCodes) -> str: def _trash_path(file_code: FileCodes) -> str:
@@ -137,7 +146,7 @@ class FileService:
return file_code return file_code
now = await get_now() now = await get_now()
original_path = await file_code.get_file_path() if file_code.text is None else "" original_path = await file_code.get_file_path() if file_code.text is None else ""
if file_code.text is None: if not should_skip_storage_delete(file_code):
await self.file_storage.move_file(file_code, self._trash_path(file_code)) await self.file_storage.move_file(file_code, self._trash_path(file_code))
await file_code.update_from_dict( await file_code.update_from_dict(
{ {
@@ -169,7 +178,7 @@ class FileService:
if file_code.trash_purged_at is not None: if file_code.trash_purged_at is not None:
raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录") raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录")
original_path = file_code.trash_original_path or "" original_path = file_code.trash_original_path or ""
if file_code.text is None: if not should_skip_storage_delete(file_code):
if not original_path: if not original_path:
raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复") raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复")
destination_dir, filename = os.path.split(original_path) destination_dir, filename = os.path.split(original_path)
@@ -181,11 +190,18 @@ class FileService:
) )
file_code.file_path = destination_dir file_code.file_path = destination_dir
original_code = file_code.code original_code = file_code.code
await ShareCodeReservations.get_or_create( active_collision = await FileCodes.filter(
code=original_code, code=original_code, is_trashed=False
defaults={"file_code_id": file_code.id, "reason": "restored"}, ).exclude(id=file_code.id).exists()
) if active_collision:
file_code.code = await get_random_code() raise HTTPException(status_code=409, detail="原取件码已被其他文件占用,无法复用")
reservations = await ShareCodeReservations.filter(code=original_code).all()
if any(reservation.file_code_id != file_code.id for reservation in reservations):
raise HTTPException(status_code=409, detail="原取件码已被历史记录占用,无法复用")
await ShareCodeReservations.filter(
code=original_code, file_code_id=file_code.id
).delete()
file_code.code = original_code
file_code.is_trashed = False file_code.is_trashed = False
file_code.trashed_at = None file_code.trashed_at = None
file_code.trash_expires_at = None file_code.trash_expires_at = None
@@ -216,7 +232,7 @@ class FileService:
async def purge_trashed_file(self, file_code: FileCodes) -> None: async def purge_trashed_file(self, file_code: FileCodes) -> None:
if file_code.trash_purged_at is not None: if file_code.trash_purged_at is not None:
return return
if file_code.text is None: if not should_skip_storage_delete(file_code):
trash_path = self._trash_path(file_code) trash_path = self._trash_path(file_code)
await self.file_storage.delete_file( await self.file_storage.delete_file(
FileCodes( FileCodes(
@@ -248,37 +264,6 @@ class FileService:
meta={"auditOnly": True}, meta={"auditOnly": True},
) )
async def list_trash(self, page: int, size: int) -> dict[str, Any]:
page = max(page, 1)
size = min(max(size, 1), 100)
query = FileCodes.filter(is_trashed=True).order_by("-trashed_at", "-id")
total = await query.count()
files = await query.offset((page - 1) * size).limit(size)
now = await get_now()
items = []
for file_code in files:
item = await self._build_admin_file_item(file_code, now=now)
item.update(
{
"trashedAt": file_code.trashed_at,
"trashExpiresAt": file_code.trash_expires_at,
"trashReason": file_code.trash_reason,
"trashPurgedAt": file_code.trash_purged_at,
"isTrashPermanent": file_code.trash_expires_at is None and file_code.trash_purged_at is None,
"isTrashPurged": file_code.trash_purged_at is not None,
}
)
items.append(item)
return {"page": page, "size": size, "total": total, "data": items}
async def set_trash_retention(self, file_id: int, retention_days: int) -> FileCodes:
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(status_code=404, detail="回收站文件不存在")
file_code.trash_expires_at = self._trash_expiry(await get_now(), retention_days)
await file_code.save(update_fields=["trash_expires_at"])
return file_code
async def delete_file(self, file_id: int): async def delete_file(self, file_id: int):
file_code = await FileCodes.get(id=file_id) file_code = await FileCodes.get(id=file_id)
target_name = self._build_file_activity_name(file_code) target_name = self._build_file_activity_name(file_code)
@@ -304,7 +289,7 @@ class FileService:
continue continue
try: try:
await self._delete_file_code(file_code) await self._delete_file_code(file_code, reason="batch_delete")
deleted.append(file_id) deleted.append(file_id)
except Exception as exc: except Exception as exc:
failed.append({"id": file_id, "reason": str(exc)}) failed.append({"id": file_id, "reason": str(exc)})
@@ -477,44 +462,45 @@ class FileService:
name: str, name: str,
filters: dict[str, Any], filters: dict[str, Any],
) -> dict[str, Any]: ) -> dict[str, Any]:
presets = await self._get_file_view_presets() async with keyvalue_write_lock:
normalized_name = self._normalize_file_view_preset_name(name) presets = await self._get_file_view_presets()
normalized_filters = self._normalize_file_view_preset_filters(filters) normalized_name = self._normalize_file_view_preset_name(name)
now = await get_now() normalized_filters = self._normalize_file_view_preset_filters(filters)
updated_at = now.isoformat() now = await get_now()
updated_at = now.isoformat()
target_index = next( target_index = next(
(index for index, preset in enumerate(presets) if preset["id"] == preset_id), (index for index, preset in enumerate(presets) if preset["id"] == preset_id),
-1, -1,
) )
is_update = target_index >= 0 is_update = target_index >= 0
if is_update: if is_update:
preset = presets[target_index] preset = presets[target_index]
next_preset = { next_preset = {
**preset, **preset,
"name": normalized_name, "name": normalized_name,
"filters": normalized_filters, "filters": normalized_filters,
"params": normalized_filters, "params": normalized_filters,
"updatedAt": updated_at, "updatedAt": updated_at,
"updated_at": updated_at, "updated_at": updated_at,
} }
presets[target_index] = next_preset presets[target_index] = next_preset
else: else:
if len(presets) >= self.MAX_VIEW_PRESETS: if len(presets) >= self.MAX_VIEW_PRESETS:
raise HTTPException(status_code=400, detail="视图预设数量已达上限") raise HTTPException(status_code=400, detail="视图预设数量已达上限")
next_preset = { next_preset = {
"id": preset_id or self._build_file_view_preset_id(normalized_name, now), "id": preset_id or self._build_file_view_preset_id(normalized_name, now),
"name": normalized_name, "name": normalized_name,
"filters": normalized_filters, "filters": normalized_filters,
"params": normalized_filters, "params": normalized_filters,
"createdAt": updated_at, "createdAt": updated_at,
"created_at": updated_at, "created_at": updated_at,
"updatedAt": updated_at, "updatedAt": updated_at,
"updated_at": updated_at, "updated_at": updated_at,
} }
presets.append(next_preset) presets.append(next_preset)
await self._save_file_view_presets(presets) await self._save_file_view_presets(presets)
await self.record_admin_activity( await self.record_admin_activity(
action="file.view_preset_update" if is_update else "file.view_preset_create", action="file.view_preset_update" if is_update else "file.view_preset_create",
target_type="view_preset", target_type="view_preset",
@@ -530,16 +516,17 @@ class FileService:
if not preset_id: if not preset_id:
raise HTTPException(status_code=400, detail="请选择要删除的视图预设") raise HTTPException(status_code=400, detail="请选择要删除的视图预设")
presets = await self._get_file_view_presets() async with keyvalue_write_lock:
deleted_preset = next( presets = await self._get_file_view_presets()
(preset for preset in presets if preset["id"] == preset_id), deleted_preset = next(
None, (preset for preset in presets if preset["id"] == preset_id),
) None,
next_presets = [preset for preset in presets if preset["id"] != preset_id] )
if len(next_presets) == len(presets): next_presets = [preset for preset in presets if preset["id"] != preset_id]
raise HTTPException(status_code=404, detail="视图预设不存在") if len(next_presets) == len(presets):
raise HTTPException(status_code=404, detail="视图预设不存在")
await self._save_file_view_presets(next_presets) await self._save_file_view_presets(next_presets)
await self.record_admin_activity( await self.record_admin_activity(
action="file.view_preset_delete", action="file.view_preset_delete",
target_type="view_preset", target_type="view_preset",
@@ -656,7 +643,7 @@ class FileService:
"fileCount": 0, "fileCount": 0,
"chunkedCount": 0, "chunkedCount": 0,
**self._empty_health_summary(), **self._empty_health_summary(),
"storageUsed": sum(file_code.size for file_code in all_files), "storageUsed": sum(file_code.size for file_code in all_files if not is_local_ref(file_code)),
"usedCount": sum(file_code.used_count for file_code in all_files), "usedCount": sum(file_code.used_count for file_code in all_files),
} }
@@ -1030,12 +1017,13 @@ class FileService:
if not activity: if not activity:
return None return None
activities = await self._get_admin_activities() async with keyvalue_write_lock:
next_activities = [ activities = await self._get_admin_activities()
activity, next_activities = [
*[item for item in activities if item["id"] != activity["id"]], activity,
][: self.MAX_ADMIN_ACTIVITIES] *[item for item in activities if item["id"] != activity["id"]],
await self._save_admin_activities(next_activities) ][: self.MAX_ADMIN_ACTIVITIES]
await self._save_admin_activities(next_activities)
return activity return activity
except Exception: except Exception:
return None return None
@@ -1653,6 +1641,8 @@ class FileService:
if file_code.text: if file_code.text:
return APIResponse(detail=file_code.text) return APIResponse(detail=file_code.text)
else: else:
if is_local_ref(file_code):
return build_local_ref_download(file_code)
return await self.file_storage.get_file_response(file_code) return await self.file_storage.get_file_response(file_code)
async def preview_file(self, file_id: int, max_chars: int = 4000): async def preview_file(self, file_id: int, max_chars: int = 4000):
@@ -1688,40 +1678,28 @@ class FileService:
if not await local_file.exists(): if not await local_file.exists():
raise HTTPException(status_code=404, detail="文件不存在") raise HTTPException(status_code=404, detail="文件不存在")
reservation_token = f"local:{uuid.uuid4().hex}" expired_at, expired_count, used_count, code = await get_expire_info(
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600) item.expire_value, item.expire_style
try: )
text = await local_file.read() name = local_file.name
expired_at, expired_count, used_count, code = await get_expire_info( suffix = Path(name).suffix
item.expire_value, item.expire_style prefix = name[: len(name) - len(suffix)] if suffix else name
) record = await FileCodes.create(
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name( code=code,
item prefix=prefix,
) suffix=suffix,
await self.file_storage.save_file(text, save_path) uuid_file_name=local_file.file,
try: file_path=LOCAL_REF_MARKER,
await FileCodes.create( size=local_file.size or 0,
code=code, expired_at=expired_at,
prefix=prefix, expired_count=expired_count,
suffix=suffix, used_count=used_count,
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 { return {
"code": code, "code": code,
"name": local_file.file, "name": name,
"path": local_file.file,
"id": record.id,
} }
@@ -1758,112 +1736,158 @@ class ConfigService:
return config return config
async def update_config(self, data: dict): async def update_config(self, data: dict):
current_config = dict(settings.items()) async with keyvalue_write_lock:
next_config = dict(current_config) await refresh_settings(force=True)
update_data = { current_config = dict(settings.items())
key: value next_config = dict(current_config)
for key, value in data.items() update_data = {
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS 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_token = update_data.get("admin_token")
admin_password_changed = False admin_password_changed = False
if admin_token is None or admin_token == "": if admin_token is None or admin_token == "":
update_data.pop("admin_token", None) update_data.pop("admin_token", None)
elif not is_password_hashed(admin_token): elif not is_password_hashed(admin_token):
update_data["admin_token"] = hash_password(admin_token) update_data["admin_token"] = hash_password(admin_token)
admin_password_changed = True admin_password_changed = True
else: else:
admin_password_changed = True admin_password_changed = True
for key, value in update_data.items(): for key, value in update_data.items():
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS: if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
continue continue
try:
if key in self.INT_FIELDS:
next_config[key] = int(value)
elif key in self.FLOAT_FIELDS:
next_config[key] = float(value)
else:
next_config[key] = value
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
try: try:
if key in self.INT_FIELDS: session_expire = int(next_config.get("adminSessionExpire"))
next_config[key] = int(value)
elif key in self.FLOAT_FIELDS:
next_config[key] = float(value)
else:
next_config[key] = value
except (TypeError, ValueError): except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误") 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
try: try:
session_expire = int(next_config.get("adminSessionExpire")) trash_retention_days = int(
except (TypeError, ValueError): next_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
raise HTTPException( )
status_code=400, except (TypeError, ValueError):
detail="adminSessionExpire 配置值格式错误", raise HTTPException(
) status_code=400,
if ( detail="trashRetentionDays 配置值格式错误",
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX )
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0 if not 1 <= trash_retention_days <= FileService.TRASH_MAX_RETENTION_DAYS:
): raise HTTPException(
raise HTTPException( status_code=400,
status_code=400, detail="trashRetentionDays 必须是 1 到 365 个整天",
detail="adminSessionExpire 必须是 1 到 365 个整天", )
) next_config["trashRetentionDays"] = trash_retention_days
next_config["adminSessionExpire"] = session_expire retention_changed = (
"trashRetentionDays" in update_data
try: and trash_retention_days != int(
trash_retention_days = int( current_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
next_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS) )
)
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="trashRetentionDays 配置值格式错误",
)
if not 1 <= trash_retention_days <= FileService.TRASH_MAX_RETENTION_DAYS:
raise HTTPException(
status_code=400,
detail="trashRetentionDays 必须是 1 到 365 个整天",
)
next_config["trashRetentionDays"] = trash_retention_days
retention_changed = (
"trashRetentionDays" in update_data
and trash_retention_days != int(
current_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
)
)
if int(next_config.get("storageLimit", 0)) < 0:
raise HTTPException(
status_code=400,
detail="storageLimit 不能小于 0",
) )
if admin_password_changed: if int(next_config.get("storageLimit", 0)) < 0:
next_config["jwt_secret"] = generate_jwt_secret() raise HTTPException(
status_code=400,
detail="storageLimit 不能小于 0",
)
await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) if str(next_config.get("background") or "") != str(current_config.get("background") or ""):
await refresh_settings() try:
validate_background_url(next_config.get("background"))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if retention_changed: if admin_password_changed:
retention_now = await get_now() next_config["jwt_secret"] = generate_jwt_secret()
retention_expiry = FileService._trash_expiry(retention_now, trash_retention_days)
await FileCodes.filter(
is_trashed=True,
trash_purged_at__isnull=True,
trash_expires_at__isnull=False,
).update(trash_expires_at=retention_expiry)
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings(force=True)
if retention_changed:
retention_now = await get_now()
retention_expiry = FileService._trash_expiry(retention_now, trash_retention_days)
await FileCodes.filter(
is_trashed=True,
trash_purged_at__isnull=True,
trash_expires_at__isnull=False,
).update(trash_expires_at=retention_expiry)
class LocalFileService: class LocalFileService:
async def list_files(self): async def list_files(self, path: str = "", *, legacy: bool = False):
files = [] relpath = normalize_local_relpath(path, allow_empty=True)
if not os.path.exists(data_root / "local"): directory = resolve_under_local(relpath)
os.makedirs(data_root / "local") if not directory.exists() or not directory.is_dir():
for file in os.listdir(data_root / "local"): raise HTTPException(status_code=404, detail="目录不存在")
local_file = LocalFileClass(file)
files.append({ root = get_local_root()
"file": local_file.file, items = []
"ctime": local_file.ctime, try:
"size": local_file.size, children = list(directory.iterdir())
}) except OSError as exc:
return files raise HTTPException(status_code=500, detail="无法读取目录") from exc
children.sort(key=lambda p: (not p.is_dir(), p.name.lower()))
truncated = False
for child in children:
if not legacy and len(items) >= MAX_LIST_ENTRIES:
truncated = True
break
try:
resolved = child.resolve()
resolved.relative_to(root)
except (OSError, ValueError):
continue
if not resolved.is_file() and not resolved.is_dir():
continue
if legacy and not resolved.is_file():
continue
child_rel = child.name if not relpath else f"{relpath}/{child.name}"
is_dir = resolved.is_dir()
items.append(
{
"file": child.name,
"name": child.name,
"path": child_rel,
"type": "dir" if is_dir else "file",
"ctime": format_local_ctime(resolved),
"size": None if is_dir else resolved.stat().st_size,
}
)
parent = ""
if relpath:
parent_path = Path(relpath).parent.as_posix()
parent = "" if parent_path == "." else parent_path
return {
"path": relpath,
"parent": parent,
"truncated": truncated,
"items": items,
}
async def delete_file(self, filename: str): async def delete_file(self, filename: str):
file = LocalFileClass(filename) file = LocalFileClass(filename)
@@ -1875,52 +1899,29 @@ class LocalFileService:
class LocalFileClass: class LocalFileClass:
def __init__(self, file): def __init__(self, file):
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。 relpath = normalize_local_relpath(file)
raw_name = str(file or "") self.file = relpath
normalized = Path(raw_name).as_posix() self.name = Path(relpath).name
# 输入本身不得包含路径分隔符或绝对路径形态。 self.path = resolve_under_local(relpath)
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(): if self.path.is_file():
self.ctime = time.strftime( self.ctime = format_local_ctime(self.path)
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path)) self.size = self.path.stat().st_size
)
self.size = os.path.getsize(self.path)
else: else:
self.ctime = None self.ctime = None
self.size = None self.size = None
async def read(self): async def read(self) -> bytes:
return open(self.path, "rb") with open(self.path, "rb") as fh:
return fh.read()
async def write(self, data): async def write(self, data):
with open(self.path, "w") as f: with open(self.path, "wb") as f:
f.write(data) f.write(data)
async def delete(self): async def delete(self):
os.remove(self.path) if not self.path.is_file():
raise HTTPException(status_code=404, detail="文件不存在")
self.path.unlink()
async def exists(self): async def exists(self):
return self.path.is_file() return self.path.is_file()
+132
View File
@@ -0,0 +1,132 @@
"""Recycle-bin queries and bulk orchestration; storage actions stay in FileService."""
from datetime import datetime, timedelta
from typing import Any
from fastapi import HTTPException
from tortoise.expressions import Q, RawSQL
from apps.base.models import FileCodes
from core.utils import get_now
def automatic_trash_reason(file_code: FileCodes, now: datetime) -> str | None:
deadline = file_code.expired_at
if deadline is not None and deadline.tzinfo is None:
deadline = deadline.replace(tzinfo=now.tzinfo)
timed_out = deadline is not None and deadline <= now
count_exhausted = file_code.expired_count == 0
if timed_out and count_exhausted:
return "expired_both"
if timed_out:
return "expired_time"
if count_exhausted:
return "expired_count"
return None
class TrashManagementMixin:
async def list_trash(self, page: int, size: int, keyword: str = "", state: str = "all", reason: str = "") -> dict[str, Any]:
if state not in {"all", "recoverable", "permanent", "scheduled", "purged"}:
raise HTTPException(400, "无效的回收站状态")
if reason not in {"", "manual", "batch_delete", "expired_time", "expired_count", "expired_both", "expired"}:
raise HTTPException(400, "无效的移入原因")
page, size = max(page, 1), min(max(size, 1), 100)
base = FileCodes.filter(is_trashed=True)
stored_total = await base.count()
purged = await base.filter(trash_purged_at__isnull=False).count()
query = base
if state == "purged":
query = query.filter(trash_purged_at__isnull=False)
elif state != "all":
query = query.filter(trash_purged_at__isnull=True)
if state in {"permanent", "scheduled"}:
query = query.filter(trash_expires_at__isnull=state == "permanent")
if reason:
query = query.filter(trash_reason=reason)
keyword = keyword.strip()
if keyword:
# FileCodeBox uses SQLite; a fixed expression joins both filename parts.
# User input remains an ORM-bound value, never SQL source.
query = query.annotate(trash_name=RawSQL('COALESCE("prefix", \'\') || COALESCE("suffix", \'\')')).filter(
Q(trash_name__icontains=keyword) | Q(code__icontains=keyword)
)
total = await query.count()
files = await query.order_by("-trashed_at", "-id").offset((page - 1) * size).limit(size)
now = await get_now()
items = []
for file_code in files:
item = await self._build_admin_file_item(file_code, now=now)
item.update({
"trashedAt": file_code.trashed_at, "trashExpiresAt": file_code.trash_expires_at,
"trashReason": file_code.trash_reason, "trashPurgedAt": file_code.trash_purged_at,
"isTrashPermanent": file_code.trash_expires_at is None and file_code.trash_purged_at is None,
"isTrashPurged": file_code.trash_purged_at is not None,
})
items.append(item)
return {"page": page, "size": size, "total": total, "data": items,
"summary": {"total": stored_total, "recoverable": stored_total-purged, "purged": purged},
"capabilities": {"filters": True, "batch": True, "customRetention": True}}
async def _retention_deadline(self, retention_days: int | None, expires_at: datetime | None):
if (retention_days is None) == (expires_at is None):
raise HTTPException(400, "请选择保留天数或自动清理时间")
now = await get_now()
if expires_at is None:
return self._trash_expiry(now, retention_days)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=now.tzinfo)
else:
expires_at = expires_at.astimezone(now.tzinfo)
if not now < expires_at <= now + timedelta(days=self.TRASH_MAX_RETENTION_DAYS):
raise HTTPException(400, "自动清理时间必须在未来 365 天内")
return expires_at
async def set_trash_retention(self, file_id: int, retention_days: int | None = None, expires_at: datetime | None = None) -> FileCodes:
deadline = await self._retention_deadline(retention_days, expires_at)
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(404, "回收站文件不存在")
if file_code.trash_purged_at is not None:
raise HTTPException(409, "文件已清理,不能修改保留时间")
file_code.trash_expires_at = deadline
await file_code.save(update_fields=["trash_expires_at"])
await self.record_admin_activity("trash.retention", "file", file_id, self._build_file_activity_name(file_code),
meta={"expiresAt": deadline.isoformat() if deadline else None})
return file_code
async def batch_trash(self, ids: list[int], action: str, retention_days: int | None = None, expires_at: datetime | None = None) -> dict[str, Any]:
if not ids or len(ids) > 100 or any(type(i) is not int or i <= 0 for i in ids):
raise HTTPException(400, "请选择 1 到 100 条有效记录")
if action not in {"restore", "purge", "retention"}:
raise HTTPException(400, "无效的批量操作")
if action == "retention":
await self._retention_deadline(retention_days, expires_at)
elif retention_days is not None or expires_at is not None:
raise HTTPException(400, "该操作不接受清理时间参数")
unique_ids = list(dict.fromkeys(ids))
succeeded, failed = [], []
for file_id in unique_ids:
try:
item = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not item:
raise HTTPException(404, "回收站文件不存在")
if item.trash_purged_at is not None:
raise HTTPException(409, "文件已清理,仅保留审计记录")
if action == "restore":
restored = await self.restore_from_trash(file_id)
succeeded.append({"id": file_id, "code": restored.code})
elif action == "purge":
await self.purge_trashed_file(item)
succeeded.append({"id": file_id})
else:
updated = await self.set_trash_retention(file_id, retention_days, expires_at)
succeeded.append({"id": file_id, "trashExpiresAt": updated.trash_expires_at})
except HTTPException as exc:
failed.append({"id": file_id, "reason": str(exc.detail)})
except Exception:
# Storage exceptions can contain private endpoints or credentials.
failed.append({"id": file_id, "reason": "操作失败,请重试"})
if succeeded:
await self.record_admin_activity(f"trash.batch_{action}", "file", count=len(succeeded),
meta={"requestedCount": len(unique_ids), "failedCount": len(failed)})
return {"requestedCount": len(unique_ids), "succeeded": succeeded, "failed": failed}
+50 -21
View File
@@ -7,6 +7,7 @@ from collections import Counter
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from apps.admin import services as admin_services
from apps.admin.services import FileService, ConfigService, LocalFileService from apps.admin.services import FileService, ConfigService, LocalFileService
from apps.admin.dependencies import ( from apps.admin.dependencies import (
admin_required, admin_required,
@@ -22,6 +23,7 @@ from apps.admin.schemas import (
BatchFilePolicyActionData, BatchFilePolicyActionData,
FilePolicyActionData, FilePolicyActionData,
TrashRetentionData, TrashRetentionData,
BatchTrashData,
FileMetadataData, FileMetadataData,
FileViewPresetData, FileViewPresetData,
FileViewPresetDeleteData, FileViewPresetDeleteData,
@@ -30,6 +32,7 @@ from apps.admin.schemas import (
LoginData, LoginData,
UpdateFileData, UpdateFileData,
) )
from apps.base.local_share import is_local_ref
from core.response import APIResponse from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
from apps.admin.dependencies import ( from apps.admin.dependencies import (
@@ -39,7 +42,8 @@ from apps.admin.dependencies import (
) )
from core.settings import settings from core.settings import settings
from core.utils import get_now, verify_password from core.utils import get_now, hash_password, password_needs_rehash, verify_password
from core.config import refresh_settings
from apps.base.utils import ip_limit from apps.base.utils import ip_limit
admin_api = APIRouter( admin_api = APIRouter(
@@ -57,23 +61,34 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
@admin_api.post("/login") @admin_api.post("/login")
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])): async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定 # Check and issue the token under the same lock used for password changes.
if not verify_password(data.password, settings.admin_token): async with admin_services.keyvalue_write_lock:
ip_limit["login"].add_ip(ip) await refresh_settings(force=True)
raise HTTPException(status_code=401, detail="密码错误") 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() if password_needs_rehash(settings.admin_token):
token = create_token({"is_admin": True}, expires_in=expires_in) record = await KeyValue.filter(key="settings").first()
return APIResponse( if record:
detail={ stored = dict(record.value or {})
"id": "admin", stored["admin_token"] = hash_password(data.password)
"username": "admin", record.value = stored
"token": token, await record.save()
"token_type": "Bearer", await refresh_settings(force=True)
"expires_at": verify_token(token)["exp"],
"expires_in": expires_in, 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") @admin_api.get("/verify")
@@ -106,7 +121,7 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
@admin_api.get("/dashboard") @admin_api.get("/dashboard")
async def dashboard(file_service: FileService = Depends(get_file_service)): async def dashboard(file_service: FileService = Depends(get_file_service)):
all_codes = await FileCodes.filter(is_trashed=False).all() all_codes = await FileCodes.filter(is_trashed=False).all()
all_size = sum([code.size for code in all_codes]) all_size = sum(code.size for code in all_codes if not is_local_ref(code))
sys_start = await KeyValue.filter(key="sys_start").first() sys_start = await KeyValue.filter(key="sys_start").first()
now = await get_now() now = await get_now()
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
@@ -459,9 +474,20 @@ async def file_batch_delete_post(
async def trash_list( async def trash_list(
page: int = 1, page: int = 1,
size: int = 20, size: int = 20,
keyword: str = "",
state: str = "all",
reason: str = "",
file_service: FileService = Depends(get_file_service), file_service: FileService = Depends(get_file_service),
): ):
return APIResponse(detail=await file_service.list_trash(page, size)) return APIResponse(detail=await file_service.list_trash(page, size, keyword, state, reason))
@admin_api.post("/trash/batch")
async def trash_batch(
data: BatchTrashData,
file_service: FileService = Depends(get_file_service),
):
return APIResponse(detail=await file_service.batch_trash(data.ids, data.action, data.retentionDays, data.expiresAt))
@admin_api.post("/trash/restore") @admin_api.post("/trash/restore")
@@ -478,7 +504,7 @@ async def trash_retention(
data: TrashRetentionData, data: TrashRetentionData,
file_service: FileService = Depends(get_file_service), file_service: FileService = Depends(get_file_service),
): ):
file_code = await file_service.set_trash_retention(data.id, data.retentionDays) file_code = await file_service.set_trash_retention(data.id, data.retentionDays, data.expiresAt)
return APIResponse(detail={"id": file_code.id, "trashExpiresAt": file_code.trash_expires_at}) return APIResponse(detail={"id": file_code.id, "trashExpiresAt": file_code.trash_expires_at})
@@ -804,9 +830,12 @@ async def file_preview(
@admin_api.get("/local/lists") @admin_api.get("/local/lists")
async def get_local_lists( async def get_local_lists(
path: Optional[str] = None,
local_file_service: LocalFileService = Depends(get_local_file_service), local_file_service: LocalFileService = Depends(get_local_file_service),
): ):
files = await local_file_service.list_files() listing = await local_file_service.list_files(path or "", legacy=path is None)
# 无 path 参数保留旧主题的数组响应;显式 path 支持目录导航。
files = listing if path is not None else [item for item in listing["items"] if item["type"] == "file"]
return APIResponse(detail=files) return APIResponse(detail=files)
+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) size = fields.BigIntField(default=0)
text = fields.TextField(null=True) text = fields.TextField(null=True)
expired_at = fields.DatetimeField(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) used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True) created_at = fields.DatetimeField(auto_now_add=True)
file_hash = fields.CharField(max_length=64, null=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 fastapi import HTTPException
from tortoise import connections from tortoise import connections
from tortoise.expressions import Q
from tortoise.functions import Sum
from apps.base.models import FileCodes, StorageReservation from apps.base.models import FileCodes, StorageReservation
from apps.base.local_share import LOCAL_REF_MARKER
from core.settings import settings from core.settings import settings
from core.utils import get_now 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: def _detect_sql_dialect() -> str:
"""识别当前默认连接的 SQL 方言。 """识别当前默认连接的 SQL 方言。
@@ -54,13 +66,14 @@ def get_storage_limit() -> int:
async def get_storage_usage() -> dict[str, int | None]: async def get_storage_usage() -> dict[str, int | None]:
now = await get_now() now = await get_now()
used = await FileCodes.all().values_list("size", flat=True) # SQL 聚合:此函数在每次上传配额检查时调用,禁止全表拉取(D3)
reserved = await StorageReservation.filter(expires_at__gt=now).values_list( used_rows = await owned_storage_queryset().annotate(total=Sum("size")).values("total")
"size", flat=True reserved_rows = await StorageReservation.filter(expires_at__gt=now).annotate(
) total=Sum("size")
).values("total")
limit = get_storage_limit() limit = get_storage_limit()
used_bytes = sum(used) used_bytes = used_rows[0]["total"] or 0
reserved_bytes = sum(reserved) reserved_bytes = reserved_rows[0]["total"] or 0
return { return {
"limit": limit, "limit": limit,
"used": used_bytes, "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) INSERT INTO storagereservation (token, size, expires_at)
SELECT {ph[0]}, {ph[1]}, {ph[2]} SELECT {ph[0]}, {ph[1]}, {ph[2]}
WHERE ( 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) + COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
+ {ph[4]} + {ph[4]}
) <= {ph[5]} ) <= {ph[5]}
+4 -3
View File
@@ -31,6 +31,7 @@ from apps.base.utils import (
get_chunk_file_path_name, get_chunk_file_path_name,
validate_expire_style, validate_expire_style,
) )
from apps.base.local_share import is_local_ref, build_local_ref_download
from core.response import APIResponse from core.response import APIResponse
from core.settings import settings from core.settings import settings
from core.storage import storages, FileStorageInterface from core.storage import storages, FileStorageInterface
@@ -293,7 +294,7 @@ async def build_select_detail(
metadata = build_file_metadata(file_code) metadata = build_file_metadata(file_code)
if file_code.text is not None: if file_code.text is not None:
download_url = 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) download_url = await get_proxy_file_url(file_code.code)
else: 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/") @share_api.post("/select/")
@@ -406,7 +407,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
return ( return (
APIResponse(detail=file_code.text) APIResponse(detail=file_code.text)
if 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))
) )
+13 -3
View File
@@ -1,3 +1,5 @@
import time
from apps.base.models import KeyValue from apps.base.models import KeyValue
from apps.base.utils import ip_limit from apps.base.utils import ip_limit
from core.database import db_startup_lock from core.database import db_startup_lock
@@ -61,7 +63,7 @@ async def ensure_security_settings() -> None:
logger.info("已将管理员密码迁移为哈希存储") logger.info("已将管理员密码迁移为哈希存储")
if security_config.jwt_secret_rotated: if security_config.jwt_secret_rotated:
logger.info("已生成独立 JWT 签名密钥") logger.info("已生成独立 JWT 签名密钥")
await refresh_settings() await refresh_settings(force=True)
def _sync_ip_limits() -> None: def _sync_ip_limits() -> None:
@@ -75,11 +77,19 @@ def _sync_ip_limits() -> None:
ip_limit["login"].count = settings.loginCount ip_limit["login"].count = settings.loginCount
async def refresh_settings() -> None: CONFIG_CACHE_TTL_SECONDS = 2.0
_config_cached_until = 0.0
async def refresh_settings(force: bool = False) -> None:
"""从数据库读取最新配置并应用到运行时。""" """从数据库读取最新配置并应用到运行时。"""
global _config_cached_until
if not force and time.monotonic() < _config_cached_until:
return
config_record = await KeyValue.filter(key="settings").first() config_record = await KeyValue.filter(key="settings").first()
settings.user_config = config_record.value if config_record and config_record.value else {} settings.user_config = config_record.value if config_record and config_record.value else {}
_sync_ip_limits() _sync_ip_limits()
_config_cached_until = time.monotonic() + CONFIG_CACHE_TTL_SECONDS
def is_runtime_initialized() -> bool: def is_runtime_initialized() -> bool:
@@ -118,4 +128,4 @@ async def initialize_system(
next_config["jwt_secret"] = generate_jwt_secret() next_config["jwt_secret"] = generate_jwt_secret()
await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings() await refresh_settings(force=True)
+2
View File
@@ -32,6 +32,8 @@ def is_config_initialized(config: dict[str, Any]) -> bool:
admin_token = str(config.get("admin_token") or "") admin_token = str(config.get("admin_token") or "")
if not admin_token: if not admin_token:
return False return False
if is_password_hashed(admin_token) and admin_token.startswith("scrypt$"):
return True
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token) return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
+4 -1
View File
@@ -18,6 +18,7 @@ from apps.admin.services import FileService
from apps.base.utils import ip_limit, get_chunk_file_path_name from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings from core.config import refresh_settings
from core.logger import logger from core.logger import logger
from apps.admin.trash_management import automatic_trash_reason
from core.settings import settings, data_root from core.settings import settings, data_root
from core.storage import FileStorageInterface, storages from core.storage import FileStorageInterface, storages
from core.utils import get_now from core.utils import get_now
@@ -43,7 +44,9 @@ async def delete_expire_files():
).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all() ).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
for exp in expire_data: for exp in expire_data:
try: try:
await file_service.move_to_trash(exp, reason="expired") reason = automatic_trash_reason(exp, await get_now())
if reason is not None:
await file_service.move_to_trash(exp, reason=reason)
except Exception as e: except Exception as e:
logger.error(f"移入过期文件回收站失败 code={exp.code}: {e}") logger.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
expired_trash = await FileCodes.filter( expired_trash = await FileCodes.filter(
+71 -7
View File
@@ -13,6 +13,27 @@ import time
from core.settings import settings from core.settings import settings
def validate_background_url(value) -> str:
"""Validate the site background config before it reaches the theme template.
Themes inject this value into inline CSS ``url('...')`` where html escaping
cannot neutralize a single-quote breakout, so only well-formed http(s) URLs
(or an empty string) are accepted.
"""
value = str(value or "").strip()
if not value:
return ""
from urllib.parse import urlparse
parsed = urlparse(value)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise ValueError("background 必须是 http(s) 完整 URL 或留空")
# quote()/whitespace would break out of the CSS url('') quoting context
if any(ch in value for ch in ("'", '"', "(", ")", " ", "\\", ";")):
raise ValueError("background URL 含有不允许的字符")
return value
async def get_random_num(length: int = 8): async def get_random_num(length: int = 8):
"""返回指定长度的纯数字取件码。""" """返回指定长度的纯数字取件码。"""
normalized_length = max(1, int(length or 8)) normalized_length = max(1, int(length or 8))
@@ -102,25 +123,61 @@ async def max_save_times_desc(max_save_seconds: int):
return desc_zh, desc_en return desc_zh, desc_en
# scrypt work factors (OWASP-recommended memory-hard parameters; ~50ms/verify)
SCRYPT_N = 2**14
SCRYPT_R = 8
SCRYPT_P = 1
_SCRYPT_MAXMEM = 64 * 1024 * 1024 # hashlib default cap (32MB) is too low for n=2^14,r=8
PASSWORD_SCHEME = "scrypt" # current scheme for new hashes; sha256/plaintext stay verifiable
def hash_password(password: str) -> str: def hash_password(password: str) -> str:
""" """
使用 SHA256 + salt 哈希密码 使用 scrypt(memory-hard)哈希密码
返回格式: sha256$<salt>$<hash> 返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
""" """
salt = os.urandom(16).hex() salt = os.urandom(16).hex()
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest() password_hash = hashlib.scrypt(
return f"sha256${salt}${password_hash}" password.encode(),
salt=salt.encode(),
n=SCRYPT_N,
r=SCRYPT_R,
p=SCRYPT_P,
maxmem=_SCRYPT_MAXMEM,
).hex()
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt}${password_hash}"
def verify_password(password: str, hashed: str) -> bool: def verify_password(password: str, hashed: str) -> bool:
""" """
验证密码是否匹配 验证密码是否匹配
支持新格式 (sha256$salt$hash) 和旧格式 (明文) 支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
""" """
if not hashed: if not hashed:
return False return False
# 新格式: sha256$salt$hash if hashed.startswith("scrypt$"):
parts = hashed.split("$")
if len(parts) != 6:
return False
try:
scheme, n, r, p, salt, stored_hash = parts
password_hash = hashlib.scrypt(
password.encode(),
salt=salt.encode(),
n=int(n),
r=int(r),
p=int(p),
maxmem=_SCRYPT_MAXMEM,
).hex()
# 默认解释器对超范围的 n/r/p 抛 TypeError/ValueError;部分构建会抛
# OverflowError,一并视为校验失败,避免坏掉的存量哈希影响登录路径。
except (ValueError, TypeError, OverflowError):
return False
return hmac.compare_digest(password_hash, stored_hash)
# sha256 格式: sha256$salt$hash(历史数据,验证逻辑保持原样)
if hashed.startswith("sha256$"): if hashed.startswith("sha256$"):
parts = hashed.split("$") parts = hashed.split("$")
if len(parts) != 3: if len(parts) != 3:
@@ -135,11 +192,18 @@ def verify_password(password: str, hashed: str) -> bool:
def is_password_hashed(password: str) -> bool: def is_password_hashed(password: str) -> bool:
""" """
检查密码是否已经是哈希格式 检查密码是否已经是哈希格式(现行或历史哈希均视为已哈希)
""" """
if password.startswith("scrypt$") and len(password.split("$")) == 6:
return True
return password.startswith("sha256$") and len(password.split("$")) == 3 return password.startswith("sha256$") and len(password.split("$")) == 3
def password_needs_rehash(hashed: str) -> bool:
"""True when the stored hash uses a legacy scheme (sha256/plaintext)."""
return bool(hashed) and not hashed.startswith(f"{PASSWORD_SCHEME}$")
async def sanitize_filename(filename: str) -> str: async def sanitize_filename(filename: str) -> str:
""" """
安全处理文件名: 安全处理文件名:
+1 -1
View File
@@ -1,7 +1,7 @@
version: "3" version: "3"
services: services:
file-code-box: file-code-box:
image: lanol/filecodebox:2.5.6 # x-release-please-version image: local/filecodebox:2.7.0 # x-release-please-version
volumes: volumes:
- fcb-data:/app/data:rw - fcb-data:/app/data:rw
restart: unless-stopped restart: unless-stopped
+1 -1
View File
@@ -759,7 +759,7 @@ async def load_config():
await KeyValue.update_or_create( await KeyValue.update_or_create(
key="sys_start", defaults={"value": int(time.time() * 1000)} key="sys_start", defaults={"value": int(time.time() * 1000)}
) )
await refresh_settings() await refresh_settings(force=True)
await ensure_security_settings() await ensure_security_settings()
ip_limit["error"].minutes = settings.errorMinute ip_limit["error"].minutes = settings.errorMinute
View File
Whitespace-only changes.
+55
View File
@@ -0,0 +1,55 @@
"""Shared test helpers: settings-override mixin and in-memory Tortoise setup.
Kept unittest-friendly (the legacy suite is unittest-based); pytest fixtures
live in conftest.py and build on top of these helpers.
"""
from tortoise import Tortoise
from core.settings import settings
# Mirrors core.database.get_db_config() but with an in-memory SQLite database
# and no WAL/startup-lock specifics, so tests never touch the real data dir's DB.
MEMORY_DB_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",
}
class SettingsOverrideMixin:
"""Snapshot settings.user_config in setUp and restore it in tearDown."""
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
async def init_memory_db():
"""Init Tortoise against an in-memory DB and create all schemas."""
# 每个测试都是全新 DB,必须同步失效进程级配置 TTL 缓存,
# 否则上一个测试的缓存会让 middleware 误判初始化状态。
import core.config as config_module
import asyncio
import apps.admin.services as services_module
services_module.keyvalue_write_lock = asyncio.Lock()
config_module._config_cached_until = 0.0
await Tortoise.init(config=MEMORY_DB_CONFIG)
await Tortoise.generate_schemas()
async def close_db():
await Tortoise.close_connections()
+13 -2
View File
@@ -1,3 +1,4 @@
from unittest.mock import AsyncMock, patch
import asyncio import asyncio
import copy import copy
import unittest import unittest
@@ -127,7 +128,8 @@ class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
verify_token(token) verify_token(token)
def test_configured_session_lifetime_is_returned_by_login(self): @patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_configured_session_lifetime_is_returned_by_login(self, refresh):
settings.admin_token = hash_password("admin-password") settings.admin_token = hash_password("admin-password")
settings.jwt_secret = "j" * 48 settings.jwt_secret = "j" * 48
settings.adminSessionExpire = 90 * 24 * 60 * 60 settings.adminSessionExpire = 90 * 24 * 60 * 60
@@ -157,7 +159,7 @@ class FakeKeyValue:
return None, True return None, True
async def fake_refresh_settings(): async def fake_refresh_settings(**kwargs):
return None return None
@@ -186,6 +188,15 @@ class FakeConfigKeyValue:
class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase): class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
self.refresh_patch = patch("apps.admin.services.refresh_settings", fake_refresh_settings)
self.refresh_patch.start()
def tearDown(self):
self.refresh_patch.stop()
super().tearDown()
def test_storage_limit_rejects_negative_values(self): def test_storage_limit_rejects_negative_values(self):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG) settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
with self.assertRaises(HTTPException) as context: with self.assertRaises(HTTPException) as context:
+135
View File
@@ -0,0 +1,135 @@
"""Tests for the background-URL config validation.
Themes inject the site ``background`` config into inline CSS ``url('...')``;
a single-quote breakout there is not neutralized by html escaping (the CSS
engine decodes entities back). The fix is upstream validation at config-write
time: only well-formed http(s) URLs (or empty) may be stored.
"""
import asyncio
import unittest
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from apps.admin.services import ConfigService
from core.utils import validate_background_url
VALID = [
"",
"https://example.com/bg.webp",
"http://cdn.example.org/a/b.jpg?id=1&token=ab",
]
INVALID = [
"x') ;background:url(https://evil.com/)",
"https://example.com/bg') ;background:url(evil)",
"javascript:alert(1)",
"data:image/svg+xml;base64,AAAA",
"/relative/path.jpg",
"//protocol-relative.example/bg",
"https://example.com/a b.png",
"https://example.com/a(b).png",
]
class ValidateBackgroundUrlTests(unittest.TestCase):
def test_valid_values_pass_through(self):
for value in VALID:
self.assertEqual(validate_background_url(value), value.strip() if value else "")
def test_injection_and_non_http_values_rejected(self):
for value in INVALID:
with self.assertRaises(ValueError, msg=value):
validate_background_url(value)
def test_none_and_whitespace_become_empty(self):
self.assertEqual(validate_background_url(None), "")
self.assertEqual(validate_background_url(" "), "")
class ConfigServiceBackgroundGuardTests(SettingsOverrideMixin, unittest.TestCase):
def test_update_config_rejects_malicious_background(self):
asyncio.run(self._scenario())
async def _scenario(self):
await init_memory_db()
try:
service = ConfigService()
# 合法值可通过
await service.update_config({"background": "https://ok.example/bg.png"})
# 恶意值被拒且不落库
from fastapi import HTTPException
with self.assertRaises(HTTPException) as ctx:
await service.update_config({"background": "x') ;background:url(https://evil.com/)"})
self.assertEqual(ctx.exception.status_code, 400)
from apps.base.models import KeyValue
record = await KeyValue.filter(key="settings").first()
self.assertEqual(
record.value.get("background"), "https://ok.example/bg.png",
"被拒绝的值不得写入配置",
)
finally:
await close_db()
class LegacyBackgroundUpgradeTests(SettingsOverrideMixin, unittest.TestCase):
"""存量部署升级:旧版本合法、新校验不接受的值,不得阻塞设置保存。"""
def test_unchanged_legacy_background_does_not_block_unrelated_save(self):
asyncio.run(self._unchanged_legacy_allows_save())
async def _unchanged_legacy_allows_save(self):
await init_memory_db()
try:
from core.config import refresh_settings
from apps.base.models import KeyValue
# 旧版本合法(相对路径 + 空格),新的 http(s) 校验会拒绝
legacy = "/static/bg image.png"
await KeyValue.create(
key="settings", value={"background": legacy, "name": "old"}
)
await refresh_settings(force=True)
service = ConfigService()
# 修复前这里会 400,导致存量部署连无关设置项都保存不了
await service.update_config({"name": "new"})
record = await KeyValue.filter(key="settings").first()
self.assertEqual(record.value.get("background"), legacy, "旧值应原样保留")
self.assertEqual(record.value.get("name"), "new")
finally:
await close_db()
def test_changing_background_is_still_validated(self):
asyncio.run(self._change_still_validated())
async def _change_still_validated(self):
await init_memory_db()
try:
from fastapi import HTTPException
from core.config import refresh_settings
from apps.base.models import KeyValue
await KeyValue.create(key="settings", value={"background": "/legacy/bg.png"})
await refresh_settings(force=True)
service = ConfigService()
# 修改为恶意值仍然被拒
with self.assertRaises(HTTPException) as ctx:
await service.update_config(
{"background": "x') ;background:url(https://evil.com/)"}
)
self.assertEqual(ctx.exception.status_code, 400)
# 修改为合法值可以通过
await service.update_config({"background": "https://ok.example/bg.png"})
record = await KeyValue.filter(key="settings").first()
self.assertEqual(record.value.get("background"), "https://ok.example/bg.png")
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
+5
View File
@@ -16,12 +16,16 @@ class SettingsOverrideMixin:
settings.user_config = self._original_user_config settings.user_config = self._original_user_config
THEMES_BUILT = all((BASE_DIR / f"themes/{year}/assets").is_dir() for year in (2023, 2024))
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase): class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
def get_theme_index_asset(self, theme: str) -> str: def get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js")) assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
self.assertTrue(assets, f"{theme} 缺少 index JS 资源") self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
return assets[0].name return assets[0].name
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
def test_resolves_assets_from_current_theme(self): def test_resolves_assets_from_current_theme(self):
settings.themesSelect = "themes/2023" settings.themesSelect = "themes/2023"
theme_2023_asset = resolve_theme_file( theme_2023_asset = resolve_theme_file(
@@ -62,6 +66,7 @@ class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
) )
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
def test_index_rewrites_assets_to_theme_specific_urls(self): def test_index_rewrites_assets_to_theme_specific_urls(self):
settings.themesSelect = "themes/2023" settings.themesSelect = "themes/2023"
+207
View File
@@ -0,0 +1,207 @@
"""Local NAS share: nested browse + zero-copy extract codes (issue #532)."""
import asyncio
import datetime
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from fastapi import HTTPException
from apps.admin.services import FileService, LocalFileClass, LocalFileService
LOCAL_REF_MARKER = "local-ref"
def is_local_ref(record):
return record.file_path == LOCAL_REF_MARKER
from apps.base.models import FileCodes
from apps.base.quota import get_storage_usage, reserve_storage
from core.tasks import delete_expire_files
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from core.settings import settings
from core.utils import get_now
class SleepSentinel(Exception):
pass
class LocalFileClassTests(unittest.TestCase):
def setUp(self):
self._tmpdir = TemporaryDirectory()
self.root = Path(self._tmpdir.name)
(self.root / "local").mkdir()
(self.root / "local" / "safe.txt").write_bytes(b"ok")
(self.root / "local" / "movies").mkdir()
(self.root / "local" / "movies" / "a.bin").write_bytes(b"nested")
self._patch = patch("core.settings.data_root", self.root)
self._patch.start()
def tearDown(self):
self._patch.stop()
self._tmpdir.cleanup()
def test_rejects_dotdot_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("../etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_nested_dotdot(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("movies/../../etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_absolute_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("/etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_allows_basename_inside_local(self):
local_file = LocalFileClass("safe.txt")
self.assertTrue(asyncio.run(local_file.exists()))
self.assertEqual(local_file.file, "safe.txt")
self.assertEqual(local_file.path, (self.root / "local" / "safe.txt").resolve())
def test_allows_nested_relative(self):
local_file = LocalFileClass("movies/a.bin")
self.assertTrue(asyncio.run(local_file.exists()))
self.assertEqual(local_file.file, "movies/a.bin")
self.assertEqual(local_file.name, "a.bin")
self.assertEqual(local_file.size, 6)
class LocalFileServiceListTests(unittest.TestCase):
def test_lists_nested_dirs_and_files(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
movies = root / "local" / "movies"
movies.mkdir(parents=True)
(root / "local" / "readme.txt").write_bytes(b"hi")
(movies / "a.bin").write_bytes(b"nested")
with patch("core.settings.data_root", root):
service = LocalFileService()
root_listing = await service.list_files("")
self.assertEqual(root_listing["path"], "")
names = {item["name"]: item for item in root_listing["items"]}
self.assertEqual(names["movies"]["type"], "dir")
self.assertEqual(names["readme.txt"]["type"], "file")
nested = await service.list_files("movies")
self.assertEqual(nested["path"], "movies")
self.assertEqual(nested["parent"], "")
self.assertEqual(nested["items"][0]["path"], "movies/a.bin")
self.assertEqual(nested["items"][0]["file"], "a.bin")
class ShareLocalFileTests(SettingsOverrideMixin, unittest.TestCase):
def test_share_local_file_is_zero_copy(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
await init_memory_db()
try:
root = Path(tmpdir)
movies = root / "local" / "movies"
movies.mkdir(parents=True)
source = movies / "doc.txt"
source.write_bytes(b"hello local share")
with patch("core.settings.data_root", root), patch(
"core.storage.data_root", root
):
class Item:
filename = "movies/doc.txt"
expire_value = 1
expire_style = "day"
result = await FileService().share_local_file(Item())
self.assertIn("code", result)
self.assertEqual(result["name"], "doc.txt")
self.assertEqual(result["path"], "movies/doc.txt")
record = await FileCodes.get(code=result["code"])
self.assertTrue(is_local_ref(record))
self.assertEqual(record.file_path, LOCAL_REF_MARKER)
self.assertEqual(record.uuid_file_name, "movies/doc.txt")
self.assertTrue(source.exists())
share_files = [
p for p in (root / "share").rglob("*") if p.is_file()
] if (root / "share").exists() else []
self.assertFalse(share_files)
finally:
await close_db()
class LocalRefCleanupTests(SettingsOverrideMixin, unittest.TestCase):
def test_expire_trashes_record_but_keeps_original(self):
asyncio.run(self._scenario())
async def _scenario(self):
with TemporaryDirectory() as tmpdir:
await init_memory_db()
try:
root = Path(tmpdir)
source = root / "local" / "keep.bin"
source.parent.mkdir(parents=True)
source.write_bytes(b"keep-me")
now = await get_now()
await FileCodes.create(
code="nas1",
prefix="keep",
suffix=".bin",
uuid_file_name="keep.bin",
file_path=LOCAL_REF_MARKER,
size=7,
expired_at=now - datetime.timedelta(days=1),
expired_count=-1,
)
def _sleep(_seconds):
raise SleepSentinel
with patch("core.settings.data_root", root), patch(
"core.storage.data_root", root
), patch("core.tasks.data_root", root), patch(
"core.tasks.asyncio.sleep", side_effect=_sleep
):
try:
await delete_expire_files()
except SleepSentinel:
pass
self.assertTrue(source.exists())
self.assertTrue((await FileCodes.get(code="nas1")).is_trashed)
finally:
await close_db()
class LocalRefQuotaTests(SettingsOverrideMixin, unittest.TestCase):
def test_local_ref_does_not_consume_quota(self):
asyncio.run(self._scenario())
async def _scenario(self):
settings.storageLimit = 100
await init_memory_db()
try:
await FileCodes.create(
code="nas-big",
size=10_000,
expired_count=-1,
file_path=LOCAL_REF_MARKER,
uuid_file_name="movies/huge.bin",
)
await FileCodes.create(code="owned", size=20, expired_count=-1)
usage = await get_storage_usage()
self.assertEqual(usage["used"], 20)
await reserve_storage("upload-ok", 50, 300)
usage = await get_storage_usage()
self.assertEqual(usage["reserved"], 50)
self.assertEqual(usage["available"], 30)
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
+152
View File
@@ -0,0 +1,152 @@
"""Tests for the scrypt password-hashing scheme and transparent rehash.
Legacy formats (sha256$salt$hash and plaintext) must keep verifying; new
hashes are scrypt (memory-hard). A successful login with a legacy-stored
password upgrades the stored hash in place.
"""
import asyncio
import time
import hashlib
import unittest
from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db
from apps.admin import views as admin_views
from apps.base.models import KeyValue
from core.settings import settings
from core.utils import (
hash_password,
is_password_hashed,
password_needs_rehash,
verify_password,
)
class PasswordHashSchemeTests(unittest.TestCase):
def test_scrypt_roundtrip_and_rejection(self):
hashed = hash_password("s3cret-pass")
self.assertTrue(hashed.startswith("scrypt$"))
self.assertTrue(verify_password("s3cret-pass", hashed))
self.assertFalse(verify_password("wrong-pass", hashed))
def test_legacy_sha256_and_plaintext_still_verify(self):
salt = "abcd1234"
sha_hash = f"sha256${salt}${hashlib.sha256(f'{salt}legacy'.encode()).hexdigest()}"
self.assertTrue(verify_password("legacy", sha_hash))
self.assertFalse(verify_password("other", sha_hash))
self.assertTrue(verify_password("plain", "plain"))
self.assertFalse(verify_password("plain", "other-plain"))
def test_scheme_detection_helpers(self):
scrypt_hash = hash_password("x")
sha_hash = "sha256$a$b"
self.assertTrue(is_password_hashed(scrypt_hash))
self.assertTrue(is_password_hashed(sha_hash))
self.assertFalse(is_password_hashed("plaintext"))
self.assertFalse(password_needs_rehash(scrypt_hash))
self.assertTrue(password_needs_rehash(sha_hash))
self.assertTrue(password_needs_rehash("plaintext"))
self.assertFalse(password_needs_rehash(""))
def test_malformed_hashes_are_rejected_not_crashing(self):
self.assertFalse(verify_password("x", "scrypt$1$2$3"))
self.assertFalse(verify_password("x", "scrypt$n$r$p$salt$zzz"))
self.assertFalse(verify_password("x", "sha256$only-two"))
self.assertFalse(verify_password("x", ""))
# 超范围的 n/r/p:解释器抛 TypeError/ValueError(部分构建抛 OverflowError),
# 都必须被吞掉并判为不匹配,而不是让登录及每个请求 500
self.assertFalse(
verify_password("x", "scrypt$99999999999999999999999999$8$1$aa$bb")
)
class TransparentRehashTests(SettingsOverrideMixin, unittest.TestCase):
def test_legacy_hash_upgraded_on_successful_login(self):
asyncio.run(self._scenario())
async def _scenario(self):
await init_memory_db()
try:
legacy_password = "old-style-pass"
salt = "feed1234"
legacy_hash = (
f"sha256${salt}${hashlib.sha256(f'{salt}{legacy_password}'.encode()).hexdigest()}"
)
record = await KeyValue.create(
key="settings",
value={"admin_token": legacy_hash, "jwt_secret": "s" * 48},
)
settings.user_config = dict(record.value)
ok = await admin_views.login(
type("D", (), {"password": legacy_password})(), ip="1.2.3.4"
)
self.assertEqual(ok.detail["username"], "admin")
upgraded = (await KeyValue.filter(key="settings").first()).value["admin_token"]
self.assertTrue(upgraded.startswith("scrypt$"), upgraded[:20])
self.assertTrue(verify_password(legacy_password, upgraded))
self.assertFalse(password_needs_rehash(upgraded))
finally:
await close_db()
if __name__ == "__main__":
unittest.main()
class CheapInitProbeTests(unittest.TestCase):
"""D1 回归:is_config_initialized 在每个请求都会被中间件调用,
对 scrypt 口令绝不允许跑慢哈希。"""
def test_scrypt_token_is_initialized_without_slow_hash(self):
from core.security import is_config_initialized
from core.utils import hash_password as hp
token = hp("some-real-password")
t0 = time.perf_counter()
self.assertTrue(is_config_initialized({"admin_token": token}))
self.assertLess(time.perf_counter() - t0, 0.01, "初始化探测不应执行 scrypt")
def test_empty_and_legacy_default_are_not_initialized(self):
from core.security import is_config_initialized, LEGACY_DEFAULT_ADMIN_TOKEN
self.assertFalse(is_config_initialized({"admin_token": ""}))
self.assertFalse(is_config_initialized({"admin_token": LEGACY_DEFAULT_ADMIN_TOKEN}))
class ConfigCacheTests(unittest.TestCase):
"""D6 回归:TTL 内的 refresh_settings 不再读库,写路径 force=True 必须穿透。
验证手法(无 mock):直接改 DB 里的值——
- TTL 内普通 refresh 不读库 → settings 仍是旧值;
- force=True 读库 → 新值生效。
"""
def test_ttl_cache_skips_db_and_force_bypasses(self):
import core.config as config_module
from apps.base.models import KeyValue
from tests.helpers import close_db, init_memory_db
async def scenario():
await init_memory_db()
try:
row = await KeyValue.create(
key="settings", value={"name": "旧值", "admin_token": "x" * 64}
)
await config_module.refresh_settings(force=True)
self.assertEqual(settings.name, "旧值")
# 直接改 DB(绕过应用层),TTL 内普通 refresh 不应看到
row.value = {"name": "新值", "admin_token": "x" * 64}
await row.save()
await config_module.refresh_settings()
self.assertEqual(settings.name, "旧值", "TTL 内不应读库")
await config_module.refresh_settings(force=True)
self.assertEqual(settings.name, "新值", "force 必须穿透缓存")
finally:
config_module._config_cached_until = 0.0
await close_db()
asyncio.run(scenario())
+1 -7
View File
@@ -1,7 +1,6 @@
from pathlib import Path
import unittest import unittest
from scripts.patch_admin_timeline_ui import build_lifecycle_script, patch_clipboard, patch_file_manage from scripts.patch_admin_timeline_ui import build_lifecycle_script
class AdminTimelinePatchTests(unittest.TestCase): class AdminTimelinePatchTests(unittest.TestCase):
@@ -12,11 +11,6 @@ class AdminTimelinePatchTests(unittest.TestCase):
self.assertIn("展开全部取件记录", script) self.assertIn("展开全部取件记录", script)
self.assertIn("row.style.overflow = 'visible'", script) self.assertIn("row.style.overflow = 'visible'", script)
def test_shared_compiled_modules_are_not_rewritten(self):
placeholder = Path("unused.js")
self.assertFalse(patch_file_manage(placeholder))
self.assertFalse(patch_clipboard(placeholder))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+4 -4
View File
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, patch
from tortoise import Tortoise from tortoise import Tortoise
from apps.base.models import FileCodes, ShareCodeReservations from apps.base.models import FileCodes
from apps.base.utils import CODE_LENGTH, get_random_code from apps.base.utils import CODE_LENGTH, get_random_code
from apps.admin.services import ConfigService, FileService from apps.admin.services import ConfigService, FileService
from core.settings import settings from core.settings import settings
@@ -59,7 +59,7 @@ class RecycleBinTests(unittest.TestCase):
purged = await FileCodes.create(code="purged", prefix="purged", suffix=".txt", file_path="share/data/purged", uuid_file_name="purged.txt", expired_count=-1, is_trashed=True, trash_purged_at=await get_now()) purged = await FileCodes.create(code="purged", prefix="purged", suffix=".txt", file_path="share/data/purged", uuid_file_name="purged.txt", expired_count=-1, is_trashed=True, trash_purged_at=await get_now())
original_refresh = __import__("apps.admin.services", fromlist=["refresh_settings"]).refresh_settings original_refresh = __import__("apps.admin.services", fromlist=["refresh_settings"]).refresh_settings
async def fake_refresh(): async def fake_refresh(**kwargs):
return None return None
module = __import__("apps.admin.services", fromlist=["refresh_settings"]) module = __import__("apps.admin.services", fromlist=["refresh_settings"])
module.refresh_settings = fake_refresh module.refresh_settings = fake_refresh
@@ -87,8 +87,8 @@ class RecycleBinTests(unittest.TestCase):
with self.assertRaises(Exception): with self.assertRaises(Exception):
await service.restore_from_trash(item.id) await service.restore_from_trash(item.id)
await ShareCodeReservations.create(code="RETIRE02", file_code_id=item.id) await FileCodes.create(code="RETIRED1", is_trashed=True, trash_purged_at=datetime.datetime.now())
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRE02", "FRESH002"])): with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRED1", "FRESH002"])):
self.assertEqual(await get_random_code(), "FRESH002") self.assertEqual(await get_random_code(), "FRESH002")
generated_code = await get_random_code() generated_code = await get_random_code()
+5 -2
View File
@@ -1,3 +1,4 @@
from unittest.mock import AsyncMock, patch
import asyncio import asyncio
import unittest import unittest
from pathlib import Path from pathlib import Path
@@ -67,7 +68,8 @@ class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
ip_limit["login"] = self._original_login_limiter ip_limit["login"] = self._original_login_limiter
super().tearDown() super().tearDown()
def test_failed_logins_are_rate_limited(self): @patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_failed_logins_are_rate_limited(self, refresh):
async def attempt(password: str): async def attempt(password: str):
return await admin_views.login( return await admin_views.login(
data=LoginData(password=password), ip="203.0.113.10" data=LoginData(password=password), ip="203.0.113.10"
@@ -80,7 +82,8 @@ class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10")) self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
def test_successful_login_does_not_consume_failure_quota(self): @patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_successful_login_does_not_consume_failure_quota(self, refresh):
result = asyncio.run( result = asyncio.run(
admin_views.login( admin_views.login(
data=LoginData(password="correct-password-123"), ip="198.51.100.8" data=LoginData(password="correct-password-123"), ip="198.51.100.8"
+1 -1
View File
@@ -40,7 +40,7 @@ class LocalFilePathTraversalTests(unittest.TestCase):
self.local_root.mkdir(parents=True, exist_ok=True) self.local_root.mkdir(parents=True, exist_ok=True)
(self.local_root / "safe.txt").write_text("ok", encoding="utf-8") (self.local_root / "safe.txt").write_text("ok", encoding="utf-8")
self._data_root_patch = patch( self._data_root_patch = patch(
"apps.admin.services.data_root", Path(self._tmpdir.name) "core.settings.data_root", Path(self._tmpdir.name)
) )
self._data_root_patch.start() self._data_root_patch.start()
+5 -8
View File
@@ -9,7 +9,7 @@ from apps.base.models import FileCodes, ShareCodeReservations
class ShareCodeReservationTests(unittest.TestCase): class ShareCodeReservationTests(unittest.TestCase):
def test_restore_reserves_old_code_before_assigning_new_code(self): def test_restore_keeps_original_code_and_releases_own_reservation(self):
asyncio.run(self.scenario()) asyncio.run(self.scenario())
async def scenario(self): async def scenario(self):
@@ -25,13 +25,10 @@ class ShareCodeReservationTests(unittest.TestCase):
try: try:
item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text") item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text")
service = FileService() service = FileService()
with patch("apps.admin.services.get_random_code", AsyncMock(return_value="NEWCODE8")): await ShareCodeReservations.create(code="OLD_CODE", file_code_id=item.id, reason="restored")
restored = await service.restore_from_trash(item.id) restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, "OLD_CODE")
self.assertEqual(restored.code, "NEWCODE8") self.assertFalse(await ShareCodeReservations.filter(code="OLD_CODE").exists())
reservation = await ShareCodeReservations.get(code="OLD_CODE")
self.assertEqual(reservation.file_code_id, item.id)
self.assertEqual(reservation.reason, "restored")
# 模拟管理员手工改码:被替换的旧码也必须永久封存。 # 模拟管理员手工改码:被替换的旧码也必须永久封存。
await ShareCodeReservations.get_or_create( await ShareCodeReservations.get_or_create(
+195
View File
@@ -0,0 +1,195 @@
import datetime
import unittest
from unittest.mock import AsyncMock
from fastapi import HTTPException
from tortoise import Tortoise
from apps.admin.services import FileService
from apps.base.models import FileCodes, ShareCodeReservations
from core.utils import get_now
class TrashManagementTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
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()
self.service = FileService()
self.now = await get_now()
self.a = await self.make('Alpha', 'ABC12345', 'manual', self.now + datetime.timedelta(days=30))
self.b = await self.make('Beta', 'BET12345', 'expired', None)
self.purged = await self.make('Retired', 'OLD12345', 'manual', None, self.now)
self.live = await FileCodes.create(code='LIVE1234', prefix='Alpha', suffix='.txt', text='live', expired_count=-1)
async def asyncTearDown(self):
await Tortoise.close_connections()
async def make(self, name, code, reason, expiry, purged=None):
return await FileCodes.create(code=code, prefix=name, suffix='.txt', text='test', expired_count=-1,
is_trashed=True, trashed_at=self.now, trash_reason=reason,
trash_expires_at=expiry, trash_purged_at=purged)
async def test_filters_apply_to_all_records_before_pagination(self):
result = await self.service.list_trash(1, 1, keyword='alpha.txt')
self.assertEqual(result['total'], 1)
self.assertEqual(result['data'][0]['id'], self.a.id)
self.assertEqual(result['summary'], {'total': 3, 'recoverable': 2, 'purged': 1})
by_code = await self.service.list_trash(1, 20, keyword='bet123')
self.assertEqual(by_code['data'][0]['id'], self.b.id)
for state, total in [('all', 3), ('recoverable', 2), ('permanent', 1), ('scheduled', 1), ('purged', 1)]:
self.assertEqual((await self.service.list_trash(1, 20, state=state))['total'], total)
self.assertEqual((await self.service.list_trash(1, 20, reason='expired'))['total'], 1)
self.assertEqual((await self.service.list_trash(1, 20, state='purged', reason='expired'))['total'], 0)
self.assertEqual((await self.service.list_trash(1, 20, keyword='no-match'))['total'], 0)
async def test_invalid_filters_and_page_bounds(self):
for kwargs in [{'state':'invalid'}, {'reason':'invalid'}]:
with self.assertRaises(HTTPException):
await self.service.list_trash(1, 20, **kwargs)
result = await self.service.list_trash(0, 1000)
self.assertEqual((result['page'], result['size']), (1, 100))
async def test_custom_deadline_supports_timezone_and_permanent(self):
deadline = self.now + datetime.timedelta(days=4)
await self.service.set_trash_retention(self.a.id, expires_at=deadline.astimezone(datetime.timezone.utc))
await self.a.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, deadline)
await self.service.set_trash_retention(self.a.id, expires_at=deadline.replace(tzinfo=None))
await self.a.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, deadline)
await self.service.set_trash_retention(self.a.id, 0)
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_expires_at)
await self.service.set_trash_retention(self.a.id, 7)
await self.a.refresh_from_db()
self.assertAlmostEqual((self.a.trash_expires_at-self.now).total_seconds(), 7*86400, delta=3)
async def test_retention_rejects_purged_live_missing_and_invalid_dates(self):
for file_id in [self.purged.id, self.live.id, 9999]:
with self.assertRaises(HTTPException):
await self.service.set_trash_retention(file_id, 0)
for kwargs in [dict(), {'retention_days': -1}, {'expires_at': self.now-datetime.timedelta(days=1)},
{'expires_at': self.now+datetime.timedelta(days=366)}, {'retention_days': 0, 'expires_at': self.now+datetime.timedelta(days=1)}]:
with self.assertRaises(HTTPException):
await self.service.set_trash_retention(self.a.id, **kwargs)
async def test_batch_updates_one_deadline_deduplicates_and_reports_failures(self):
deadline = self.now+datetime.timedelta(days=5)
result = await self.service.batch_trash([self.a.id, self.a.id, self.b.id, self.purged.id, self.live.id, 9999], 'retention', expires_at=deadline)
self.assertEqual(len(result['succeeded']), 2)
self.assertEqual(len(result['failed']), 3)
self.assertEqual(result['requestedCount'], 5)
await self.a.refresh_from_db(); await self.b.refresh_from_db()
self.assertEqual(self.a.trash_expires_at, self.b.trash_expires_at)
self.assertEqual(self.a.trash_expires_at, deadline)
async def test_batch_restore_reuses_old_codes_and_preserves_live_records(self):
old = self.a.code
result = await self.service.batch_trash([self.a.id, self.b.id, self.purged.id, self.live.id], 'restore')
self.assertEqual(len(result['succeeded']), 2)
self.assertEqual(len(result['failed']), 2)
await self.a.refresh_from_db()
self.assertFalse(self.a.is_trashed)
self.assertEqual(old, self.a.code)
self.assertEqual(len(result['succeeded'][0]['code']), 8)
async def test_batch_purge_preserves_audit_and_sanitizes_storage_failures(self):
file = await FileCodes.create(code='FILE1234', prefix='error', suffix='.txt', is_trashed=True, file_path='share/test', uuid_file_name='test.txt', expired_count=-1)
self.service._file_storage = AsyncMock()
self.service._file_storage.delete_file.side_effect = RuntimeError('private storage credentials')
result = await self.service.batch_trash([file.id, self.a.id], 'purge')
self.assertEqual(len(result['succeeded']), 1)
self.assertEqual(result['failed'][0]['reason'], '操作失败,请重试')
await self.a.refresh_from_db(); await file.refresh_from_db()
self.assertIsNotNone(self.a.trash_purged_at)
self.assertTrue(self.a.is_trashed)
self.assertIsNone(file.trash_purged_at)
async def test_bad_batch_request_never_modifies_records(self):
for ids, action, kwargs in [([], 'restore', {}), (list(range(1,102)), 'purge', {}), ([self.a.id], 'bad', {}), ([self.a.id], 'retention', {'retention_days': -1})]:
with self.assertRaises(HTTPException):
await self.service.batch_trash(ids, action, **kwargs)
await self.a.refresh_from_db()
self.assertTrue(self.a.is_trashed)
self.assertIsNone(self.a.trash_purged_at)
async def test_specific_deletion_reasons_and_expiry_classification(self):
from apps.admin.trash_management import automatic_trash_reason
from types import SimpleNamespace
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=self.now, expired_count=-1), self.now), 'expired_time')
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=None, expired_count=0), self.now), 'expired_count')
self.assertEqual(automatic_trash_reason(SimpleNamespace(expired_at=self.now.replace(tzinfo=None), expired_count=0), self.now), 'expired_both')
self.assertIsNone(automatic_trash_reason(SimpleNamespace(expired_at=self.now+datetime.timedelta(days=1), expired_count=-1), self.now))
await self.service.delete_files([self.live.id])
await self.live.refresh_from_db()
self.assertEqual(self.live.trash_reason, 'batch_delete')
result=await self.service.list_trash(1,20,reason='batch_delete')
self.assertEqual(result['total'],1)
self.assertEqual((await self.service.list_trash(1,20,reason='expired_count'))['total'],0)
def api_client(self, authorized=True):
import httpx
from fastapi import FastAPI
from apps.admin.views import admin_api
from apps.admin.dependencies import admin_required, get_file_service
app = FastAPI()
app.include_router(admin_api)
if authorized:
app.dependency_overrides[admin_required] = lambda: None
app.dependency_overrides[get_file_service] = lambda: self.service
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test')
async def test_api_filters_and_batch_custom_deadline(self):
async with self.api_client() as client:
response = await client.get('/admin/trash/list', params={'keyword':'Alpha.txt','state':'scheduled','reason':'manual'})
self.assertEqual(response.status_code,200)
self.assertEqual(response.json()['detail']['total'],1)
self.assertTrue(response.json()['detail']['capabilities']['batch'])
date=(self.now+datetime.timedelta(days=2)).isoformat()
response=await client.post('/admin/trash/batch',json={'ids':[self.a.id,self.b.id],'action':'retention','expiresAt':date})
self.assertEqual(response.status_code,200)
self.assertEqual(len(response.json()['detail']['succeeded']),2)
response=await client.post('/admin/trash/retention',json={'id':self.a.id,'retentionDays':0})
self.assertEqual(response.status_code,200)
self.assertIsNone(response.json()['detail']['trashExpiresAt'])
async def test_api_schema_rejects_invalid_batches_and_requires_authentication(self):
async with self.api_client() as client:
for body in [
{'ids':[],'action':'purge'}, {'ids':[self.a.id],'action':'retention'},
{'ids':[self.a.id],'action':'purge','retentionDays':0},
{'ids':[self.a.id],'action':'retention','retentionDays':0,'expiresAt':self.now.isoformat()},
{'ids':[True],'action':'purge'}, {'ids':[self.a.id],'action':'invalid'},
{'ids':list(range(101)),'action':'purge'},
]:
self.assertEqual((await client.post('/admin/trash/batch',json=body)).status_code,422)
self.assertEqual((await client.post('/admin/trash/retention',json={'id':self.a.id})).status_code,422)
self.assertEqual((await client.get('/admin/trash/list',params={'state':'invalid'})).status_code,400)
async with self.api_client(authorized=False) as client:
response=await client.post('/admin/trash/batch',json={'ids':[self.a.id],'action':'purge'})
self.assertIn(response.status_code,[401,403])
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_purged_at)
async def test_invalid_direct_requests_and_all_failed_batches(self):
for ids,action,kwargs in [([0],'purge',{}),([True],'purge',{}),([self.a.id],'purge',{'retention_days':0})]:
with self.assertRaises(HTTPException):
await self.service.batch_trash(ids,action,**kwargs)
result=await self.service.batch_trash([self.purged.id],'purge')
self.assertEqual(result['succeeded'],[])
self.assertEqual(len(result['failed']),1)
result=await self.service.batch_trash([self.a.id,self.b.id],'retention',retention_days=0)
self.assertEqual(len(result['succeeded']),2)
await self.a.refresh_from_db()
self.assertIsNone(self.a.trash_expires_at)
async def test_restore_rejects_old_code_owned_by_another_active_file(self):
await ShareCodeReservations.create(code=self.a.code, reason='retired')
with self.assertRaises(HTTPException):
await self.service.restore_from_trash(self.a.id)
await self.a.refresh_from_db()
self.assertTrue(self.a.is_trashed)
+131
View File
@@ -0,0 +1,131 @@
import asyncio
import datetime
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import httpx
from fastapi import FastAPI
from apps.admin.services import ConfigService, FileService
from apps.admin.views import admin_api
from apps.base.models import FileCodes, KeyValue
from apps.base.views import share_api
from core.settings import settings
from core.utils import get_now, hash_password
from tests.helpers import close_db, init_memory_db
class UpgradeIntegrationTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.original_settings = dict(settings.user_config)
await init_memory_db()
async def asyncTearDown(self):
settings.user_config = self.original_settings
await close_db()
async def test_time_based_records_do_not_expire_immediately(self):
item = await FileCodes.create(code="DEFAULT1", expired_at=await get_now() + datetime.timedelta(days=1))
self.assertFalse(await item.is_expired())
async def test_legacy_listing_keeps_files_when_many_directories_exist(self):
from apps.admin.services import LocalFileService
from apps.admin.views import get_local_lists
with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)):
root = Path(tmp, "local")
root.mkdir()
for n in range(501):
(root / f"dir-{n}").mkdir()
(root / "visible.txt").write_text("visible")
result = await get_local_lists(path=None, local_file_service=LocalFileService())
self.assertEqual([item["file"] for item in result.detail], ["visible.txt"])
async def test_local_paths_preserve_spaces_and_reject_external_symlinks(self):
from apps.admin.services import LocalFileClass, LocalFileService
from fastapi import HTTPException
with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)):
root = Path(tmp, "local")
root.mkdir()
(root / " report.txt ").write_bytes(b"spaced")
self.assertEqual(await LocalFileClass(" report.txt ").read(), b"spaced")
outside = Path(tmp, "private.txt")
outside.write_bytes(b"private")
(root / "escape.txt").symlink_to(outside)
with self.assertRaises(HTTPException):
LocalFileClass("escape.txt")
listing = await LocalFileService().list_files()
self.assertEqual([item["name"] for item in listing["items"]], [" report.txt "])
async def test_concurrent_activity_writes_keep_every_event(self):
await asyncio.gather(*(FileService().record_admin_activity("file.update", "file", n, f"file-{n}") for n in range(20)))
items = (await FileService().list_admin_activities(size=100))["items"]
self.assertEqual({item["targetId"] for item in items}, set(range(20)))
async def test_concurrent_settings_updates_preserve_both_changes(self):
await ConfigService().update_config({"name": "before", "description": "before"})
await asyncio.gather(ConfigService().update_config({"name": "after"}), ConfigService().update_config({"description": "after"}))
stored = (await KeyValue.get(key="settings")).value
self.assertEqual((stored["name"], stored["description"]), ("after", "after"))
async def test_password_change_rejects_login_waiting_on_old_password(self):
from apps.admin import services, views
from core.config import refresh_settings
from fastapi import HTTPException
row = await KeyValue.create(key="settings", value={"admin_token": hash_password("old-password"), "jwt_secret": "s" * 48})
await refresh_settings(force=True)
async with services.keyvalue_write_lock:
pending = asyncio.create_task(views.login(type("Login", (), {"password": "old-password"})(), ip="192.0.2.77"))
await asyncio.sleep(0)
row.value = {"admin_token": hash_password("new-password"), "jwt_secret": "n" * 48}
await row.save()
await refresh_settings(force=True)
with self.assertRaises(HTTPException) as error:
await pending
self.assertEqual(error.exception.status_code, 401)
async def test_local_share_http_download_trash_restore_and_purge_preserve_source(self):
settings.user_config = {"admin_token": hash_password("integration-password"), "jwt_secret": "s" * 48, "file_storage": "webdav"}
await KeyValue.create(key="settings", value=dict(settings.user_config))
app = FastAPI()
app.include_router(admin_api)
app.include_router(share_api)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
login = await client.post("/admin/login", json={"password": "integration-password"})
self.assertEqual(login.status_code, 200, login.text)
headers = {"Authorization": "Bearer " + login.json()["detail"]["token"]}
with TemporaryDirectory() as tmp, patch("core.settings.data_root", Path(tmp)):
source = Path(tmp, "local", "nested", "sample.txt")
source.parent.mkdir(parents=True)
source.write_bytes(b"original NAS bytes")
unauthorized = await client.get("/admin/local/lists", params={"path": "nested"})
self.assertIn(unauthorized.status_code, (401, 403))
listing = await client.get("/admin/local/lists", params={"path": "nested"}, headers=headers)
self.assertEqual(listing.json()["detail"]["items"][0]["path"], "nested/sample.txt")
legacy = await client.get("/admin/local/lists", headers=headers)
self.assertIsInstance(legacy.json()["detail"], list)
bad = await client.get("/admin/local/lists", params={"path": "../"}, headers=headers)
self.assertEqual(bad.status_code, 400)
shared = await client.post("/admin/local/share", headers=headers, json={"filename": "nested/sample.txt", "expire_style": "day", "expire_value": 1})
self.assertEqual(shared.status_code, 200, shared.text)
code = shared.json()["detail"]["code"]
item = await FileCodes.get(code=code)
selected = await client.post("/share/select/", json={"code": code})
self.assertEqual(selected.json()["detail"]["used_count"], 0)
downloaded = await client.get(selected.json()["detail"]["download_url"])
self.assertEqual(downloaded.content, b"original NAS bytes")
service = FileService()
await service.move_to_trash(item, reason="manual")
hidden = await client.post("/share/select/", json={"code": code})
self.assertEqual(hidden.json()["code"], 404)
restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, code)
self.assertEqual((await client.get("/admin/file/download", params={"id": item.id}, headers=headers)).content, b"original NAS bytes")
await service.move_to_trash(restored, reason="manual")
await service.purge_trashed_file(restored)
self.assertEqual(source.read_bytes(), b"original NAS bytes")
self.assertIsNotNone((await FileCodes.get(id=item.id)).trash_purged_at)