From 9e9571b031915cb8c06c2c6ff51b54033b5350c1 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 10:08:42 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=95=B4=E5=90=88=E5=AE=98=E6=96=B9=20?= =?UTF-8?q?2.7.0=20=E5=AE=89=E5=85=A8=E4=BF=AE=E5=A4=8D=E4=B8=8E=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=E6=96=87=E4=BB=B6=E5=88=86=E4=BA=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 12 + .gitignore | 8 + .release-please-manifest.json | 3 + Dockerfile.upgrade | 15 + UPGRADE.md | 67 ++++ VERSION | 2 +- apps/admin/services.py | 466 +++++++++++++----------- apps/admin/views.py | 55 ++- apps/base/local_share.py | 105 ++++++ apps/base/models.py | 2 +- apps/base/quota.py | 27 +- apps/base/views.py | 7 +- core/config.py | 16 +- core/security.py | 2 + core/utils.py | 78 +++- docker-compose.yml | 22 ++ main.py | 2 +- package-lock.json | 4 +- package.json | 2 +- tests/__init__.py | 0 tests/helpers.py | 55 +++ tests/test_admin_security.py | 279 ++++++++++++++ tests/test_background_url_validation.py | 135 +++++++ tests/test_issue_461_s3_addressing.py | 33 ++ tests/test_issue_464_admin_file_list.py | 65 ++++ tests/test_issue_465_file_type.py | 31 ++ tests/test_issue_473_retrieve_code.py | 34 ++ tests/test_issue_476_theme_assets.py | 79 ++++ tests/test_issue_478_s3_file_exists.py | 46 +++ tests/test_issue_480_admin_address.py | 26 ++ tests/test_issue_482_share_usage.py | 218 +++++++++++ tests/test_issue_486_storage_quota.py | 91 +++++ tests/test_local_share.py | 207 +++++++++++ tests/test_logging.py | 60 +++ tests/test_password_hashing.py | 152 ++++++++ tests/test_pr494_security_patches.py | 141 +++++++ tests/test_recycle_bin.py | 2 +- tests/test_security_gaps.py | 106 ++++++ tests/test_security_hardening.py | 222 +++++++++++ tests/test_share_code_reservations.py | 44 +++ tests/test_upgrade_270.py | 131 +++++++ tests/test_version.py | 40 ++ 42 files changed, 2824 insertions(+), 268 deletions(-) create mode 100644 .dockerignore create mode 100644 .release-please-manifest.json create mode 100644 Dockerfile.upgrade create mode 100644 UPGRADE.md create mode 100644 apps/base/local_share.py create mode 100644 docker-compose.yml create mode 100644 tests/__init__.py create mode 100644 tests/helpers.py create mode 100644 tests/test_admin_security.py create mode 100644 tests/test_background_url_validation.py create mode 100644 tests/test_issue_461_s3_addressing.py create mode 100644 tests/test_issue_464_admin_file_list.py create mode 100644 tests/test_issue_465_file_type.py create mode 100644 tests/test_issue_473_retrieve_code.py create mode 100644 tests/test_issue_476_theme_assets.py create mode 100644 tests/test_issue_478_s3_file_exists.py create mode 100644 tests/test_issue_480_admin_address.py create mode 100644 tests/test_issue_482_share_usage.py create mode 100644 tests/test_issue_486_storage_quota.py create mode 100644 tests/test_local_share.py create mode 100644 tests/test_logging.py create mode 100644 tests/test_password_hashing.py create mode 100644 tests/test_pr494_security_patches.py create mode 100644 tests/test_security_gaps.py create mode 100644 tests/test_security_hardening.py create mode 100644 tests/test_share_code_reservations.py create mode 100644 tests/test_upgrade_270.py create mode 100644 tests/test_version.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ebd73eb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git +.idea +node_modules +data +output +coverage +__pycache__ +**/__pycache__ +.pytest_cache +.coverage* +*.log +.env* diff --git a/.gitignore b/.gitignore index 2d29e0a..76def8b 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,11 @@ output *.sw? *.tsbuildinfo + +# Python verification artifacts +__pycache__/ +*.py[cod] +.coverage* +.pytest_cache/ + +/data/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..6ed9c80 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "2.7.0" +} diff --git a/Dockerfile.upgrade b/Dockerfile.upgrade new file mode 100644 index 0000000..6f3904c --- /dev/null +++ b/Dockerfile.upgrade @@ -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}" diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000..3a4b14d --- /dev/null +++ b/UPGRADE.md @@ -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 需要跨进程并发控制后再启用。 diff --git a/VERSION b/VERSION index da6b0a8..24ba9a3 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.5.6 +2.7.0 diff --git a/apps/admin/services.py b/apps/admin/services.py index 58e0b79..8acf711 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -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() diff --git a/apps/admin/views.py b/apps/admin/views.py index 2caa3ae..77ea154 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -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) diff --git a/apps/base/local_share.py b/apps/base/local_share.py new file mode 100644 index 0000000..8e67bc8 --- /dev/null +++ b/apps/base/local_share.py @@ -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) diff --git a/apps/base/models.py b/apps/base/models.py index 11f75c9..ddec8d5 100644 --- a/apps/base/models.py +++ b/apps/base/models.py @@ -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) diff --git a/apps/base/quota.py b/apps/base/quota.py index 2e673dd..159a260 100644 --- a/apps/base/quota.py +++ b/apps/base/quota.py @@ -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]} diff --git a/apps/base/views.py b/apps/base/views.py index f5c1b3f..4c76157 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -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)) ) diff --git a/core/config.py b/core/config.py index c7fe873..07d49c2 100644 --- a/core/config.py +++ b/core/config.py @@ -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) diff --git a/core/security.py b/core/security.py index 7625287..4b966fa 100644 --- a/core/security.py +++ b/core/security.py @@ -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) diff --git a/core/utils.py b/core/utils.py index 8d5c916..66a5259 100644 --- a/core/utils.py +++ b/core/utils.py @@ -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$$ + 使用 scrypt(memory-hard)哈希密码 + 返回格式: scrypt$$$

