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

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

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
.git
.idea
node_modules
data
output
coverage
__pycache__
**/__pycache__
.pytest_cache
.coverage*
*.log
.env*
+8
View File
@@ -29,3 +29,11 @@ output
*.sw?
*.tsbuildinfo
# Python verification artifacts
__pycache__/
*.py[cod]
.coverage*
.pytest_cache/
/data/
+3
View File
@@ -0,0 +1,3 @@
{
".": "2.7.0"
}
+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}"
+67
View File
@@ -0,0 +1,67 @@
# 官方版本整合与发布
后续官方更新沿用本流程:比较源码并选择有用改动,保留定制功能和兼容接口;
先升级测试实例,验证后再升级正式实例;最后同步 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 .
```
正式实例用其原镜像作为基础,确保前端与测试实例差异不会被意外覆盖。
需要更新主题时再用主 Dockerfile,并固定各主题的 Git 提交。
## 验证与部署
1. 单元及集成:`python -m pytest -q`;覆盖率:
`python -m pytest --cov=apps --cov=core --cov=main --cov-report=term`。
2. 前端:`node --test --experimental-test-coverage tests/retrieval-code.test.mjs tests/scrollLock.test.mjs`;
`npm run build`。本地未生成主题时,两个主题测试会跳过,必须在最终镜像中补跑。
3. 备份原镜像、Compose、容器配置;使用 SQLite backup API 备份应用数据库和
`/opt/1panel/db/agent.db`,不能直接复制正在写入的 WAL 数据库。
4. 测试实例 `filecodebox-test`(40158)先更新,保留独立数据目录。
验证首页/静态资源、版本、鉴权、上传下载、NAS 分享和回收站。
5. 正式实例 `filecodebox`(40157)使用相同源码提交,保留正式数据及主题,
更新后再验证接口、日志、容器状态。失败时恢复原镜像/Compose,必要时恢复数据库备份。
6. 验证运行时与镜像确为目标版本后,在事务中仅更新对应 `app_installs` 的
`version`、同 `app_id` 下目标版本的 `app_detail_id`、实际 `docker_compose` 和时间戳。
同步磁盘 Compose。保留 `app_id` 和官方商店关联,不改全局 `app_details.update`,
不把新版本加入忽略列表。测试实例目前不在 1Panel `app_installs` 中,不伪造安装记录。
7. 重新读取安装记录、容器及 HTTP 版本;核对 1Panel 升级候选列表不再包含已安装版本。
官方发布更高版本后仍应提示,再重复本流程。
生产按单 worker 运行。配置/审计写锁为进程内锁;多 worker 需要跨进程并发控制后再启用。
+1 -1
View File
@@ -1 +1 @@
2.5.6
2.7.0
+244 -222
View File
@@ -1,13 +1,17 @@
import asyncio
import hashlib
import json
from pathlib import Path
import os
import time
import uuid
from datetime import datetime, timedelta
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.storage import FileStorageInterface, storages
from core.settings import (
@@ -19,16 +23,18 @@ from core.config import refresh_settings
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.utils import get_expire_info, get_file_path_name, get_random_code
from apps.base.quota import release_storage, reserve_storage
from apps.base.utils import get_expire_info, get_random_code
from fastapi import HTTPException
from core.settings import data_root
from core.utils import get_now, hash_password, is_password_hashed
from core.utils import get_now, hash_password, is_password_hashed, validate_background_url
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_VIEW_PRESETS_KEY = "admin_file_view_presets"
@@ -140,7 +146,7 @@ class FileService(TrashManagementMixin):
return file_code
now = await get_now()
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 file_code.update_from_dict(
{
@@ -172,7 +178,7 @@ class FileService(TrashManagementMixin):
if file_code.trash_purged_at is not None:
raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录")
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:
raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复")
destination_dir, filename = os.path.split(original_path)
@@ -226,7 +232,7 @@ class FileService(TrashManagementMixin):
async def purge_trashed_file(self, file_code: FileCodes) -> None:
if file_code.trash_purged_at is not None:
return
if file_code.text is None:
if not should_skip_storage_delete(file_code):
trash_path = self._trash_path(file_code)
await self.file_storage.delete_file(
FileCodes(
@@ -456,44 +462,45 @@ class FileService(TrashManagementMixin):
name: str,
filters: dict[str, Any],
) -> dict[str, Any]:
presets = await self._get_file_view_presets()
normalized_name = self._normalize_file_view_preset_name(name)
normalized_filters = self._normalize_file_view_preset_filters(filters)
now = await get_now()
updated_at = now.isoformat()
async with keyvalue_write_lock:
presets = await self._get_file_view_presets()
normalized_name = self._normalize_file_view_preset_name(name)
normalized_filters = self._normalize_file_view_preset_filters(filters)
now = await get_now()
updated_at = now.isoformat()
target_index = next(
(index for index, preset in enumerate(presets) if preset["id"] == preset_id),
-1,
)
is_update = target_index >= 0
if is_update:
preset = presets[target_index]
next_preset = {
**preset,
"name": normalized_name,
"filters": normalized_filters,
"params": normalized_filters,
"updatedAt": updated_at,
"updated_at": updated_at,
}
presets[target_index] = next_preset
else:
if len(presets) >= self.MAX_VIEW_PRESETS:
raise HTTPException(status_code=400, detail="视图预设数量已达上限")
next_preset = {
"id": preset_id or self._build_file_view_preset_id(normalized_name, now),
"name": normalized_name,
"filters": normalized_filters,
"params": normalized_filters,
"createdAt": updated_at,
"created_at": updated_at,
"updatedAt": updated_at,
"updated_at": updated_at,
}
presets.append(next_preset)
target_index = next(
(index for index, preset in enumerate(presets) if preset["id"] == preset_id),
-1,
)
is_update = target_index >= 0
if is_update:
preset = presets[target_index]
next_preset = {
**preset,
"name": normalized_name,
"filters": normalized_filters,
"params": normalized_filters,
"updatedAt": updated_at,
"updated_at": updated_at,
}
presets[target_index] = next_preset
else:
if len(presets) >= self.MAX_VIEW_PRESETS:
raise HTTPException(status_code=400, detail="视图预设数量已达上限")
next_preset = {
"id": preset_id or self._build_file_view_preset_id(normalized_name, now),
"name": normalized_name,
"filters": normalized_filters,
"params": normalized_filters,
"createdAt": updated_at,
"created_at": updated_at,
"updatedAt": updated_at,
"updated_at": updated_at,
}
presets.append(next_preset)
await self._save_file_view_presets(presets)
await self._save_file_view_presets(presets)
await self.record_admin_activity(
action="file.view_preset_update" if is_update else "file.view_preset_create",
target_type="view_preset",
@@ -509,16 +516,17 @@ class FileService(TrashManagementMixin):
if not preset_id:
raise HTTPException(status_code=400, detail="请选择要删除的视图预设")
presets = await self._get_file_view_presets()
deleted_preset = next(
(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):
raise HTTPException(status_code=404, detail="视图预设不存在")
async with keyvalue_write_lock:
presets = await self._get_file_view_presets()
deleted_preset = next(
(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):
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(
action="file.view_preset_delete",
target_type="view_preset",
@@ -635,7 +643,7 @@ class FileService(TrashManagementMixin):
"fileCount": 0,
"chunkedCount": 0,
**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),
}
@@ -1009,12 +1017,13 @@ class FileService(TrashManagementMixin):
if not activity:
return None
activities = await self._get_admin_activities()
next_activities = [
activity,
*[item for item in activities if item["id"] != activity["id"]],
][: self.MAX_ADMIN_ACTIVITIES]
await self._save_admin_activities(next_activities)
async with keyvalue_write_lock:
activities = await self._get_admin_activities()
next_activities = [
activity,
*[item for item in activities if item["id"] != activity["id"]],
][: self.MAX_ADMIN_ACTIVITIES]
await self._save_admin_activities(next_activities)
return activity
except Exception:
return None
@@ -1632,6 +1641,8 @@ class FileService(TrashManagementMixin):
if file_code.text:
return APIResponse(detail=file_code.text)
else:
if is_local_ref(file_code):
return build_local_ref_download(file_code)
return await self.file_storage.get_file_response(file_code)
async def preview_file(self, file_id: int, max_chars: int = 4000):
@@ -1667,40 +1678,28 @@ class FileService(TrashManagementMixin):
if not await local_file.exists():
raise HTTPException(status_code=404, detail="文件不存在")
reservation_token = f"local:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600)
try:
text = await local_file.read()
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(
item
)
await self.file_storage.save_file(text, save_path)
try:
await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
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)
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
name = local_file.name
suffix = Path(name).suffix
prefix = name[: len(name) - len(suffix)] if suffix else name
record = await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=local_file.file,
file_path=LOCAL_REF_MARKER,
size=local_file.size or 0,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
return {
"code": code,
"name": local_file.file,
"name": name,
"path": local_file.file,
"id": record.id,
}
@@ -1737,112 +1736,158 @@ class ConfigService:
return config
async def update_config(self, data: dict):
current_config = dict(settings.items())
next_config = dict(current_config)
update_data = {
key: value
for key, value in data.items()
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
}
async with keyvalue_write_lock:
await refresh_settings(force=True)
current_config = dict(settings.items())
next_config = dict(current_config)
update_data = {
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_password_changed = False
if admin_token is None or admin_token == "":
update_data.pop("admin_token", None)
elif not is_password_hashed(admin_token):
update_data["admin_token"] = hash_password(admin_token)
admin_password_changed = True
else:
admin_password_changed = True
admin_token = update_data.get("admin_token")
admin_password_changed = False
if admin_token is None or admin_token == "":
update_data.pop("admin_token", None)
elif not is_password_hashed(admin_token):
update_data["admin_token"] = hash_password(admin_token)
admin_password_changed = True
else:
admin_password_changed = True
for key, value in update_data.items():
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
continue
for key, value in update_data.items():
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
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:
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
session_expire = int(next_config.get("adminSessionExpire"))
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:
session_expire = int(next_config.get("adminSessionExpire"))
except (TypeError, ValueError):
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:
trash_retention_days = int(
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",
try:
trash_retention_days = int(
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 admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
if int(next_config.get("storageLimit", 0)) < 0:
raise HTTPException(
status_code=400,
detail="storageLimit 不能小于 0",
)
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings()
if str(next_config.get("background") or "") != str(current_config.get("background") or ""):
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:
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)
if admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
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:
async def list_files(self):
files = []
if not os.path.exists(data_root / "local"):
os.makedirs(data_root / "local")
for file in os.listdir(data_root / "local"):
local_file = LocalFileClass(file)
files.append({
"file": local_file.file,
"ctime": local_file.ctime,
"size": local_file.size,
})
return files
async def list_files(self, path: str = "", *, legacy: bool = False):
relpath = normalize_local_relpath(path, allow_empty=True)
directory = resolve_under_local(relpath)
if not directory.exists() or not directory.is_dir():
raise HTTPException(status_code=404, detail="目录不存在")
root = get_local_root()
items = []
try:
children = list(directory.iterdir())
except OSError as exc:
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):
file = LocalFileClass(filename)
@@ -1854,52 +1899,29 @@ class LocalFileService:
class LocalFileClass:
def __init__(self, file):
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。
raw_name = str(file or "")
normalized = Path(raw_name).as_posix()
# 输入本身不得包含路径分隔符或绝对路径形态。
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
relpath = normalize_local_relpath(file)
self.file = relpath
self.name = Path(relpath).name
self.path = resolve_under_local(relpath)
if self.path.is_file():
self.ctime = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
)
self.size = os.path.getsize(self.path)
self.ctime = format_local_ctime(self.path)
self.size = self.path.stat().st_size
else:
self.ctime = None
self.size = None
async def read(self):
return open(self.path, "rb")
async def read(self) -> bytes:
with open(self.path, "rb") as fh:
return fh.read()
async def write(self, data):
with open(self.path, "w") as f:
with open(self.path, "wb") as f:
f.write(data)
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):
return self.path.is_file()
+36 -19
View File
@@ -7,6 +7,7 @@ from collections import Counter
from typing import Optional
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.dependencies import (
admin_required,
@@ -31,6 +32,7 @@ from apps.admin.schemas import (
LoginData,
UpdateFileData,
)
from apps.base.local_share import is_local_ref
from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
from apps.admin.dependencies import (
@@ -40,7 +42,8 @@ from apps.admin.dependencies import (
)
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
admin_api = APIRouter(
@@ -58,23 +61,34 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
@admin_api.post("/login")
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
if not verify_password(data.password, settings.admin_token):
ip_limit["login"].add_ip(ip)
raise HTTPException(status_code=401, detail="密码错误")
# Check and issue the token under the same lock used for password changes.
async with admin_services.keyvalue_write_lock:
await refresh_settings(force=True)
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()
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,
}
)
if password_needs_rehash(settings.admin_token):
record = await KeyValue.filter(key="settings").first()
if record:
stored = dict(record.value or {})
stored["admin_token"] = hash_password(data.password)
record.value = stored
await record.save()
await refresh_settings(force=True)
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")
@@ -107,7 +121,7 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
@admin_api.get("/dashboard")
async def dashboard(file_service: FileService = Depends(get_file_service)):
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()
now = await get_now()
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
@@ -816,9 +830,12 @@ async def file_preview(
@admin_api.get("/local/lists")
async def get_local_lists(
path: Optional[str] = None,
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)
+105
View File
@@ -0,0 +1,105 @@
"""Local NAS-style share helpers.
Files under ``data/local`` can be browsed by admin and turned into extract
codes without copying them into ``data/share``. The original file is never
deleted when a share expires or is removed from the file list.
``FileCodes.file_path`` is the sentinel ``local-ref``; ``uuid_file_name``
stores the posix relative path under ``data/local``. Accidental storage
deletes therefore look at ``data/local-ref/...`` and cannot touch the
original NAS file.
"""
from __future__ import annotations
import time
from pathlib import Path
from urllib.parse import quote
from fastapi import HTTPException
from starlette.responses import FileResponse
LOCAL_REF_MARKER = "local-ref"
MAX_RELPATH_LEN = 255
MAX_LIST_ENTRIES = 500
def is_local_ref(file_code) -> bool:
return (getattr(file_code, "file_path", None) or "") == LOCAL_REF_MARKER
def should_skip_storage_delete(file_code) -> bool:
return is_local_ref(file_code) or getattr(file_code, "text", None) is not None
def get_local_root() -> Path:
from core.settings import data_root
root = (Path(data_root) / "local").resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def normalize_local_relpath(raw: str, *, allow_empty: bool = False) -> str:
text = str(raw or "").replace("\\", "/")
if not text:
if allow_empty:
return ""
raise HTTPException(status_code=400, detail="非法文件名")
if (
text in {".", ".."}
or text.startswith("/")
or text.startswith("~")
or "\x00" in text
or ":" in text.split("/", 1)[0]
):
raise HTTPException(status_code=400, detail="非法文件名")
parts = [part for part in text.split("/") if part not in {"", "."}]
if not parts or any(part == ".." for part in parts):
raise HTTPException(status_code=400, detail="非法文件名")
relpath = "/".join(parts)
if len(relpath) > MAX_RELPATH_LEN:
raise HTTPException(status_code=400, detail="路径过长")
return relpath
def resolve_under_local(relpath: str) -> Path:
root = get_local_root()
if not relpath:
return root
candidate = (root / relpath).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise HTTPException(status_code=400, detail="非法文件路径") from exc
return candidate
def format_local_ctime(path: Path) -> str | None:
try:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(path.stat().st_ctime))
except OSError:
return None
def build_local_ref_download(file_code) -> FileResponse:
try:
relpath = normalize_local_relpath(getattr(file_code, "uuid_file_name", None) or "")
path = resolve_under_local(relpath)
except HTTPException as exc:
raise HTTPException(status_code=404, detail="文件已过期删除") from exc
if not path.is_file():
raise HTTPException(status_code=404, detail="文件已过期删除")
filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}"
if not filename:
filename = path.name
encoded_filename = quote(filename, safe="")
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}
try:
headers["Content-Length"] = str(path.stat().st_size)
except OSError:
pass
return FileResponse(path=path, filename=filename, headers=headers)
+1 -1
View File
@@ -22,7 +22,7 @@ class FileCodes(models.Model):
size = fields.BigIntField(default=0)
text = fields.TextField(null=True)
expired_at = fields.DatetimeField(null=True)
expired_count = fields.IntField(default=0)
expired_count = fields.IntField(default=-1)
used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True)
file_hash = fields.CharField(max_length=64, null=True)
+20 -7
View File
@@ -2,12 +2,24 @@ import datetime
from fastapi import HTTPException
from tortoise import connections
from tortoise.expressions import Q
from tortoise.functions import Sum
from apps.base.models import FileCodes, StorageReservation
from apps.base.local_share import LOCAL_REF_MARKER
from core.settings import settings
from core.utils import get_now
def owned_storage_queryset(queryset=None):
"""FileCodes that occupy FileCodeBox storage (exclude NAS local-ref rows).
SQL ``file_path != 'local-ref'`` drops NULLs, so keep null paths explicitly.
"""
qs = FileCodes.all() if queryset is None else queryset
return qs.filter(Q(file_path__isnull=True) | ~Q(file_path=LOCAL_REF_MARKER))
def _detect_sql_dialect() -> str:
"""识别当前默认连接的 SQL 方言。
@@ -54,13 +66,14 @@ def get_storage_limit() -> int:
async def get_storage_usage() -> dict[str, int | None]:
now = await get_now()
used = await FileCodes.all().values_list("size", flat=True)
reserved = await StorageReservation.filter(expires_at__gt=now).values_list(
"size", flat=True
)
# SQL 聚合:此函数在每次上传配额检查时调用,禁止全表拉取(D3)
used_rows = await owned_storage_queryset().annotate(total=Sum("size")).values("total")
reserved_rows = await StorageReservation.filter(expires_at__gt=now).annotate(
total=Sum("size")
).values("total")
limit = get_storage_limit()
used_bytes = sum(used)
reserved_bytes = sum(reserved)
used_bytes = used_rows[0]["total"] or 0
reserved_bytes = reserved_rows[0]["total"] or 0
return {
"limit": limit,
"used": used_bytes,
@@ -92,7 +105,7 @@ async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
INSERT INTO storagereservation (token, size, expires_at)
SELECT {ph[0]}, {ph[1]}, {ph[2]}
WHERE (
COALESCE((SELECT SUM(size) FROM filecodes), 0)
COALESCE((SELECT SUM(size) FROM filecodes WHERE file_path IS NULL OR file_path != '{LOCAL_REF_MARKER}'), 0)
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
+ {ph[4]}
) <= {ph[5]}
+4 -3
View File
@@ -31,6 +31,7 @@ from apps.base.utils import (
get_chunk_file_path_name,
validate_expire_style,
)
from apps.base.local_share import is_local_ref, build_local_ref_download
from core.response import APIResponse
from core.settings import settings
from core.storage import storages, FileStorageInterface
@@ -293,7 +294,7 @@ async def build_select_detail(
metadata = build_file_metadata(file_code)
if file_code.text is not None:
download_url = None
elif file_code.expired_count >= 0:
elif file_code.expired_count >= 0 or is_local_ref(file_code):
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
download_url = await get_proxy_file_url(file_code.code)
else:
@@ -357,7 +358,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
},
)
return await file_storage.get_file_response(file_code)
return (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
@share_api.post("/select/")
@@ -406,7 +407,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
return (
APIResponse(detail=file_code.text)
if file_code.text
else await file_storage.get_file_response(file_code)
else (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
)
+13 -3
View File
@@ -1,3 +1,5 @@
import time
from apps.base.models import KeyValue
from apps.base.utils import ip_limit
from core.database import db_startup_lock
@@ -61,7 +63,7 @@ async def ensure_security_settings() -> None:
logger.info("已将管理员密码迁移为哈希存储")
if security_config.jwt_secret_rotated:
logger.info("已生成独立 JWT 签名密钥")
await refresh_settings()
await refresh_settings(force=True)
def _sync_ip_limits() -> None:
@@ -75,11 +77,19 @@ def _sync_ip_limits() -> None:
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()
settings.user_config = config_record.value if config_record and config_record.value else {}
_sync_ip_limits()
_config_cached_until = time.monotonic() + CONFIG_CACHE_TTL_SECONDS
def is_runtime_initialized() -> bool:
@@ -118,4 +128,4 @@ async def initialize_system(
next_config["jwt_secret"] = generate_jwt_secret()
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 "")
if not admin_token:
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)
+71 -7
View File
@@ -13,6 +13,27 @@ import time
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):
"""返回指定长度的纯数字取件码。"""
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
# 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:
"""
使用 SHA256 + salt 哈希密码
返回格式: sha256$<salt>$<hash>
使用 scrypt(memory-hard)哈希密码
返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
"""
salt = os.urandom(16).hex()
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return f"sha256${salt}${password_hash}"
password_hash = hashlib.scrypt(
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:
"""
验证密码是否匹配
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
"""
if not hashed:
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$"):
parts = hashed.split("$")
if len(parts) != 3:
@@ -135,11 +192,18 @@ def verify_password(password: str, hashed: 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
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:
"""
安全处理文件名:
+22
View File
@@ -0,0 +1,22 @@
version: "3"
services:
file-code-box:
image: local/filecodebox:2.7.0 # x-release-please-version
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
ports:
- "12345:12345"
environment:
- APP_ENV=production
- LOG_LEVEL=warning
- ACCESS_LOG=false
- WORKERS=1
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
fcb-data:
external: false
+1 -1
View File
@@ -759,7 +759,7 @@ async def load_config():
await KeyValue.update_or_create(
key="sys_start", defaults={"value": int(time.time() * 1000)}
)
await refresh_settings()
await refresh_settings(force=True)
await ensure_security_settings()
ip_limit["error"].minutes = settings.errorMinute
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "filecodeboxfronted",
"version": "0.0.0",
"version": "2.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "filecodeboxfronted",
"version": "0.0.0",
"version": "2.7.0",
"dependencies": {
"@tailwindcss/typography": "^0.5.16",
"axios": "^1.13.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "filecodeboxfronted",
"version": "0.0.0",
"version": "2.7.0",
"private": true,
"type": "module",
"scripts": {
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()
+279
View File
@@ -0,0 +1,279 @@
from unittest.mock import AsyncMock, patch
import asyncio
import copy
import unittest
import apps.admin.services as admin_services
import apps.admin.views as admin_views
import apps.admin.dependencies as admin_dependencies
import core.config as core_config
from apps.admin.dependencies import create_token, verify_token
from apps.admin.schemas import LoginData
from apps.admin.services import ConfigService
from fastapi import HTTPException
from main import parse_setup_options
from core.security import (
LEGACY_DEFAULT_ADMIN_TOKEN,
is_config_initialized,
prepare_security_config,
)
from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password, verify_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class SecurityConfigTests(unittest.TestCase):
def test_initial_security_config_requires_setup_and_generates_jwt_secret(self):
result = prepare_security_config(DEFAULT_CONFIG)
self.assertTrue(result.changed)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertFalse(is_config_initialized(result.config))
self.assertGreaterEqual(len(result.config["jwt_secret"]), 32)
def test_legacy_default_password_requires_setup(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = hash_password(LEGACY_DEFAULT_ADMIN_TOKEN)
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertEqual(result.config["jwt_secret"], "j" * 48)
def test_custom_plaintext_password_is_hashed_and_initialized(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = "custom-password"
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.password_hashed)
self.assertTrue(is_config_initialized(result.config))
self.assertTrue(verify_password("custom-password", result.config["admin_token"]))
class SetupOptionTests(unittest.TestCase):
def test_parse_setup_options_converts_common_fields(self):
options = parse_setup_options(
{
"upload_size_value": "20",
"upload_size_unit": "MB",
"save_time_value": "7",
"save_time_unit": "day",
"uploadCount": "30",
"uploadMinute": "2",
"errorCount": "5",
"errorMinute": "1",
"loginCount": "4",
"loginMinute": "20",
"openUpload": ["0", "1"],
"enableChunk": "0",
"code_generate_type": "secret",
"expireStyle": ["day", "count"],
"allowed_file_types": ".zip, image/*",
}
)
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
self.assertEqual(options["max_save_seconds"], 7 * 86400)
self.assertEqual(options["uploadCount"], 30)
self.assertEqual(options["uploadMinute"], 2)
self.assertEqual(options["errorCount"], 5)
self.assertEqual(options["errorMinute"], 1)
self.assertEqual(options["loginCount"], 4)
self.assertEqual(options["loginMinute"], 20)
self.assertEqual(options["openUpload"], 1)
self.assertEqual(options["enableChunk"], 0)
self.assertEqual(options["code_generate_type"], "secret")
self.assertEqual(options["expireStyle"], ["day", "count"])
self.assertEqual(options["allowed_file_types"], [".zip", "image/*"])
def test_parse_setup_options_allows_turning_guest_upload_off(self):
options = parse_setup_options(
{
"openUpload": "0",
"expireStyle": ["day"],
}
)
self.assertEqual(options["openUpload"], 0)
def test_parse_setup_options_requires_expire_style(self):
with self.assertRaises(ValueError):
parse_setup_options({"expireStyle": []})
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
def test_admin_jwt_signature_uses_independent_secret(self):
settings.admin_token = hash_password("old-admin-password")
settings.jwt_secret = "j" * 48
token = create_token({"is_admin": True}, expires_in=60)
self.assertTrue(verify_token(token)["is_admin"])
settings.admin_token = hash_password("new-admin-password")
self.assertTrue(verify_token(token)["is_admin"])
settings.jwt_secret = "k" * 48
with self.assertRaises(ValueError):
verify_token(token)
@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.jwt_secret = "j" * 48
settings.adminSessionExpire = 90 * 24 * 60 * 60
original_time = admin_dependencies.time.time
admin_dependencies.time.time = lambda: 1_800_000_000
try:
response = asyncio.run(
admin_views.login(LoginData(password="admin-password"))
)
payload = verify_token(response.detail["token"])
finally:
admin_dependencies.time.time = original_time
self.assertEqual(response.detail["expires_in"], 90 * 24 * 60 * 60)
self.assertEqual(
response.detail["expires_at"], 1_800_000_000 + 90 * 24 * 60 * 60
)
self.assertEqual(payload["exp"], response.detail["expires_at"])
class FakeKeyValue:
saved_value = None
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
async def fake_refresh_settings(**kwargs):
return None
class FakeConfigRecord:
def __init__(self, value):
self.value = value
class FakeConfigQuery:
async def first(self):
return FakeConfigKeyValue.record
class FakeConfigKeyValue:
record = None
saved_value = None
@classmethod
def filter(cls, key):
return FakeConfigQuery()
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
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):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
with self.assertRaises(HTTPException) as context:
asyncio.run(ConfigService().update_config({"storageLimit": -1}))
self.assertEqual(context.exception.status_code, 400)
def test_admin_session_lifetime_rejects_out_of_range_values(self):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
for invalid_value in (0, 86399, 90000, 365 * 24 * 60 * 60 + 1):
with self.subTest(invalid_value=invalid_value):
with self.assertRaises(HTTPException) as context:
asyncio.run(
ConfigService().update_config(
{"adminSessionExpire": invalid_value}
)
)
self.assertEqual(context.exception.status_code, 400)
def test_admin_password_update_rotates_jwt_secret(self):
old_secret = "j" * 48
settings.user_config = {
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": hash_password("old-admin-password"),
"jwt_secret": old_secret,
}
original_key_value = admin_services.KeyValue
original_refresh_settings = admin_services.refresh_settings
admin_services.KeyValue = FakeKeyValue
admin_services.refresh_settings = fake_refresh_settings
FakeKeyValue.saved_value = None
try:
asyncio.run(ConfigService().update_config({"admin_token": "new-admin-password"}))
finally:
admin_services.KeyValue = original_key_value
admin_services.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeKeyValue.saved_value)
self.assertTrue(verify_password("new-admin-password", FakeKeyValue.saved_value["admin_token"]))
self.assertNotEqual(FakeKeyValue.saved_value["jwt_secret"], old_secret)
self.assertGreaterEqual(len(FakeKeyValue.saved_value["jwt_secret"]), 32)
def test_initialize_system_sets_admin_password_and_jwt_secret(self):
original_key_value = core_config.KeyValue
original_refresh_settings = core_config.refresh_settings
FakeConfigKeyValue.record = FakeConfigRecord(
{
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": "",
"jwt_secret": "",
}
)
FakeConfigKeyValue.saved_value = None
core_config.KeyValue = FakeConfigKeyValue
core_config.refresh_settings = fake_refresh_settings
try:
asyncio.run(
core_config.initialize_system(
admin_password="new-admin-password",
site_name="我的文件快递柜",
setup_options={
"uploadSize": 50 * 1024 * 1024,
"errorCount": 6,
"expireStyle": ["day", "count"],
},
)
)
finally:
core_config.KeyValue = original_key_value
core_config.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeConfigKeyValue.saved_value)
self.assertTrue(
verify_password("new-admin-password", FakeConfigKeyValue.saved_value["admin_token"])
)
self.assertGreaterEqual(len(FakeConfigKeyValue.saved_value["jwt_secret"]), 32)
self.assertEqual(FakeConfigKeyValue.saved_value["name"], "我的文件快递柜")
self.assertEqual(FakeConfigKeyValue.saved_value["uploadSize"], 50 * 1024 * 1024)
self.assertEqual(FakeConfigKeyValue.saved_value["errorCount"], 6)
self.assertEqual(FakeConfigKeyValue.saved_value["expireStyle"], ["day", "count"])
+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()
+33
View File
@@ -0,0 +1,33 @@
import unittest
from core.settings import settings
from core.storage import S3FileStorage
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
def test_client_config_uses_path_style_when_configured(self):
storage = S3FileStorage.__new__(S3FileStorage)
storage.signature_version = "s3v4"
storage.addressing_style = "path"
config = storage._client_config()
self.assertEqual(config.signature_version, "s3v4")
self.assertEqual(config.s3["addressing_style"], "path")
def test_client_config_ignores_invalid_addressing_style(self):
storage = S3FileStorage.__new__(S3FileStorage)
storage.signature_version = "s3v4"
storage.addressing_style = "invalid"
config = storage._client_config()
self.assertIsNone(config.s3)
+65
View File
@@ -0,0 +1,65 @@
import asyncio
import unittest
from datetime import datetime, timedelta
from apps.admin.services import FileService
from core.settings import settings
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class FakeFileCode:
def __init__(self):
self.id = 1
self.code = "ABC123"
self.prefix = "report"
self.suffix = ".txt"
self.uuid_file_name = "report.txt"
self.file_path = "share/data/2026/01/01/abc"
self.size = 12
self.text = None
self.expired_at = datetime(2026, 1, 2, 12, 0, 0)
self.expired_count = 3
self.used_count = 0
self.created_at = datetime(2026, 1, 1, 12, 0, 0)
self.file_hash = "a" * 64
self.is_chunked = False
self.upload_id = None
async def is_expired(self):
return False
class AdminFileItemTests(SettingsOverrideMixin, unittest.TestCase):
def test_build_admin_file_item_serializes_required_fields(self):
settings.file_storage = "local"
service = FileService()
now = datetime(2026, 1, 1, 13, 0, 0)
item = asyncio.run(service._build_admin_file_item(FakeFileCode(), now=now))
self.assertEqual(item["id"], 1)
self.assertEqual(item["name"], "report.txt")
self.assertEqual(item["type"], "file")
self.assertFalse(item["isExpired"])
self.assertEqual(item["remainingDownloads"], 3)
self.assertEqual(item["file_path"], "share/data/2026/01/01/abc")
self.assertIn("never_retrieved", item["statusInsights"]["reasons"])
self.assertEqual(item["statusInsights"]["metrics"]["ageSeconds"], 3600)
def test_build_admin_file_item_marks_expiring_soon(self):
settings.file_storage = "local"
service = FileService()
file_code = FakeFileCode()
now = file_code.expired_at - timedelta(hours=2)
item = asyncio.run(service._build_admin_file_item(file_code, now=now))
self.assertEqual(item["statusInsights"]["severity"], "warning")
self.assertIn("expires_soon", item["statusInsights"]["reasons"])
+31
View File
@@ -0,0 +1,31 @@
import unittest
from fastapi import HTTPException
from apps.base.views import validate_file_type
from core.settings import settings
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
def test_allows_extensions_and_mime_patterns(self):
settings.allowed_file_types = ["rar", ".zip", "image/*"]
validate_file_type("backup.RAR")
validate_file_type("archive.zip")
validate_file_type("avatar.bin", "image/png")
def test_rejects_disallowed_file_type(self):
settings.allowed_file_types = ["rar"]
with self.assertRaises(HTTPException) as error:
validate_file_type("payload.exe", "application/octet-stream")
self.assertEqual(error.exception.status_code, 403)
+34
View File
@@ -0,0 +1,34 @@
import asyncio
import unittest
import apps.base.views as views
from apps.base.views import normalize_share_code
class FakeFileCodes:
seen_code = None
@classmethod
def filter(cls, **kwargs):
cls.seen_code = kwargs.get("code")
return cls()
async def first(self):
return None
class RetrieveCodeTests(unittest.TestCase):
def test_normalize_share_code_strips_surrounding_whitespace(self):
self.assertEqual(normalize_share_code(" 12345\n"), "12345")
def test_get_code_file_by_code_queries_normalized_code(self):
original_file_codes = views.FileCodes
views.FileCodes = FakeFileCodes
try:
has_file, message = asyncio.run(views.get_code_file_by_code(" 12345\n"))
finally:
views.FileCodes = original_file_codes
self.assertFalse(has_file)
self.assertEqual(message, "文件不存在")
self.assertEqual(FakeFileCodes.seen_code, "12345")
+79
View File
@@ -0,0 +1,79 @@
import asyncio
import unittest
from types import SimpleNamespace
from fastapi import HTTPException
from core.settings import BASE_DIR, settings
from main import index, resolve_theme_file, theme_asset
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
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):
def get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
return assets[0].name
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
def test_resolves_assets_from_current_theme(self):
settings.themesSelect = "themes/2023"
theme_2023_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2023")
)
settings.themesSelect = "themes/2024"
theme_2024_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2024")
)
self.assertIn("themes/2023/assets", str(theme_2023_asset))
self.assertIn("themes/2024/assets", str(theme_2024_asset))
def test_rejects_theme_asset_path_traversal(self):
settings.themesSelect = "themes/2024"
with self.assertRaises(HTTPException) as error:
resolve_theme_file("assets", "..", "..", "core", "settings.py")
self.assertEqual(error.exception.status_code, 404)
def test_theme_asset_returns_404_for_missing_or_traversal_paths(self):
settings.themesSelect = "themes/2023"
for asset_path in ("missing.js", "../../core/settings.py"):
with self.subTest(asset_path=asset_path):
with self.assertRaises(HTTPException) as error:
asyncio.run(theme_asset(asset_path))
self.assertEqual(error.exception.status_code, 404)
response = asyncio.run(
index(
request=SimpleNamespace(
url=SimpleNamespace(path="/theme-assets/missing.js")
)
)
)
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):
settings.themesSelect = "themes/2023"
response = asyncio.run(index())
html = response.body.decode("utf-8")
self.assertIn('src="/theme-assets/', html)
self.assertIn('href="/theme-assets/', html)
self.assertNotIn('src="/assets/', html)
self.assertNotIn('href="/assets/', html)
+46
View File
@@ -0,0 +1,46 @@
import asyncio
import unittest
from core.storage import S3FileStorage
class FakeS3Client:
def __init__(self, list_response):
self.list_response = list_response
self.head_calls = 0
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, traceback):
return False
async def head_object(self, **kwargs):
self.head_calls += 1
raise RuntimeError("head not supported")
async def list_objects_v2(self, **kwargs):
return self.list_response
class S3FileExistsTests(unittest.TestCase):
def test_file_exists_falls_back_to_list_objects(self):
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
storage = S3FileStorage.__new__(S3FileStorage)
storage.bucket_name = "bucket"
storage._client = lambda: client
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
self.assertTrue(exists)
self.assertEqual(client.head_calls, 3)
def test_file_exists_returns_false_when_missing(self):
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
storage = S3FileStorage.__new__(S3FileStorage)
storage.bucket_name = "bucket"
storage._client = lambda: client
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
self.assertFalse(exists)
+26
View File
@@ -0,0 +1,26 @@
import unittest
from core.settings import settings
from main import build_public_config, build_public_meta
class AdminAddressPublicConfigTests(unittest.TestCase):
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
def test_admin_address_is_exposed_as_strict_binary_flag(self):
cases = ((0, 0), (1, 1), ("0", 0), ("1", 1))
for configured_value, expected_value in cases:
with self.subTest(configured_value=configured_value):
settings.showAdminAddr = configured_value
public_value = build_public_config()["show_admin_address"]
feature_value = build_public_meta()["features"]["adminAddressVisible"]
self.assertIs(type(public_value), int)
self.assertEqual(public_value, expected_value)
self.assertIs(feature_value, bool(expected_value))
+218
View File
@@ -0,0 +1,218 @@
import asyncio
import datetime
import unittest
from unittest.mock import patch
from tortoise import Tortoise
from apps.base.models import FileCodes
from apps.base import views
from core.settings import DEFAULT_CONFIG, settings
from core.utils import get_now, get_select_token
from main import build_setup_page, parse_setup_options
class FakeStorage:
direct_url_calls = 0
async def get_file_url(self, file_code):
self.direct_url_calls += 1
return "https://storage.example/reusable-url"
async def get_file_response(self, file_code):
return {"downloaded": file_code.code}
class FakeRateLimit:
def __init__(self):
self.seen_ips = []
def add_ip(self, ip):
self.seen_ips.append(ip)
class ShareUsageSecurityTests(unittest.TestCase):
def test_new_installations_default_to_secret_codes(self):
self.assertEqual(DEFAULT_CONFIG["code_generate_type"], "secret")
self.assertEqual(
parse_setup_options({"expireStyle": ["day"]})["code_generate_type"],
"secret",
)
self.assertIn('<option value="secret" selected>', build_setup_page())
def test_atomic_usage_download_and_metadata_limits(self):
asyncio.run(self._run_scenario())
async def _run_scenario(self):
original_config = dict(settings.user_config)
original_metadata_limit = views.ip_limit["metadata"]
settings.file_storage = "local"
settings.jwt_secret = "test-download-secret"
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await self._assert_count_consumption_is_atomic()
await self._assert_time_expiration_and_usage_are_atomic()
await self._assert_download_url_is_single_use()
await self._assert_text_share_downloads_as_txt()
await self._assert_limited_files_do_not_expose_direct_urls()
await self._assert_metadata_counts_all_attempts()
finally:
views.ip_limit["metadata"] = original_metadata_limit
settings.user_config = original_config
await Tortoise.close_connections()
async def _assert_count_consumption_is_atomic(self):
record = await FileCodes.create(
code="atomic",
prefix="atomic",
suffix=".txt",
expired_count=1,
expired_at=await get_now() + datetime.timedelta(days=1),
)
stale_copies = await asyncio.gather(
*(FileCodes.get(id=record.id) for _ in range(20))
)
consumed = await asyncio.gather(
*(views.consume_file_usage(item) for item in stale_copies)
)
await record.refresh_from_db()
self.assertEqual(sum(consumed), 1)
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_time_expiration_and_usage_are_atomic(self):
valid = await FileCodes.create(
code="time-valid",
text="valid",
expired_count=-1,
expired_at=await get_now() + datetime.timedelta(minutes=5),
)
expired = await FileCodes.create(
code="time-expired",
text="expired",
expired_count=-1,
expired_at=await get_now() - datetime.timedelta(seconds=1),
)
valid_copies = await asyncio.gather(
*(FileCodes.get(id=valid.id) for _ in range(20))
)
consumed = await asyncio.gather(
*(views.consume_file_usage(item) for item in valid_copies)
)
self.assertTrue(all(consumed))
self.assertFalse(await views.consume_file_usage(expired))
await valid.refresh_from_db()
await expired.refresh_from_db()
self.assertEqual(valid.expired_count, -1)
self.assertEqual(valid.used_count, 20)
self.assertEqual(expired.used_count, 0)
async def _assert_download_url_is_single_use(self):
record = await FileCodes.create(
code="single-use",
prefix="report",
suffix=".pdf",
expired_count=1,
expired_at=await get_now() + datetime.timedelta(days=1),
)
key = await get_select_token(record.code)
with patch.dict(views.storages, {"local": FakeStorage}):
selected = await views.select_file(
data=views.SelectFileModel(code=record.code), ip="127.0.0.1"
)
await record.refresh_from_db()
self.assertEqual(selected.detail["expired_count"], 1)
self.assertEqual(record.expired_count, 1)
self.assertEqual(record.used_count, 0)
first = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
second = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
self.assertEqual(first, {"downloaded": record.code})
self.assertEqual(second.code, 404)
await record.refresh_from_db()
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_text_share_downloads_as_txt(self):
record = await FileCodes.create(
code="text-download",
prefix="TAG",
text="hello, 文本直链",
expired_count=-1,
expired_at=None,
)
with patch.dict(views.storages, {"local": FakeStorage}):
response = await views.get_code_file(
code=record.code, ip="127.0.0.1"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.body.decode("utf-8"), record.text)
self.assertEqual(response.media_type, "text/plain")
self.assertEqual(
response.headers["content-disposition"],
"attachment; filename*=UTF-8''TAG.txt",
)
await record.refresh_from_db()
self.assertEqual(record.used_count, 1)
async def _assert_limited_files_do_not_expose_direct_urls(self):
record = await FileCodes.create(
code="proxy-only",
prefix="archive",
suffix=".zip",
expired_count=2,
expired_at=await get_now() + datetime.timedelta(days=1),
)
storage = FakeStorage()
detail = await views.build_select_detail(record, storage)
self.assertTrue(detail["download_url"].startswith("/share/download?"))
self.assertEqual(storage.direct_url_calls, 0)
async def _assert_metadata_counts_all_attempts(self):
await FileCodes.create(
code="metadata",
text="hello",
expired_count=-1,
expired_at=None,
)
limiter = FakeRateLimit()
views.ip_limit["metadata"] = limiter
success = await views.get_file_metadata(code="metadata", ip="192.0.2.1")
missing = await views.get_file_metadata(code="missing", ip="192.0.2.1")
self.assertEqual(success.code, 200)
self.assertEqual(missing.code, 404)
self.assertEqual(limiter.seen_ips, ["192.0.2.1", "192.0.2.1"])
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
import asyncio
import unittest
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base.models import FileCodes, StorageReservation
from apps.base.quota import get_storage_usage, release_storage, reserve_storage
from core.settings import settings
from core.utils import get_now
class StorageQuotaTests(unittest.TestCase):
def test_quota_reservations_are_atomic_and_reusable(self):
asyncio.run(self._run_scenario())
async def _run_scenario(self):
original_config = dict(settings.user_config)
settings.storageLimit = 100
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await FileCodes.create(code="existing", size=60, expired_count=-1)
results = await asyncio.gather(
reserve_storage("upload-a", 30, 300),
reserve_storage("upload-b", 30, 300),
return_exceptions=True,
)
self.assertEqual(sum(result is None for result in results), 1)
rejected = [result for result in results if isinstance(result, HTTPException)]
self.assertEqual(len(rejected), 1)
self.assertEqual(rejected[0].status_code, 507)
usage = await get_storage_usage()
self.assertEqual(usage["used"], 60)
self.assertEqual(usage["reserved"], 30)
self.assertEqual(usage["available"], 10)
active = await StorageReservation.first()
await release_storage(active.token)
await reserve_storage("upload-c", 40, 300)
self.assertEqual((await get_storage_usage())["available"], 0)
settings.storageLimit = 0
await reserve_storage("unlimited", 10_000, 300)
self.assertFalse(
await StorageReservation.filter(token="unlimited").exists()
)
settings.storageLimit = 100
expired = await StorageReservation.get(token="upload-c")
expired.expires_at = await get_now()
await expired.save(update_fields=["expires_at"])
await reserve_storage("upload-d", 40, 300)
self.assertEqual((await get_storage_usage())["reserved"], 40)
await release_storage("upload-d")
same_token_results = await asyncio.gather(
*(reserve_storage("same-upload", 40, 300) for _ in range(10)),
return_exceptions=True,
)
self.assertTrue(all(result is None for result in same_token_results))
self.assertEqual(
await StorageReservation.filter(token="same-upload").count(), 1
)
finally:
settings.user_config = original_config
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
+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()
+60
View File
@@ -0,0 +1,60 @@
import importlib
import logging
import os
import unittest
from pathlib import Path
from unittest.mock import patch
import core.logger as logger_module
class LoggingConfigurationTests(unittest.TestCase):
def setUp(self):
self.environment_patch = None
def tearDown(self):
if self.environment_patch is not None:
self.environment_patch.stop()
importlib.reload(logger_module)
def reload_with_environment(self, values):
self.environment_patch = patch.dict(os.environ, values, clear=True)
self.environment_patch.start()
return importlib.reload(logger_module)
def test_production_defaults_to_warning_and_disables_access_logs(self):
module = self.reload_with_environment({"APP_ENV": "production"})
self.assertEqual(module.get_log_level_name(), "warning")
self.assertEqual(module.logger.level, logging.WARNING)
self.assertFalse(module.is_access_log_enabled())
def test_development_defaults_to_info_and_keeps_access_logs(self):
module = self.reload_with_environment({"APP_ENV": "development"})
self.assertEqual(module.get_log_level_name(), "info")
self.assertEqual(module.logger.level, logging.INFO)
self.assertTrue(module.is_access_log_enabled())
def test_explicit_log_and_access_settings_override_environment_defaults(self):
module = self.reload_with_environment(
{"APP_ENV": "production", "LOG_LEVEL": "error", "ACCESS_LOG": "true"}
)
self.assertEqual(module.get_log_level_name(), "error")
self.assertEqual(module.logger.level, logging.ERROR)
self.assertTrue(module.is_access_log_enabled())
def test_log_file_configuration_is_bounded_in_docker_compose(self):
compose = Path("docker-compose.yml").read_text(encoding="utf-8")
dockerfile = Path("Dockerfile").read_text(encoding="utf-8")
self.assertIn('max-size: "10m"', compose)
self.assertIn('max-file: "3"', compose)
self.assertIn('APP_ENV="production"', dockerfile)
self.assertIn('LOG_LEVEL="warning"', dockerfile)
self.assertIn("--no-access-log", dockerfile)
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())
+141
View File
@@ -0,0 +1,141 @@
import asyncio
import hashlib
import time
import unittest
from unittest.mock import patch
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base import views
from apps.base.models import FileCodes
from apps.base.quota import _detect_sql_dialect, _sql_placeholders, reserve_storage
from apps.base.utils import validate_expire_style
from core.settings import settings
from core.utils import get_select_token
class FakeStorage:
async def get_file_url(self, file_code):
return f"https://example.invalid/{file_code.code}"
async def get_file_response(self, file_code):
return {"downloaded": file_code.code}
class SecurityPatchTests(unittest.TestCase):
def test_validate_expire_style_rejects_unknown_mode(self):
original = dict(settings.user_config)
try:
settings.expireStyle = ["day", "count"]
self.assertEqual(validate_expire_style("day"), "day")
with self.assertRaises(HTTPException) as ctx:
validate_expire_style("forever")
self.assertEqual(ctx.exception.status_code, 400)
finally:
settings.user_config = original
def test_sql_placeholders_follow_dialect(self):
asyncio.run(self._assert_sql_placeholders())
async def _assert_sql_placeholders(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",
}
)
try:
self.assertEqual(_detect_sql_dialect(), "sqlite")
self.assertEqual(_sql_placeholders(3), ["?", "?", "?"])
with patch(
"apps.base.quota._detect_sql_dialect", return_value="postgres"
):
self.assertEqual(_sql_placeholders(3), ["$1", "$2", "$3"])
with patch("apps.base.quota._detect_sql_dialect", return_value="mysql"):
self.assertEqual(_sql_placeholders(2), ["%s", "%s"])
# sqlite 下 reserve_storage 仍可正常工作
settings.storageLimit = 100
await Tortoise.generate_schemas()
await reserve_storage("patch-token", 10, 300)
finally:
settings.storageLimit = 0
await Tortoise.close_connections()
def test_download_token_accepts_previous_window(self):
asyncio.run(self._assert_download_token_window())
async def _assert_download_token_window(self):
original = dict(settings.user_config)
settings.jwt_secret = "test-secret-key-for-token-window"
now = 2_000_500 # 落在窗口 2000 内
code = "ABCDE"
with patch("core.utils.time.time", return_value=now):
current = await get_select_token(code, offset=0)
previous = await get_select_token(code, offset=1)
expected_current = hashlib.sha256(
f"{code}{int(now / 1000)}000{settings.jwt_secret}".encode()
).hexdigest()
expected_previous = hashlib.sha256(
f"{code}{int(now / 1000) - 1}000{settings.jwt_secret}".encode()
).hexdigest()
self.assertEqual(current, expected_current)
self.assertEqual(previous, expected_previous)
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await FileCodes.create(
code=code,
prefix="demo",
suffix=".txt",
expired_count=-1,
size=1,
)
# 模拟请求进入下一窗口,但仍携带上一窗口 token
next_window = now + 1000
with patch("core.utils.time.time", return_value=next_window):
with patch.dict(views.storages, {"local": FakeStorage}):
result = await views.download_file(
key=current, code=code, ip="127.0.0.1"
)
self.assertEqual(result, {"downloaded": code})
finally:
settings.user_config = original
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -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())
original_refresh = __import__("apps.admin.services", fromlist=["refresh_settings"]).refresh_settings
async def fake_refresh():
async def fake_refresh(**kwargs):
return None
module = __import__("apps.admin.services", fromlist=["refresh_settings"])
module.refresh_settings = fake_refresh
+106
View File
@@ -0,0 +1,106 @@
from unittest.mock import AsyncMock, patch
import asyncio
import unittest
from pathlib import Path
from fastapi import HTTPException
from apps.admin import views as admin_views
from apps.admin.schemas import LoginData
from apps.base.dependencies import IPRateLimit
from apps.base.file_validation import detect_file_kind, validate_file_magic, validate_file_type
from apps.base.utils import ip_limit
from core.settings import settings
from core.utils import hash_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
def test_detects_common_signatures(self):
self.assertEqual(detect_file_kind(b"\x89PNG\r\n\x1a\nxxxx").name, "png")
self.assertEqual(detect_file_kind(b"\xff\xd8\xff\xe0xxxx").name, "jpg")
self.assertEqual(detect_file_kind(b"%PDF-1.7").name, "pdf")
self.assertEqual(detect_file_kind(b"PK\x03\x04xxxx").name, "zip")
self.assertEqual(detect_file_kind(b"RIFF\x00\x00\x00\x00WEBPxxxx").name, "webp")
self.assertEqual(detect_file_kind(b"\x00\x00\x00\x18ftypmp42").name, "mp4")
def test_rejects_extension_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("photo.png", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
self.assertIn("扩展名", ctx.exception.detail)
def test_rejects_content_type_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("blob.bin", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
def test_accepts_matching_png(self):
settings.allowed_file_types = [".png", "image/*"]
validate_file_magic("a.png", "image/png", b"\x89PNG\r\n\x1a\nxxxx")
def test_whitelist_still_enforced(self):
settings.allowed_file_types = [".png"]
with self.assertRaises(HTTPException):
validate_file_type("a.exe", "application/x-msdownload")
class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
settings.admin_token = hash_password("correct-password-123")
settings.jwt_secret = "j" * 48
settings.loginCount = 3
settings.loginMinute = 15
self._original_login_limiter = ip_limit["login"]
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
def tearDown(self):
ip_limit["login"] = self._original_login_limiter
super().tearDown()
@patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_failed_logins_are_rate_limited(self, refresh):
async def attempt(password: str):
return await admin_views.login(
data=LoginData(password=password), ip="203.0.113.10"
)
for _ in range(3):
with self.assertRaises(HTTPException) as ctx:
asyncio.run(attempt("wrong-password"))
self.assertEqual(ctx.exception.status_code, 401)
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
@patch("apps.admin.views.refresh_settings", new_callable=AsyncMock)
def test_successful_login_does_not_consume_failure_quota(self, refresh):
result = asyncio.run(
admin_views.login(
data=LoginData(password="correct-password-123"), ip="198.51.100.8"
)
)
self.assertIn("token", result.detail)
self.assertTrue(ip_limit["login"].check_ip("198.51.100.8"))
class DockerRuntimeUserTests(unittest.TestCase):
def test_dockerfile_defaults_to_root_for_volume_compatibility(self):
# 默认 root:兼容已有 data 卷权限;如需非 root 可由编排层自行指定 user
text = Path("Dockerfile").read_text()
self.assertNotIn("USER appuser", text)
compose = Path("docker-compose.yml").read_text()
self.assertNotIn('user: "1000:1000"', compose)
if __name__ == "__main__":
unittest.main()
+222
View File
@@ -0,0 +1,222 @@
import asyncio
from io import BytesIO
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from fastapi import HTTPException
from starlette.datastructures import UploadFile
from tortoise import Tortoise
from apps.base import views
from apps.admin import dependencies as admin_dependencies
from apps.admin.dependencies import create_token, verify_token
from apps.admin.services import LocalFileClass
from apps.base.models import FileCodes, UploadChunk
from apps.base.schemas import CompleteUploadModel, InitChunkUploadModel
from apps.base.utils import get_chunk_file_path_name
from core.settings import data_root, settings
from core.storage import SystemFileStorage
from core.utils import hash_password, verify_password
class PasswordCompareTests(unittest.TestCase):
def test_verify_password_accepts_valid_hash(self):
hashed = hash_password("s3cret-pass")
self.assertTrue(verify_password("s3cret-pass", hashed))
self.assertFalse(verify_password("wrong-pass", hashed))
def test_verify_password_supports_legacy_plaintext(self):
self.assertTrue(verify_password("legacy", "legacy"))
self.assertFalse(verify_password("legacy", "other"))
class LocalFilePathTraversalTests(unittest.TestCase):
def setUp(self):
self._tmpdir = tempfile.TemporaryDirectory()
self.local_root = Path(self._tmpdir.name) / "local"
self.local_root.mkdir(parents=True, exist_ok=True)
(self.local_root / "safe.txt").write_text("ok", encoding="utf-8")
self._data_root_patch = patch(
"core.settings.data_root", Path(self._tmpdir.name)
)
self._data_root_patch.start()
def tearDown(self):
self._data_root_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_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.local_root / "safe.txt").resolve())
class SystemStoragePathTests(unittest.TestCase):
def setUp(self):
self._tmpdir = tempfile.TemporaryDirectory()
self.storage = SystemFileStorage()
self.storage.root_path = Path(self._tmpdir.name)
def tearDown(self):
self._tmpdir.cleanup()
def test_resolve_safe_path_blocks_escape(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("../etc/passwd")
def test_resolve_safe_path_blocks_internal_dotdot(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("share/data/2026/08/29/x/../../../../../../filecodebox.db")
def test_resolve_safe_path_blocks_windows_dotdot(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("share\\data\\..\\..\\filecodebox.db")
def test_resolve_safe_path_allows_nested(self):
target = self.storage._resolve_safe_path("share/data/a/b.txt")
self.assertTrue(str(target).startswith(str(Path(self._tmpdir.name).resolve())))
class ChunkFileNameSanitizeTests(unittest.TestCase):
def test_chunk_file_path_name_strips_traversal(self):
path, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("../../../../../../filecodebox.db", "a" * 32)
)
self.assertNotIn("..", save_path)
self.assertEqual(filename, "filecodebox.db")
self.assertEqual(save_path, f"{path}/filecodebox.db")
self.assertIn("a" * 32, path)
def test_chunk_file_path_name_strips_windows_traversal(self):
_, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("..\\..\\..\\..\\..\\..\\evil.bin", "b" * 32)
)
self.assertNotIn("..", save_path)
self.assertEqual(filename, "evil.bin")
def test_chunk_file_path_name_keeps_normal_name(self):
_, _, _, filename, save_path = asyncio.run(
get_chunk_file_path_name("safe.txt", "c" * 32)
)
self.assertEqual(filename, "safe.txt")
self.assertTrue(save_path.endswith("/safe.txt"))
class ChunkUploadMetadataTests(unittest.TestCase):
def test_traversal_filename_remains_downloadable_after_completion(self):
asyncio.run(self._run_traversal_upload())
async def _run_traversal_upload(self):
original_config = dict(settings.user_config)
tmpdir = tempfile.TemporaryDirectory()
try:
settings.file_storage = "local"
settings.allowed_file_types = ["*"]
with patch("core.storage.data_root", Path(tmpdir.name)):
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
raw_name = "../../../../../../filecodebox.db"
payload = b"chunk payload"
init_result = await views.init_chunk_upload(
InitChunkUploadModel(
file_name=raw_name,
file_size=len(payload),
chunk_size=1024,
file_hash="f" * 64,
)
)
upload_id = init_result.detail["upload_id"]
session = await UploadChunk.get(
upload_id=upload_id, chunk_index=-1
)
self.assertEqual(session.file_name, "filecodebox.db")
self.assertNotIn("..", session.save_path)
await views.upload_chunk(
upload_id=upload_id,
chunk_index=0,
chunk=UploadFile(
file=BytesIO(payload), filename="filecodebox.db"
),
)
# Simulate a legacy session whose display name was not sanitized.
session.file_name = raw_name
await session.save(update_fields=["file_name"])
complete_result = await views.complete_upload(
upload_id=upload_id,
data=CompleteUploadModel(
expire_value=1, expire_style="day"
),
ip="127.0.0.1",
)
self.assertEqual(complete_result.detail["name"], "filecodebox.db")
file_code = await FileCodes.get(code=complete_result.detail["code"])
expected_relative_path = session.save_path
self.assertEqual(
await file_code.get_file_path(), expected_relative_path
)
storage = views.storages[settings.file_storage]()
resolved_path = storage._resolve_safe_path(
await file_code.get_file_path()
)
self.assertEqual(
resolved_path, Path(tmpdir.name).resolve() / expected_relative_path
)
self.assertEqual(resolved_path.read_bytes(), payload)
finally:
await Tortoise.close_connections()
finally:
settings.user_config = original_config
tmpdir.cleanup()
class AdminJwtUrlSafeTests(unittest.TestCase):
def setUp(self):
settings.jwt_secret = "j" * 48
def test_create_and_verify_roundtrip(self):
token = create_token({"is_admin": True}, expires_in=60)
# urlsafe token 不应依赖标准 base64 填充字符
self.assertNotIn("+", token)
self.assertNotIn("/", token)
payload = verify_token(token)
self.assertTrue(payload["is_admin"])
if __name__ == "__main__":
unittest.main()
+44
View File
@@ -0,0 +1,44 @@
import asyncio
import unittest
from unittest.mock import AsyncMock, patch
from tortoise import Tortoise
from apps.admin.services import FileService
from apps.base.models import FileCodes, ShareCodeReservations
class ShareCodeReservationTests(unittest.TestCase):
def test_restore_keeps_original_code_and_releases_own_reservation(self):
asyncio.run(self.scenario())
async def scenario(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()
try:
item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text")
service = FileService()
await ShareCodeReservations.create(code="OLD_CODE", file_code_id=item.id, reason="restored")
restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, "OLD_CODE")
self.assertFalse(await ShareCodeReservations.filter(code="OLD_CODE").exists())
# 模拟管理员手工改码:被替换的旧码也必须永久封存。
await ShareCodeReservations.get_or_create(
code="MANUALOLD",
defaults={"file_code_id": item.id, "reason": "manual_update"},
)
self.assertTrue(await ShareCodeReservations.filter(code="MANUALOLD").exists())
finally:
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
+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)
+40
View File
@@ -0,0 +1,40 @@
import json
import os
import unittest
from unittest.mock import patch
from core.version import APP_VERSION, VERSION_FILE, load_app_version
from main import app
class ApplicationVersionTests(unittest.TestCase):
def test_version_file_is_the_runtime_version_source(self):
version = VERSION_FILE.read_text(encoding="utf-8").strip()
self.assertRegex(version, r"^\d+\.\d+\.\d+$")
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(load_app_version(), version)
self.assertEqual(app.version, APP_VERSION)
def test_release_manifest_matches_version_file(self):
manifest_file = VERSION_FILE.parent / ".release-please-manifest.json"
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
self.assertEqual(manifest["."], VERSION_FILE.read_text(encoding="utf-8").strip())
def test_build_can_override_version_with_environment(self):
for version in ("9.8.7", "9.8.7-dev+abc123"):
with self.subTest(version=version):
with patch.dict(os.environ, {"APP_VERSION": version}):
self.assertEqual(load_app_version(), version)
def test_rejects_non_canonical_versions(self):
for version in ("v2.4.0", "2.4", "2.4.0 beta"):
with self.subTest(version=version):
with patch.dict(os.environ, {"APP_VERSION": version}):
with self.assertRaises(RuntimeError):
load_app_version()
if __name__ == "__main__":
unittest.main()