From cdaf3638b80a12f0b22e620815653c7e065916f1 Mon Sep 17 00:00:00 2001 From: Lan Date: Tue, 16 Jun 2026 00:49:43 +0800 Subject: [PATCH] feat: add first-run setup security flow --- apps/admin/dependencies.py | 13 +- apps/admin/services.py | 18 +- core/config.py | 95 +++- core/security.py | 60 +++ core/settings.py | 3 +- core/utils.py | 4 +- core/version.py | 2 +- docs/api/index.md | 4 +- docs/en/api/index.md | 4 +- docs/en/guide/configuration.md | 4 +- docs/en/guide/getting-started.md | 5 +- docs/en/guide/management.md | 9 +- docs/en/guide/security.md | 6 +- docs/en/guide/upload.md | 2 +- docs/guide/configuration.md | 4 +- docs/guide/getting-started.md | 5 +- docs/guide/management.md | 11 +- docs/guide/security.md | 6 +- docs/guide/upload.md | 2 +- main.py | 690 ++++++++++++++++++++++++++- readme.md | 4 +- readme_en.md | 4 +- tests/test_admin_security.py | 221 +++++++++ tests/test_issue_476_theme_assets.py | 15 +- 24 files changed, 1127 insertions(+), 64 deletions(-) create mode 100644 core/security.py create mode 100644 tests/test_admin_security.py diff --git a/apps/admin/dependencies.py b/apps/admin/dependencies.py index e648628..2e8febc 100644 --- a/apps/admin/dependencies.py +++ b/apps/admin/dependencies.py @@ -12,6 +12,13 @@ from core.settings import settings from apps.admin.services import FileService, ConfigService, LocalFileService +def _get_jwt_secret() -> bytes: + secret = getattr(settings, "jwt_secret", "") + if not secret: + raise RuntimeError("JWT签名密钥未初始化") + return secret.encode() + + def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str: """ 创建JWT token @@ -25,9 +32,7 @@ def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str: json.dumps({**data, "exp": int(time.time()) + expires_in}).encode() ).decode() - signature = hmac.new( - settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256" - ).digest() + signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest() signature = base64.b64encode(signature).decode() return f"{header}.{payload}.{signature}" @@ -44,7 +49,7 @@ def verify_token(token: str) -> dict: # 验证签名 expected_signature = hmac.new( - settings.admin_token.encode(), + _get_jwt_secret(), f"{header_b64}.{payload_b64}".encode(), "sha256", ).digest() diff --git a/apps/admin/services.py b/apps/admin/services.py index 3270e23..684e569 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -8,6 +8,7 @@ from core.response import APIResponse from core.storage import FileStorageInterface, storages from core.settings import settings from core.config import refresh_settings +from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret from apps.base.models import FileCodes, KeyValue from apps.base.utils import get_expire_info, get_file_path_name from fastapi import HTTPException @@ -1514,20 +1515,30 @@ class ConfigService: FLOAT_FIELDS = {"opacity"} def get_config(self): - return dict(settings.items()) + config = dict(settings.items()) + config["admin_token"] = "" + for key in INTERNAL_CONFIG_KEYS: + config.pop(key, None) + 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 + 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 for key, value in update_data.items(): if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS: @@ -1543,6 +1554,9 @@ class ConfigService: except (TypeError, ValueError): raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误") + 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() diff --git a/core/config.py b/core/config.py index a2dd349..fdc3e9b 100644 --- a/core/config.py +++ b/core/config.py @@ -1,10 +1,64 @@ from apps.base.models import KeyValue from apps.base.utils import ip_limit +from core.database import db_startup_lock +from core.logger import logger +from core.security import ( + generate_jwt_secret, + is_config_initialized, + is_valid_jwt_secret, + prepare_security_config, +) from core.settings import DEFAULT_CONFIG, settings +from core.utils import hash_password + + +MIN_ADMIN_PASSWORD_LENGTH = 8 +SETUP_CONFIG_FIELDS = { + "allowed_file_types", + "code_generate_type", + "enableChunk", + "errorCount", + "errorMinute", + "expireStyle", + "max_save_seconds", + "name", + "openUpload", + "uploadCount", + "uploadMinute", + "uploadSize", +} async def ensure_settings_row() -> None: - await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG}) + initial_security = prepare_security_config(DEFAULT_CONFIG) + _, created = await KeyValue.get_or_create( + key="settings", defaults={"value": initial_security.config} + ) + if created: + logger.warning( + "系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置" + ) + + +async def ensure_security_settings() -> None: + config_record = await KeyValue.filter(key="settings").first() + if not config_record: + return + + current_config = {**DEFAULT_CONFIG, **(config_record.value or {})} + security_config = prepare_security_config(current_config) + if not security_config.changed: + return + + config_record.value = security_config.config + await config_record.save() + if security_config.setup_required: + logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置") + elif security_config.password_hashed: + logger.info("已将管理员密码迁移为哈希存储") + if security_config.jwt_secret_rotated: + logger.info("已生成独立 JWT 签名密钥") + await refresh_settings() def _sync_ip_limits() -> None: @@ -19,3 +73,42 @@ async def refresh_settings() -> None: 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() + + +def is_runtime_initialized() -> bool: + return is_config_initialized(dict(settings.items())) + + +async def initialize_system( + admin_password: str, + site_name: str | None = None, + setup_options: dict | None = None, +) -> None: + password = str(admin_password or "").strip() + if len(password) < MIN_ADMIN_PASSWORD_LENGTH: + raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位") + + async with db_startup_lock(): + config_record = await KeyValue.filter(key="settings").first() + current_config = { + **DEFAULT_CONFIG, + **(config_record.value if config_record and config_record.value else {}), + } + if is_config_initialized(current_config): + raise ValueError("系统已经初始化,请直接登录后台") + + next_config = dict(current_config) + for key, value in (setup_options or {}).items(): + if key in SETUP_CONFIG_FIELDS: + next_config[key] = value + + normalized_site_name = str(site_name or "").strip() + if normalized_site_name: + next_config["name"] = normalized_site_name[:80] + + next_config["admin_token"] = hash_password(password) + if not is_valid_jwt_secret(next_config.get("jwt_secret")): + next_config["jwt_secret"] = generate_jwt_secret() + + await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) + await refresh_settings() diff --git a/core/security.py b/core/security.py new file mode 100644 index 0000000..7625287 --- /dev/null +++ b/core/security.py @@ -0,0 +1,60 @@ +import copy +import secrets +from dataclasses import dataclass +from typing import Any + +from core.utils import hash_password, is_password_hashed, verify_password + + +JWT_SECRET_MIN_LENGTH = 32 +INTERNAL_CONFIG_KEYS = {"jwt_secret"} +LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023" + + +@dataclass +class SecurityConfigResult: + config: dict[str, Any] + changed: bool = False + password_hashed: bool = False + jwt_secret_rotated: bool = False + setup_required: bool = False + + +def generate_jwt_secret() -> str: + return secrets.token_urlsafe(48) + + +def is_valid_jwt_secret(secret: Any) -> bool: + return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH + + +def is_config_initialized(config: dict[str, Any]) -> bool: + admin_token = str(config.get("admin_token") or "") + if not admin_token: + return False + return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token) + + +def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult: + next_config = copy.deepcopy(config) + result = SecurityConfigResult(config=next_config) + + admin_token = str(next_config.get("admin_token") or "") + if not admin_token: + result.setup_required = True + elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token): + next_config["admin_token"] = "" + result.setup_required = True + result.changed = True + elif not is_password_hashed(admin_token): + next_config["admin_token"] = hash_password(admin_token) + result.password_hashed = True + result.changed = True + + jwt_secret = next_config.get("jwt_secret") + if not is_valid_jwt_secret(jwt_secret): + next_config["jwt_secret"] = generate_jwt_secret() + result.jwt_secret_rotated = True + result.changed = True + + return result diff --git a/core/settings.py b/core/settings.py index 919dae1..40d7ba4 100644 --- a/core/settings.py +++ b/core/settings.py @@ -38,7 +38,8 @@ DEFAULT_CONFIG = { "onedrive_proxy": 0, "webdav_root_path": "filebox_storage", "webdav_proxy": 0, - "admin_token": "FileCodeBox2023", + "admin_token": "", + "jwt_secret": "", "openUpload": 1, "uploadSize": 1024 * 1024 * 10, "allowed_file_types": ["*"], diff --git a/core/utils.py b/core/utils.py index 6085fdb..a762f55 100644 --- a/core/utils.py +++ b/core/utils.py @@ -46,7 +46,9 @@ async def get_select_token(code: str): :param code: :return: """ - token = settings.admin_token + token = getattr(settings, "jwt_secret", "") + if not token: + raise RuntimeError("应用签名密钥未初始化") return hashlib.sha256( f"{code}{int(time.time() / 1000)}000{token}".encode() ).hexdigest() diff --git a/core/version.py b/core/version.py index 5599691..bb219e8 100644 --- a/core/version.py +++ b/core/version.py @@ -1 +1 @@ -APP_VERSION = "2.0.0-dev" +APP_VERSION = "2.4.0" diff --git a/docs/api/index.md b/docs/api/index.md index 2b2cac0..aefbde3 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -22,7 +22,7 @@ Authorization: Bearer ```bash curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": "<初始化时设置的管理员密码>"}' ``` **响应示例:** @@ -329,4 +329,4 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file - 403: 禁止访问 - 404: 资源不存在 - 422: 请求参数验证错误 -- 500: 服务器内部错误 \ No newline at end of file +- 500: 服务器内部错误 diff --git a/docs/en/api/index.md b/docs/en/api/index.md index 2addc64..1ec342f 100644 --- a/docs/en/api/index.md +++ b/docs/en/api/index.md @@ -22,7 +22,7 @@ When guest upload is disabled in admin panel (`openUpload=0`), you need to login ```bash curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": ""}' ``` **Response Example:** @@ -329,4 +329,4 @@ When an error occurs, the API will return corresponding error message: - 403: Forbidden - 404: Not Found - 422: Validation Error -- 500: Internal Server Error \ No newline at end of file +- 500: Internal Server Error diff --git a/docs/en/guide/configuration.md b/docs/en/guide/configuration.md index 89f6be3..db1c0f5 100644 --- a/docs/en/guide/configuration.md +++ b/docs/en/guide/configuration.md @@ -109,11 +109,11 @@ Default available themes: | Setting | Type | Default | Description | |---------|------|---------|-------------| -| `admin_token` | string | `FileCodeBox2023` | Admin login password | +| `admin_token` | string | Set during setup | Admin login password | | `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) | ::: danger Security Warning -Always change the default `admin_token` in production environments! Using the default password poses serious security risks. +The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet. ::: ## Security Settings diff --git a/docs/en/guide/getting-started.md b/docs/en/guide/getting-started.md index 0cb41c0..c0214e9 100644 --- a/docs/en/guide/getting-started.md +++ b/docs/en/guide/getting-started.md @@ -55,8 +55,9 @@ python main.py - Download file 4. Admin Panel + - Open `http://localhost:12345` on first run and complete setup - Visit `http://localhost:12345/#/admin` - - Enter admin password: `FileCodeBox2023` + - Enter the admin password set during setup - Enter admin panel - View system information, file list, user management, etc. @@ -64,4 +65,4 @@ python main.py - [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods - [Security Settings](/en/guide/security) - Learn how to enhance system security -- [API Documentation](/en/api/) - Learn how to integrate through API \ No newline at end of file +- [API Documentation](/en/api/) - Learn how to integrate through API diff --git a/docs/en/guide/management.md b/docs/en/guide/management.md index e22a65c..e7cbfb6 100644 --- a/docs/en/guide/management.md +++ b/docs/en/guide/management.md @@ -8,12 +8,13 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to The admin panel is located at the `/admin` path. Access method: -1. Visit `http://your-domain.com/admin` in your browser -2. Enter the admin password (the value of the `admin_token` configuration) -3. Click the login button +1. On first run, set the admin password on the setup page +2. Visit `http://your-domain.com/admin` in your browser +3. Enter the admin password (the value of the `admin_token` configuration) +4. Click the login button ::: tip Tip -The default admin password is `FileCodeBox2023`. Be sure to change this password in production environments. See [Security Settings](/en/guide/security) for details. +The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet. ::: ### Show Admin Entry diff --git a/docs/en/guide/security.md b/docs/en/guide/security.md index 3c74118..15a082b 100644 --- a/docs/en/guide/security.md +++ b/docs/en/guide/security.md @@ -4,10 +4,10 @@ FileCodeBox provides multiple layers of security mechanisms to protect your file ## Admin Password -### Change Default Password +### First-Run Setup ::: danger Important Security Warning -FileCodeBox's default admin password is `FileCodeBox2023`. **You must change this password immediately in production environments!** Using the default password allows anyone to access your admin panel. +FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page. ::: There are two ways to change the admin password: @@ -272,7 +272,7 @@ your-domain.com { Before deploying FileCodeBox, confirm the following security configurations: -- [ ] Changed default admin password `admin_token` +- [ ] Completed first-run setup and set the admin password `admin_token` - [ ] Hidden admin entry `showAdminAddr: 0` - [ ] Configured appropriate upload rate limiting - [ ] Configured error rate limiting to prevent brute-force attacks diff --git a/docs/en/guide/upload.md b/docs/en/guide/upload.md index 1dd9306..d8d0f88 100644 --- a/docs/en/guide/upload.md +++ b/docs/en/guide/upload.md @@ -149,7 +149,7 @@ If guest upload is disabled in admin panel (`openUpload=0`), you need to login f # 1. Login to get token curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": ""}' # Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}} diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index f32cd51..c4303f0 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -108,11 +108,11 @@ FileCodeBox 支持两种配置方式: | 配置项 | 类型 | 默认值 | 说明 | |--------|------|--------|------| -| `admin_token` | string | `FileCodeBox2023` | 管理员登录密码 | +| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) | | `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) | ::: danger 安全警告 -请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。 +未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。 ::: ## 安全设置 diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index b09d069..1852ed9 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -109,8 +109,9 @@ python main.py - 下载文件 4. 后台管理 + - 首次访问 `http://localhost:12345` 完成初始化 - 访问 `http://localhost:12345/#/admin` - - 输入管理员密码:`FileCodeBox2023` + - 输入初始化时设置的管理员密码 - 进入后台管理页面 - 查看系统信息、文件列表、用户管理等 @@ -118,4 +119,4 @@ python main.py - [存储配置](/guide/storage) - 了解如何配置不同的存储方式 - [安全设置](/guide/security) - 了解如何增强系统安全性 -- [API 文档](/api/) - 了解如何通过 API 集成 \ No newline at end of file +- [API 文档](/api/) - 了解如何通过 API 集成 diff --git a/docs/guide/management.md b/docs/guide/management.md index 933fa4c..c9a4559 100644 --- a/docs/guide/management.md +++ b/docs/guide/management.md @@ -8,12 +8,13 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地 管理面板位于 `/admin` 路径。访问方式: -1. 在浏览器中访问 `http://your-domain.com/admin` -2. 输入管理员密码(`admin_token` 配置项的值) -3. 点击登录按钮 +1. 首次访问站点时,按初始化页面设置管理员密码 +2. 在浏览器中访问 `http://your-domain.com/admin` +3. 输入管理员密码(`admin_token` 配置项的值) +4. 点击登录按钮 ::: tip 提示 -默认管理员密码是 `FileCodeBox2023`。请务必在生产环境中修改此密码,详见 [安全设置](/guide/security)。 +未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。 ::: ### 显示管理入口 @@ -384,7 +385,7 @@ Content-Type: application/json -- 查看当前配置 SELECT * FROM keyvalue WHERE key = 'settings'; --- 或者删除配置,恢复默认密码 +-- 或者删除配置,重启后重新进入初始化流程 DELETE FROM keyvalue WHERE key = 'settings'; ``` diff --git a/docs/guide/security.md b/docs/guide/security.md index d12c23f..5fa2dd3 100644 --- a/docs/guide/security.md +++ b/docs/guide/security.md @@ -4,10 +4,10 @@ FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本 ## 管理员密码 -### 修改默认密码 +### 首次初始化 ::: danger 重要安全警告 -FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。 +FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。 ::: 修改管理员密码有两种方式: @@ -271,7 +271,7 @@ your-domain.com { 部署 FileCodeBox 前,请确认以下安全配置: -- [ ] 已修改默认管理员密码 `admin_token` +- [ ] 已完成首次初始化并设置管理员密码 `admin_token` - [ ] 已隐藏管理入口 `showAdminAddr: 0` - [ ] 已配置合适的上传频率限制 - [ ] 已配置错误次数限制防止暴力破解 diff --git a/docs/guide/upload.md b/docs/guide/upload.md index a5f1b8f..95a1197 100644 --- a/docs/guide/upload.md +++ b/docs/guide/upload.md @@ -149,7 +149,7 @@ curl -L "http://localhost:12345/share/select/?code=取件码" -o downloaded_file # 1. 登录获取 token curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": "<初始化时设置的管理员密码>"}' # 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}} diff --git a/main.py b/main.py index 7b69a20..a6ff0f7 100644 --- a/main.py +++ b/main.py @@ -3,12 +3,14 @@ # @File : main.py # @Software: PyCharm import asyncio +import html import time from contextlib import asynccontextmanager +from urllib.parse import parse_qs -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse, HTMLResponse +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse from tortoise import Tortoise from tortoise.contrib.fastapi import register_tortoise @@ -16,13 +18,18 @@ from apps.admin.views import admin_api from apps.base.models import KeyValue from apps.base.utils import ip_limit from apps.base.views import share_api, chunk_api, presign_api -from core.config import ensure_settings_row, refresh_settings +from core.config import ( + ensure_security_settings, + ensure_settings_row, + initialize_system, + is_runtime_initialized, + refresh_settings, +) from core.database import db_startup_lock, get_db_config, init_db from core.logger import logger from core.response import APIResponse from core.settings import settings, BASE_DIR, DEFAULT_CONFIG from core.tasks import delete_expire_files, clean_incomplete_uploads -from core.utils import hash_password, is_password_hashed from core.version import APP_VERSION @@ -67,6 +74,617 @@ def build_public_meta() -> dict: } +FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3} +SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400} +EXPIRE_STYLE_OPTIONS = [ + ("day", "按天"), + ("hour", "按小时"), + ("minute", "按分钟"), + ("forever", "永久"), + ("count", "按取件次数"), +] + + +def get_form_value(data: dict, key: str, default: str = "") -> str: + value = data.get(key, default) + if isinstance(value, list): + value = value[-1] if value else default + return str(value if value is not None else default) + + +def get_form_list(data: dict, key: str) -> list[str]: + value = data.get(key, []) + if isinstance(value, list): + return [str(item) for item in value if str(item)] + if value: + return [str(value)] + return [] + + +def normalize_bool_field(data: dict, key: str, default: bool) -> bool: + if key not in data: + return default + return get_form_value(data, key).lower() in {"1", "true", "on", "yes"} + + +def parse_int_field( + data: dict, + key: str, + default: int, + label: str, + min_value: int = 0, + max_value: int | None = None, +) -> int: + raw_value = get_form_value(data, key, str(default)).strip() + try: + value = int(raw_value) + except ValueError: + raise ValueError(f"{label} 必须是整数") + if value < min_value: + raise ValueError(f"{label} 不能小于 {min_value}") + if max_value is not None and value > max_value: + raise ValueError(f"{label} 不能大于 {max_value}") + return value + + +def parse_allowed_file_types(value: str) -> list[str]: + items = [item.strip() for item in value.split(",") if item.strip()] + return items or ["*"] + + +def parse_setup_options(data: dict) -> dict: + upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper() + if upload_size_unit not in FILE_SIZE_UNITS: + raise ValueError("文件大小单位不正确") + upload_size_value = parse_int_field( + data, "upload_size_value", 10, "文件大小限制", min_value=1 + ) + + save_time_unit = get_form_value(data, "save_time_unit", "day") + if save_time_unit not in SAVE_TIME_UNITS: + raise ValueError("最长保存时间单位不正确") + save_time_value = parse_int_field( + data, "save_time_value", 0, "最长保存时间", min_value=0 + ) + + expire_styles = get_form_list(data, "expireStyle") + valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS} + expire_styles = [style for style in expire_styles if style in valid_expire_styles] + if not expire_styles: + raise ValueError("至少需要选择一种过期方式") + + code_generate_type = get_form_value(data, "code_generate_type", "number") + if code_generate_type not in {"number", "secret"}: + raise ValueError("提取码类型不正确") + + return { + "allowed_file_types": parse_allowed_file_types( + get_form_value(data, "allowed_file_types", "*") + ), + "code_generate_type": code_generate_type, + "enableChunk": int(normalize_bool_field(data, "enableChunk", False)), + "errorCount": parse_int_field( + data, "errorCount", DEFAULT_CONFIG["errorCount"], "取件错误次数限制", 1 + ), + "errorMinute": parse_int_field( + data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1 + ), + "expireStyle": expire_styles, + "max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit], + "openUpload": int(normalize_bool_field(data, "openUpload", True)), + "uploadCount": parse_int_field( + data, "uploadCount", DEFAULT_CONFIG["uploadCount"], "上传次数限制", 1 + ), + "uploadMinute": parse_int_field( + data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1 + ), + "uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit], + } + + +def build_expire_style_inputs(selected_styles: list[str]) -> str: + inputs = [] + selected = set(selected_styles) + for style, label in EXPIRE_STYLE_OPTIONS: + checked = " checked" if style in selected else "" + inputs.append( + f'' + ) + return "\n ".join(inputs) + + +def build_setup_page(error: str = "", form: dict | None = None) -> str: + form = form or {} + escaped_error = html.escape(error) + escaped_site_name = html.escape( + get_form_value(form, "site_name", DEFAULT_CONFIG["name"]) + ) + escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*")) + upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10")) + upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper() + save_time_value = html.escape(get_form_value(form, "save_time_value", "0")) + save_time_unit = get_form_value(form, "save_time_unit", "day") + upload_minute = html.escape( + get_form_value(form, "uploadMinute", str(DEFAULT_CONFIG["uploadMinute"])) + ) + upload_count = html.escape( + get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"])) + ) + error_minute = html.escape( + get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"])) + ) + error_count = html.escape( + get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"])) + ) + open_upload_checked = ( + " checked" if normalize_bool_field(form, "openUpload", True) else "" + ) + chunk_checked = ( + " checked" if normalize_bool_field(form, "enableChunk", False) else "" + ) + code_generate_type = get_form_value(form, "code_generate_type", "number") + selected_expire_styles = get_form_list(form, "expireStyle") or list( + DEFAULT_CONFIG["expireStyle"] + ) + expire_style_inputs = build_expire_style_inputs(selected_expire_styles) + size_unit_options = "\n".join( + f'' + for unit in FILE_SIZE_UNITS + ) + save_time_unit_options = "\n".join( + f'' + for unit, label in [ + ("second", "秒"), + ("minute", "分钟"), + ("hour", "小时"), + ("day", "天"), + ] + ) + code_type_options = "\n".join( + f'' + for value, label in [("number", "数字"), ("secret", "随机字符")] + ) + error_block = ( + f'' if escaped_error else "" + ) + return f""" + + + + + 初始化 FileCodeBox + + + +
+
+
+
FCB
+
+