$$ """ 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: """ 安全处理文件名: diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..57b5a51 --- /dev/null +++ b/docker-compose.yml @@ -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 diff --git a/main.py b/main.py index d493a72..1a2ec26 100644 --- a/main.py +++ b/main.py @@ -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 diff --git a/package-lock.json b/package-lock.json index 66d3ebe..1c691da 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index ea88377..360e51b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "filecodeboxfronted", - "version": "0.0.0", + "version": "2.7.0", "private": true, "type": "module", "scripts": { diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..b2d912d --- /dev/null +++ b/tests/helpers.py @@ -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() diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py new file mode 100644 index 0000000..afb997b --- /dev/null +++ b/tests/test_admin_security.py @@ -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"]) diff --git a/tests/test_background_url_validation.py b/tests/test_background_url_validation.py new file mode 100644 index 0000000..b29eb27 --- /dev/null +++ b/tests/test_background_url_validation.py @@ -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() diff --git a/tests/test_issue_461_s3_addressing.py b/tests/test_issue_461_s3_addressing.py new file mode 100644 index 0000000..9ff6ecd --- /dev/null +++ b/tests/test_issue_461_s3_addressing.py @@ -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) diff --git a/tests/test_issue_464_admin_file_list.py b/tests/test_issue_464_admin_file_list.py new file mode 100644 index 0000000..38d21c9 --- /dev/null +++ b/tests/test_issue_464_admin_file_list.py @@ -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"]) diff --git a/tests/test_issue_465_file_type.py b/tests/test_issue_465_file_type.py new file mode 100644 index 0000000..d2bee8d --- /dev/null +++ b/tests/test_issue_465_file_type.py @@ -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) diff --git a/tests/test_issue_473_retrieve_code.py b/tests/test_issue_473_retrieve_code.py new file mode 100644 index 0000000..cdc9086 --- /dev/null +++ b/tests/test_issue_473_retrieve_code.py @@ -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") diff --git a/tests/test_issue_476_theme_assets.py b/tests/test_issue_476_theme_assets.py new file mode 100644 index 0000000..57dd498 --- /dev/null +++ b/tests/test_issue_476_theme_assets.py @@ -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) diff --git a/tests/test_issue_478_s3_file_exists.py b/tests/test_issue_478_s3_file_exists.py new file mode 100644 index 0000000..5f1d214 --- /dev/null +++ b/tests/test_issue_478_s3_file_exists.py @@ -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) diff --git a/tests/test_issue_480_admin_address.py b/tests/test_issue_480_admin_address.py new file mode 100644 index 0000000..8ff9da5 --- /dev/null +++ b/tests/test_issue_480_admin_address.py @@ -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)) diff --git a/tests/test_issue_482_share_usage.py b/tests/test_issue_482_share_usage.py new file mode 100644 index 0000000..f2ca237 --- /dev/null +++ b/tests/test_issue_482_share_usage.py @@ -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('