Compare commits

...
Author SHA1 Message Date
Lan 5c72562af7 chore: rebuild docker image 2026-06-16 01:35:42 +08:00
Lan cdaf3638b8 feat: add first-run setup security flow 2026-06-16 00:49:43 +08:00
Lan 1b6d8e7277 fix: harden share rate limit and code generation (#479) 2026-06-09 00:53:11 +08:00
26 changed files with 1215 additions and 77 deletions

No files matched your search

+9 -4
View File
@@ -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()
+16 -2
View File
@@ -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()
+64 -6
View File
@@ -1,7 +1,69 @@
from typing import Dict, Union
from ipaddress import ip_address, ip_network
from typing import Dict, Iterable, Union
from datetime import datetime, timedelta
from fastapi import HTTPException, Request
from core.settings import settings
def _iter_trusted_proxies() -> Iterable[str]:
trusted_proxies = getattr(settings, "trustedProxies", [])
if isinstance(trusted_proxies, str):
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
return [item for item in trusted_proxies if item]
def _is_trusted_proxy(host: str) -> bool:
try:
remote_addr = ip_address(host)
except ValueError:
return False
for proxy in _iter_trusted_proxies():
try:
if remote_addr in ip_network(proxy, strict=False):
return True
except ValueError:
continue
return False
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
forwarded_chain = [
item.strip() for item in header_value.split(",") if item.strip()
]
if not forwarded_chain:
return fallback_ip
for candidate in reversed(forwarded_chain):
try:
ip_address(candidate)
except ValueError:
return fallback_ip
if not _is_trusted_proxy(candidate):
return candidate
return forwarded_chain[0]
def get_client_ip(request: Request) -> str:
client_host = request.client.host if request.client else "unknown"
if not _is_trusted_proxy(client_host):
return client_host
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return _get_forwarded_for_ip(forwarded_for, client_host)
real_ip = request.headers.get("X-Real-IP")
if real_ip:
try:
ip_address(real_ip)
except ValueError:
return client_host
return real_ip
return client_host
class IPRateLimit:
def __init__(self, count: int, minutes: int):
@@ -35,11 +97,7 @@ class IPRateLimit:
}
def __call__(self, request: Request) -> str:
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
ip = get_client_ip(request)
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip
+19 -4
View File
@@ -76,8 +76,6 @@ async def get_expire_info(
expired_at, extra = result
if expire_style == "count":
expired_count = extra
elif expire_style == "forever":
code = await get_random_code(style="string")
else:
expired_at = result
if expired_at and expired_at - now > max_timedelta:
@@ -91,9 +89,26 @@ async def get_expire_info(
return expired_at, expired_count, used_count, code
async def get_random_code(style: str = "num") -> str:
def get_code_generate_type() -> str:
code_generate_type = getattr(settings, "code_generate_type", "number")
if code_generate_type in {"secret", "string"}:
return "secret"
return "number"
async def get_random_code(style: str | None = None) -> str:
code_style = style or get_code_generate_type()
if code_style == "num":
code_style = "number"
if code_style == "string":
code_style = "secret"
while True:
code = await get_random_num() if style == "num" else await get_random_string()
code = (
await get_random_num()
if code_style == "number"
else await get_random_string()
)
if not await FileCodes.filter(code=code).exists():
return str(code)
+94 -1
View File
@@ -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()
+60
View File
@@ -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
+4 -1
View File
@@ -38,11 +38,13 @@ 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": ["*"],
"expireStyle": ["day", "hour", "minute", "forever", "count"],
"code_generate_type": "number",
"uploadMinute": 1,
"enableChunk": 0,
"webdav_url": "",
@@ -73,6 +75,7 @@ DEFAULT_CONFIG = {
"serverPort": 12345,
"showAdminAddr": 0,
"robotsText": "User-agent: *\nDisallow: /",
"trustedProxies": [],
}
+6 -4
View File
@@ -5,8 +5,8 @@
import datetime
import hashlib
import os
import random
import re
import secrets
import string
import time
@@ -18,7 +18,7 @@ async def get_random_num():
获取随机数
:return:
"""
return random.randint(10000, 99999)
return secrets.randbelow(90000) + 10000
r_s = string.ascii_uppercase + string.digits
@@ -29,7 +29,7 @@ async def get_random_string():
获取随机字符串
:return:
"""
return "".join(random.choice(r_s) for _ in range(5))
return "".join(secrets.choice(r_s) for _ in range(5))
async def get_now():
@@ -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()
+1 -1
View File
@@ -1 +1 @@
APP_VERSION = "2.0.0-dev"
APP_VERSION = "2.4.0"
+2 -2
View File
@@ -22,7 +22,7 @@ Authorization: Bearer <token>
```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: 服务器内部错误
- 500: 服务器内部错误
+2 -2
View File
@@ -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": "<admin-password-set-during-setup>"}'
```
**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
- 500: Internal Server Error
+2 -2
View File
@@ -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
+3 -2
View File
@@ -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
- [API Documentation](/en/api/) - Learn how to integrate through API
+5 -4
View File
@@ -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
+3 -3
View File
@@ -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
+1 -1
View File
@@ -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": "<admin-password-set-during-setup>"}'
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
+2 -2
View File
@@ -108,11 +108,11 @@ FileCodeBox 支持两种配置方式:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `admin_token` | string | `FileCodeBox2023` | 管理员登录密码 |
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
::: danger 安全警告
请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
:::
## 安全设置
+3 -2
View File
@@ -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 集成
- [API 文档](/api/) - 了解如何通过 API 集成
+6 -5
View File
@@ -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';
```
+3 -3
View File
@@ -4,10 +4,10 @@ FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本
## 管理员密码
### 修改默认密码
### 首次初始化
::: danger 重要安全警告
FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。
FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。
:::
修改管理员密码有两种方式:
@@ -271,7 +271,7 @@ your-domain.com {
部署 FileCodeBox 前,请确认以下安全配置:
- [ ] 已修改默认管理员密码 `admin_token`
- [ ] 已完成首次初始化并设置管理员密码 `admin_token`
- [ ] 已隐藏管理入口 `showAdminAddr: 0`
- [ ] 已配置合适的上传频率限制
- [ ] 已配置错误次数限制防止暴力破解
+1 -1
View File
@@ -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"}}
+672 -18
View File
@@ -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'<label class="check"><input type="checkbox" name="expireStyle" value="{style}"{checked}> {label}</label>'
)
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'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
for unit in FILE_SIZE_UNITS
)
save_time_unit_options = "\n".join(
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
for unit, label in [
("second", "秒"),
("minute", "分钟"),
("hour", "小时"),
("day", "天"),
]
)
code_type_options = "\n".join(
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
for value, label in [("number", "数字"), ("secret", "随机字符")]
)
error_block = (
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
)
return f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>初始化 FileCodeBox</title>
<style>
:root {{
color-scheme: light;
--bg: #f5f5f7;
--panel: rgba(255, 255, 255, .86);
--panel-strong: rgba(255, 255, 255, .96);
--text: #18181b;
--muted: #71717a;
--line: rgba(228, 228, 231, .9);
--line-strong: rgba(212, 212, 216, .95);
--primary: #18181b;
--primary-soft: #f4f4f5;
--danger-bg: #fef2f2;
--danger: #b91c1c;
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 14px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
}}
main {{
width: min(100%, 1040px);
padding: 14px;
border: 1px solid rgba(255, 255, 255, .8);
border-radius: 20px;
background: rgba(255, 255, 255, .62);
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
backdrop-filter: blur(22px);
}}
.setup-header {{
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 10px 10px 12px;
}}
.brand-mark {{
flex: 0 0 auto;
width: 40px;
height: 40px;
display: grid;
place-items: center;
border-radius: 14px;
background: #18181b;
color: #fff;
font-weight: 800;
letter-spacing: 0;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
}}
.title-wrap {{
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
}}
h1 {{
margin: 0;
font-size: 21px;
line-height: 1.25;
letter-spacing: 0;
font-weight: 750;
}}
p {{
margin: 2px 0 0;
color: var(--muted);
line-height: 1.35;
font-size: 13px;
}}
form {{
margin: 0;
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}}
.panel-grid {{
display: grid;
grid-template-columns: 1.05fr 1fr 1fr;
gap: 10px;
}}
.panel {{
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, .68);
}}
.panel-wide {{
grid-column: 1 / -1;
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
gap: 12px;
align-items: end;
}}
.panel-title {{
margin: 0 0 2px;
color: #18181b;
font-size: 13px;
font-weight: 760;
}}
label {{
display: block;
margin: 8px 0 5px;
font-weight: 650;
font-size: 12px;
color: #3f3f46;
}}
input, select {{
width: 100%;
height: 34px;
border: 1px solid var(--line);
border-radius: 10px;
padding: 0 10px;
font: inherit;
color: var(--text);
outline: none;
background: rgba(255, 255, 255, .84);
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
}}
input:focus, select:focus {{
border-color: #a1a1aa;
background: #fff;
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
}}
.grid {{
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 12px;
}}
.full {{ grid-column: 1 / -1; }}
.span-2 {{ grid-column: span 2; }}
.row {{
display: grid;
grid-template-columns: minmax(0, 1fr) 88px;
gap: 8px;
}}
.checks {{
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 5px;
}}
.check {{
display: flex;
align-items: center;
gap: 8px;
min-height: 36px;
margin: 0;
padding: 0 9px;
border: 1px solid var(--line);
border-radius: 10px;
font-weight: 550;
font-size: 13px;
color: var(--text);
white-space: nowrap;
background: rgba(255, 255, 255, .72);
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
}}
.check:hover {{
border-color: var(--line-strong);
background: #fff;
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
}}
.check input {{
width: 16px;
height: 16px;
padding: 0;
box-shadow: none;
}}
.section-title {{
display: none;
}}
.help {{
margin: 4px 0 0;
font-size: 12px;
color: var(--muted);
}}
.alert {{
margin-bottom: 8px;
padding: 9px 12px;
border-radius: 12px;
background: var(--danger-bg);
color: var(--danger);
font-size: 13px;
}}
button {{
width: 100%;
height: 38px;
margin-top: 12px;
border: 0;
border-radius: 12px;
background: var(--primary);
color: white;
font: inherit;
font-weight: 700;
cursor: pointer;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
transition: background-color .2s ease, box-shadow .2s ease;
}}
button:hover {{
background: #27272a;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
}}
.hint {{
margin-top: 8px;
margin-bottom: 0;
font-size: 12px;
}}
.compact-help {{
display: inline;
margin-left: 6px;
color: var(--muted);
font-weight: 500;
font-size: 12px;
}}
.topline {{
display: none;
}}
.badge {{
min-height: 26px;
display: inline-flex;
align-items: center;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, .76);
color: #52525b;
font-size: 12px;
font-weight: 650;
white-space: nowrap;
}}
@media (max-width: 640px) {{
body {{ padding: 10px; }}
main {{ padding: 10px; }}
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
.title-wrap {{ align-items: flex-start; }}
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
.grid, .checks {{ grid-template-columns: 1fr; }}
.span-2 {{ grid-column: auto; }}
.row {{ grid-template-columns: 1fr; }}
.badge {{ display: none; }}
}}
</style>
</head>
<body>
<main>
<div class="setup-header">
<div class="title-wrap">
<div class="brand-mark">FCB</div>
<div>
<h1>初始化 FileCodeBox</h1>
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
</div>
</div>
<span class="badge">首次配置向导</span>
</div>
<form method="post" action="/setup" autocomplete="off">
{error_block}
<div class="panel-grid">
<section class="panel">
<div class="panel-title">基础设置</div>
<label for="site_name">站点名称</label>
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
<label for="admin_password">管理员密码</label>
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
<label for="confirm_password">确认管理员密码</label>
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
</section>
<section class="panel">
<div class="panel-title">上传设置</div>
<label for="upload_size_value">单文件大小限制</label>
<div class="row">
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
<select name="upload_size_unit" aria-label="文件大小单位">
{size_unit_options}
</select>
</div>
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="uploadCount" name="uploadCount" type="number" min="1" value="{upload_count}" required>
<input name="uploadMinute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
</div>
<div class="grid">
<input type="hidden" name="openUpload" value="0">
<label class="check"><input type="checkbox" name="openUpload" value="1"{open_upload_checked}> 允许游客上传</label>
<input type="hidden" name="enableChunk" value="0">
<label class="check"><input type="checkbox" name="enableChunk" value="1"{chunk_checked}> 启用切片上传</label>
</div>
</section>
<section class="panel">
<div class="panel-title">取件与保存</div>
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="errorCount" name="errorCount" type="number" min="1" value="{error_count}" required>
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
</div>
<label for="save_time_value">最长保存时间</label>
<div class="row">
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
<select name="save_time_unit" aria-label="最长保存时间单位">
{save_time_unit_options}
</select>
</div>
<label for="code_generate_type">提取码类型</label>
<select id="code_generate_type" name="code_generate_type">
{code_type_options}
</select>
</section>
<section class="panel panel-wide">
<div>
<div class="panel-title">可用策略</div>
<label>允许的过期方式</label>
<div class="checks">
{expire_style_inputs}
</div>
</div>
<div>
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
</div>
</section>
</div>
<button type="submit">完成初始化</button>
</form>
</main>
</body>
</html>"""
def build_setup_success_page() -> str:
return """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="2;url=/#/admin">
<title>初始化完成</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f8fb;
color: #172033;
}
main {
width: min(100%, 420px);
padding: 28px;
border: 1px solid #d9e1ec;
border-radius: 8px;
background: #fff;
text-align: center;
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
}
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 42px;
padding: 0 18px;
border-radius: 6px;
background: #2563eb;
color: white;
text-decoration: none;
font-weight: 700;
}
</style>
</head>
<body>
<main>
<h1>初始化完成</h1>
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
<a href="/#/admin">进入后台</a>
</main>
</body>
</html>"""
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()
+2 -2
View File
@@ -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/" \
+2 -2
View File
@@ -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": "<admin-password-set-during-setup>"}'
# 2. Upload with token
curl -X POST "http://localhost:12345/share/file/" \
+221
View File
@@ -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"])
+12 -3
View File
@@ -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))