初始化 FileCodeBox

+

首次配置管理员密码、上传限制和取件策略,后续可在后台调整。

+
+
+ 首次配置向导 +
+
+ {error_block} +
+
+
基础设置
+ + + + + + + + +
+ +
+
上传设置
+ +
+ + +
+ + +
+ + +
+ +
+ + + + +
+
+ +
+
取件与保存
+ +
+ + +
+ + +
+ + +
+ + + +
+ +
+
+
可用策略
+ +
+ {expire_style_inputs} +
+
+ +
+ + +
+
+
+ +
+
+ +""" + + +def build_setup_success_page() -> str: + return """ + + + + + + 初始化完成 + + + +
+

初始化完成

+

管理员密码已设置,请使用刚才的密码登录后台。

+ 进入后台 +
+ +""" + + +def setup_response(content: str, status_code: int = 200) -> HTMLResponse: + return HTMLResponse( + content=content, + status_code=status_code, + media_type="text/html", + headers={"Cache-Control": "no-store"}, + ) + + +def is_setup_path(path: str) -> bool: + return path.rstrip("/") == "/setup" + + +def wants_html_response(request: Request) -> bool: + if request.method not in {"GET", "HEAD"}: + return False + accept = request.headers.get("accept", "") + return not accept or "text/html" in accept or "*/*" in accept + + +async def read_setup_payload(request: Request) -> dict: + content_type = request.headers.get("content-type", "") + if "application/json" in content_type: + data = await request.json() + return data if isinstance(data, dict) else {} + + body = (await request.body()).decode("utf-8") + return { + key: values if len(values) > 1 else values[-1] + for key, values in parse_qs(body).items() + } + + @asynccontextmanager async def lifespan(app: FastAPI): logger.info("正在初始化应用...") @@ -99,31 +717,30 @@ async def load_config(): key="sys_start", defaults={"value": int(time.time() * 1000)} ) await refresh_settings() - - await migrate_password_to_hash() + await ensure_security_settings() ip_limit["error"].minutes = settings.errorMinute ip_limit["error"].count = settings.errorCount ip_limit["upload"].minutes = settings.uploadMinute ip_limit["upload"].count = settings.uploadCount - -async def migrate_password_to_hash(): - if not is_password_hashed(settings.admin_token): - hashed = hash_password(settings.admin_token) - settings.admin_token = hashed - config_record = await KeyValue.filter(key="settings").first() - if config_record and config_record.value: - config_record.value["admin_token"] = hashed - await config_record.save() - logger.info("已将管理员密码迁移为哈希存储") - - app = FastAPI(lifespan=lifespan) @app.middleware("http") async def refresh_settings_middleware(request, call_next): await refresh_settings() + if not is_runtime_initialized() and not is_setup_path(request.url.path): + if wants_html_response(request): + return setup_response(build_setup_page()) + return JSONResponse( + status_code=428, + content={ + "code": 428, + "message": "系统未初始化,请先完成初始化", + "msg": "系统未初始化,请先完成初始化", + "detail": {"setup": "/setup"}, + }, + ) return await call_next(request) app.add_middleware( @@ -149,6 +766,43 @@ app.include_router(presign_api, prefix="/api") app.include_router(admin_api) +@app.get("/setup", include_in_schema=False) +@app.get("/setup/", include_in_schema=False) +async def setup_page(): + if is_runtime_initialized(): + return RedirectResponse(url="/", status_code=303) + return setup_response(build_setup_page()) + + +@app.post("/setup", include_in_schema=False) +@app.post("/setup/", include_in_schema=False) +async def setup_submit(request: Request): + if is_runtime_initialized(): + return RedirectResponse(url="/", status_code=303) + + data = await read_setup_payload(request) + admin_password = str(data.get("admin_password") or "") + confirm_password = str(data.get("confirm_password") or "") + site_name = str(data.get("site_name") or "") + + if admin_password != confirm_password: + return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400) + + try: + setup_options = parse_setup_options(data) + await initialize_system( + admin_password=admin_password, + site_name=site_name, + setup_options=setup_options, + ) + except ValueError as exc: + return setup_response(build_setup_page(str(exc), data), 400) + + if "application/json" in request.headers.get("accept", ""): + return APIResponse(detail={"ok": True, "admin": "/#/admin"}) + return setup_response(build_setup_success_page()) + + def resolve_theme_root(): themes_root = (BASE_DIR / "themes").resolve() theme_root = (BASE_DIR / str(settings.themesSelect)).resolve() diff --git a/readme.md b/readme.md index 63c46e0..b248d67 100644 --- a/readme.md +++ b/readme.md @@ -254,7 +254,7 @@ python main.py |------|------| | **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 | | **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 | -| **管理后台** | 访问 `/#/admin` → 输入密码 `FileCodeBox2023` | +| **管理后台** | 首次访问站点完成初始化 → 访问 `/#/admin` → 输入初始化时设置的密码 | ### 命令行使用(curl) @@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=提取码" -o filename # 1. 获取 token curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": "<初始化时设置的管理员密码>"}' # 2. 携带 token 上传 curl -X POST "http://localhost:12345/share/file/" \ diff --git a/readme_en.md b/readme_en.md index 6448f23..91cb8ed 100644 --- a/readme_en.md +++ b/readme_en.md @@ -254,7 +254,7 @@ python main.py |-----------|-------| | **Share File** | Open website → Select/drag files → Set expiration → Get passcode | | **Retrieve File** | Open website → Enter passcode → Download file or view text | -| **Admin Panel** | Visit `/#/admin` → Enter password `FileCodeBox2023` | +| **Admin Panel** | Complete first-run setup → Visit `/#/admin` → Enter the password set during setup | ### Command Line Usage (curl) @@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=PASSCODE" -o filename # 1. Get token curl -X POST "http://localhost:12345/admin/login" \ -H "Content-Type: application/json" \ - -d '{"password": "FileCodeBox2023"}' + -d '{"password": ""}' # 2. Upload with token curl -X POST "http://localhost:12345/share/file/" \ diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py new file mode 100644 index 0000000..9dee60d --- /dev/null +++ b/tests/test_admin_security.py @@ -0,0 +1,221 @@ +import asyncio +import copy +import unittest + +import apps.admin.services as admin_services +import core.config as core_config +from apps.admin.dependencies import create_token, verify_token +from apps.admin.services import ConfigService +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", + "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["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) + + +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(): + 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 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_issue_476_theme_assets.py b/tests/test_issue_476_theme_assets.py index 5041607..56b7275 100644 --- a/tests/test_issue_476_theme_assets.py +++ b/tests/test_issue_476_theme_assets.py @@ -3,7 +3,7 @@ import unittest from fastapi import HTTPException -from core.settings import settings +from core.settings import BASE_DIR, settings from main import index, resolve_theme_file @@ -16,12 +16,21 @@ class SettingsOverrideMixin: 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 + def test_resolves_assets_from_current_theme(self): settings.themesSelect = "themes/2023" - theme_2023_asset = resolve_theme_file("assets", "index-CxMsK_Ni.js") + 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", "index-DjzJA_Oj.js") + 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))