mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-22 06:57:56 +08:00
feat: rename all config keys to snake_case with DB migration 007
- 20 camelCase keys (uploadSize, expireStyle, openUpload, ...) renamed across DEFAULT_CONFIG, settings accessors, setup form fields, and ConfigService - migrations_007 renames keys inside the existing settings KeyValue row, preserving all values for existing deployments - schema guard meta-test keeps future keys declared
This commit is contained in:
1 parent
c5d525df08
commit
5121db6edc
23 files changed
+255
-201
No files matched your search
@@ -27,7 +27,7 @@ def _get_jwt_secret() -> bytes:
|
||||
def get_admin_session_expire_seconds() -> int:
|
||||
try:
|
||||
expires_in = int(
|
||||
getattr(settings, "adminSessionExpire", ADMIN_SESSION_EXPIRE_DEFAULT)
|
||||
getattr(settings, "admin_session_expire", ADMIN_SESSION_EXPIRE_DEFAULT)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
@@ -155,14 +155,14 @@ async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
|
||||
当settings.openUpload为True时,允许游客上传
|
||||
当 settings.open_upload 为False时,要求用户必须登录并具有管理员权限
|
||||
当 settings.open_upload 为True时,允许游客上传
|
||||
|
||||
:param authorization: 认证头信息
|
||||
:param request: 请求对象
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.openUpload:
|
||||
if not settings.open_upload:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
|
||||
+20
-20
@@ -1515,24 +1515,24 @@ class FileService:
|
||||
|
||||
class ConfigService:
|
||||
INT_FIELDS = {
|
||||
"adminSessionExpire",
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"admin_session_expire",
|
||||
"enable_chunk",
|
||||
"error_count",
|
||||
"error_minute",
|
||||
"login_count",
|
||||
"login_minute",
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"openUpload",
|
||||
"open_upload",
|
||||
"port",
|
||||
"s3_proxy",
|
||||
"serverPort",
|
||||
"serverWorkers",
|
||||
"showAdminAddr",
|
||||
"storageLimit",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
"server_port",
|
||||
"server_workers",
|
||||
"show_admin_addr",
|
||||
"storage_limit",
|
||||
"upload_count",
|
||||
"upload_minute",
|
||||
"upload_size",
|
||||
"webdav_proxy",
|
||||
}
|
||||
FLOAT_FIELDS = {"opacity"}
|
||||
@@ -1578,11 +1578,11 @@ class ConfigService:
|
||||
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
|
||||
|
||||
try:
|
||||
session_expire = int(next_config.get("adminSessionExpire"))
|
||||
session_expire = int(next_config.get("admin_session_expire"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 配置值格式错误",
|
||||
detail="admin_session_expire 配置值格式错误",
|
||||
)
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
|
||||
@@ -1590,14 +1590,14 @@ class ConfigService:
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 必须是 1 到 365 个整天",
|
||||
detail="admin_session_expire 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["adminSessionExpire"] = session_expire
|
||||
next_config["admin_session_expire"] = session_expire
|
||||
|
||||
if int(next_config.get("storageLimit", 0)) < 0:
|
||||
if int(next_config.get("storage_limit", 0)) < 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="storageLimit 不能小于 0",
|
||||
detail="storage_limit 不能小于 0",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
+6
-6
@@ -56,7 +56,7 @@ 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 后暂时锁定
|
||||
# 登录失败计入 IP 频率限制,超过 login_count/login_minute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
@@ -168,9 +168,9 @@ async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
"chunkedCount": chunked_count,
|
||||
"usedCount": used_count,
|
||||
"storageBackend": settings.file_storage,
|
||||
"uploadSizeLimit": settings.uploadSize,
|
||||
"openUpload": settings.openUpload,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"uploadSizeLimit": settings.upload_size,
|
||||
"open_upload": settings.open_upload,
|
||||
"enable_chunk": settings.enable_chunk,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
**health_summary,
|
||||
"healthSummary": health_summary,
|
||||
@@ -518,7 +518,7 @@ async def update_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices", None)
|
||||
data.pop("themes_choices", None)
|
||||
await config_service.update_config(data)
|
||||
await file_service.record_admin_activity(
|
||||
action="config.update",
|
||||
@@ -588,7 +588,7 @@ async def share_local_file(
|
||||
count=1,
|
||||
meta={
|
||||
"expireValue": item.expire_value,
|
||||
"expireStyle": item.expire_style,
|
||||
"expire_style": item.expire_style,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail=share_info)
|
||||
|
||||
+18
-18
@@ -16,18 +16,18 @@ MIN_ADMIN_PASSWORD_LENGTH = 8
|
||||
SETUP_CONFIG_FIELDS = {
|
||||
"allowed_file_types",
|
||||
"code_generate_type",
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"expireStyle",
|
||||
"enable_chunk",
|
||||
"error_count",
|
||||
"error_minute",
|
||||
"login_count",
|
||||
"login_minute",
|
||||
"expire_style",
|
||||
"max_save_seconds",
|
||||
"name",
|
||||
"openUpload",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
"open_upload",
|
||||
"upload_count",
|
||||
"upload_minute",
|
||||
"upload_size",
|
||||
}
|
||||
|
||||
|
||||
@@ -64,14 +64,14 @@ async def ensure_security_settings() -> None:
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["metadata"].minutes = settings.errorMinute
|
||||
ip_limit["metadata"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
ip_limit["login"].minutes = settings.loginMinute
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
ip_limit["error"].minutes = settings.error_minute
|
||||
ip_limit["error"].count = settings.error_count
|
||||
ip_limit["metadata"].minutes = settings.error_minute
|
||||
ip_limit["metadata"].count = settings.error_count
|
||||
ip_limit["upload"].minutes = settings.upload_minute
|
||||
ip_limit["upload"].count = settings.upload_count
|
||||
ip_limit["login"].minutes = settings.login_minute
|
||||
ip_limit["login"].count = settings.login_count
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ from core.settings import settings
|
||||
|
||||
|
||||
def _iter_trusted_proxies() -> Iterable[str]:
|
||||
trusted_proxies = getattr(settings, "trustedProxies", [])
|
||||
trusted_proxies = getattr(settings, "trusted_proxies", [])
|
||||
if isinstance(trusted_proxies, str):
|
||||
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
|
||||
return [item for item in trusted_proxies if item]
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
|
||||
from tortoise import connections
|
||||
|
||||
# 配置键驼峰 -> snake_case 统一(2.5)。settings 存于 KeyValue 表的 JSON 值中,
|
||||
# 迁移在 Python 层读取、改写键名后写回,保证存量部署升级后键名与代码一致。
|
||||
|
||||
KEY_RENAMES = {
|
||||
"adminSessionExpire": "admin_session_expire",
|
||||
"enableChunk": "enable_chunk",
|
||||
"errorCount": "error_count",
|
||||
"errorMinute": "error_minute",
|
||||
"expireStyle": "expire_style",
|
||||
"loginCount": "login_count",
|
||||
"loginMinute": "login_minute",
|
||||
"openUpload": "open_upload",
|
||||
"robotsText": "robots_text",
|
||||
"serverHost": "server_host",
|
||||
"serverPort": "server_port",
|
||||
"serverWorkers": "server_workers",
|
||||
"showAdminAddr": "show_admin_addr",
|
||||
"storageLimit": "storage_limit",
|
||||
"themesChoices": "themes_choices",
|
||||
"themesSelect": "themes_select",
|
||||
"trustedProxies": "trusted_proxies",
|
||||
"uploadCount": "upload_count",
|
||||
"uploadMinute": "upload_minute",
|
||||
"uploadSize": "upload_size",
|
||||
}
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
rows = await conn.execute_query_dict(
|
||||
"SELECT id, value FROM keyvalue WHERE key = 'settings'"
|
||||
)
|
||||
for row in rows:
|
||||
value = row["value"]
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except ValueError:
|
||||
continue
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
renamed = {KEY_RENAMES.get(k, k): v for k, v in value.items()}
|
||||
if renamed != value:
|
||||
await conn.execute_query(
|
||||
"UPDATE keyvalue SET value = ? WHERE id = ?",
|
||||
[json.dumps(renamed, ensure_ascii=False), row["id"]],
|
||||
)
|
||||
+5
-5
@@ -60,13 +60,13 @@ async def setup_submit(request: Request):
|
||||
|
||||
def resolve_theme_root():
|
||||
themes_root = (BASE_DIR / "themes").resolve()
|
||||
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
|
||||
theme_root = (BASE_DIR / str(settings.themes_select)).resolve()
|
||||
try:
|
||||
theme_root.relative_to(themes_root)
|
||||
except ValueError:
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themes_select"]).resolve()
|
||||
if not theme_root.exists():
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themes_select"]).resolve()
|
||||
return theme_root
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ async def index(request=None, exc=None):
|
||||
|
||||
@router.get("/robots.txt")
|
||||
async def robots():
|
||||
return HTMLResponse(content=settings.robotsText, media_type="text/plain")
|
||||
return HTMLResponse(content=settings.robots_text, media_type="text/plain")
|
||||
|
||||
|
||||
@router.post("/")
|
||||
@@ -132,6 +132,6 @@ async def health_check():
|
||||
"status": "ok",
|
||||
"version": APP_VERSION,
|
||||
"storage": settings.file_storage,
|
||||
"theme": settings.themesSelect,
|
||||
"theme": settings.themes_select,
|
||||
}
|
||||
)
|
||||
+1
-1
@@ -47,7 +47,7 @@ def _sql_placeholders(count: int) -> list[str]:
|
||||
|
||||
def get_storage_limit() -> int:
|
||||
try:
|
||||
return max(0, int(getattr(settings, "storageLimit", 0)))
|
||||
return max(0, int(getattr(settings, "storage_limit", 0)))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
+53
-53
@@ -34,14 +34,14 @@ def build_public_config() -> dict:
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"uploadSize": settings.uploadSize,
|
||||
"upload_size": settings.upload_size,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"expireStyle": settings.expireStyle,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"openUpload": settings.openUpload,
|
||||
"expire_style": settings.expire_style,
|
||||
"enable_chunk": settings.enable_chunk,
|
||||
"open_upload": settings.open_upload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": normalize_public_flag(settings.showAdminAddr),
|
||||
"show_admin_address": normalize_public_flag(settings.show_admin_addr),
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
}
|
||||
|
||||
@@ -55,17 +55,17 @@ def build_public_meta() -> dict:
|
||||
"health": "/health",
|
||||
},
|
||||
"features": {
|
||||
"chunkUpload": bool(settings.enableChunk),
|
||||
"guestUpload": bool(settings.openUpload),
|
||||
"adminAddressVisible": bool(normalize_public_flag(settings.showAdminAddr)),
|
||||
"expirationModes": settings.expireStyle,
|
||||
"chunkUpload": bool(settings.enable_chunk),
|
||||
"guestUpload": bool(settings.open_upload),
|
||||
"adminAddressVisible": bool(normalize_public_flag(settings.show_admin_addr)),
|
||||
"expirationModes": settings.expire_style,
|
||||
},
|
||||
"limits": {
|
||||
"uploadSize": settings.uploadSize,
|
||||
"upload_size": settings.upload_size,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
"uploadWindowMinutes": settings.uploadMinute,
|
||||
"uploadWindowCount": settings.uploadCount,
|
||||
"uploadWindowMinutes": settings.upload_minute,
|
||||
"uploadWindowCount": settings.upload_count,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ def parse_setup_options(data: dict) -> dict:
|
||||
data, "save_time_value", 0, "最长保存时间", min_value=0
|
||||
)
|
||||
|
||||
expire_styles = get_form_list(data, "expireStyle")
|
||||
expire_styles = get_form_list(data, "expire_style")
|
||||
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:
|
||||
@@ -152,29 +152,29 @@ def parse_setup_options(data: dict) -> dict:
|
||||
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
|
||||
"enable_chunk": int(normalize_bool_field(data, "enable_chunk", False)),
|
||||
"error_count": parse_int_field(
|
||||
data, "error_count", DEFAULT_CONFIG["error_count"], "取件错误次数限制", 1
|
||||
),
|
||||
"errorMinute": parse_int_field(
|
||||
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
|
||||
"error_minute": parse_int_field(
|
||||
data, "error_minute", DEFAULT_CONFIG["error_minute"], "取件错误检测窗口", 1
|
||||
),
|
||||
"loginCount": parse_int_field(
|
||||
data, "loginCount", DEFAULT_CONFIG["loginCount"], "登录失败次数限制", 1
|
||||
"login_count": parse_int_field(
|
||||
data, "login_count", DEFAULT_CONFIG["login_count"], "登录失败次数限制", 1
|
||||
),
|
||||
"loginMinute": parse_int_field(
|
||||
data, "loginMinute", DEFAULT_CONFIG["loginMinute"], "登录失败检测窗口", 1
|
||||
"login_minute": parse_int_field(
|
||||
data, "login_minute", DEFAULT_CONFIG["login_minute"], "登录失败检测窗口", 1
|
||||
),
|
||||
"expireStyle": expire_styles,
|
||||
"expire_style": 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
|
||||
"open_upload": int(normalize_bool_field(data, "open_upload", True)),
|
||||
"upload_count": parse_int_field(
|
||||
data, "upload_count", DEFAULT_CONFIG["upload_count"], "上传次数限制", 1
|
||||
),
|
||||
"uploadMinute": parse_int_field(
|
||||
data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1
|
||||
"upload_minute": parse_int_field(
|
||||
data, "upload_minute", DEFAULT_CONFIG["upload_minute"], "上传检测窗口", 1
|
||||
),
|
||||
"uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
|
||||
"upload_size": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
|
||||
}
|
||||
|
||||
def build_expire_style_inputs(selected_styles: list[str]) -> str:
|
||||
@@ -183,7 +183,7 @@ def build_expire_style_inputs(selected_styles: list[str]) -> str:
|
||||
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>'
|
||||
f'<label class="check"><input type="checkbox" name="expire_style" value="{style}"{checked}> {label}</label>'
|
||||
)
|
||||
return "\n ".join(inputs)
|
||||
|
||||
@@ -199,34 +199,34 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
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"]))
|
||||
get_form_value(form, "upload_minute", str(DEFAULT_CONFIG["upload_minute"]))
|
||||
)
|
||||
upload_count = html.escape(
|
||||
get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"]))
|
||||
get_form_value(form, "upload_count", str(DEFAULT_CONFIG["upload_count"]))
|
||||
)
|
||||
error_minute = html.escape(
|
||||
get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"]))
|
||||
get_form_value(form, "error_minute", str(DEFAULT_CONFIG["error_minute"]))
|
||||
)
|
||||
error_count = html.escape(
|
||||
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
|
||||
get_form_value(form, "error_count", str(DEFAULT_CONFIG["error_count"]))
|
||||
)
|
||||
login_minute = html.escape(
|
||||
get_form_value(form, "loginMinute", str(DEFAULT_CONFIG["loginMinute"]))
|
||||
get_form_value(form, "login_minute", str(DEFAULT_CONFIG["login_minute"]))
|
||||
)
|
||||
login_count = html.escape(
|
||||
get_form_value(form, "loginCount", str(DEFAULT_CONFIG["loginCount"]))
|
||||
get_form_value(form, "login_count", str(DEFAULT_CONFIG["login_count"]))
|
||||
)
|
||||
open_upload_checked = (
|
||||
" checked" if normalize_bool_field(form, "openUpload", True) else ""
|
||||
" checked" if normalize_bool_field(form, "open_upload", True) else ""
|
||||
)
|
||||
chunk_checked = (
|
||||
" checked" if normalize_bool_field(form, "enableChunk", False) else ""
|
||||
" checked" if normalize_bool_field(form, "enable_chunk", False) else ""
|
||||
)
|
||||
code_generate_type = get_form_value(
|
||||
form, "code_generate_type", DEFAULT_CONFIG["code_generate_type"]
|
||||
)
|
||||
selected_expire_styles = get_form_list(form, "expireStyle") or list(
|
||||
DEFAULT_CONFIG["expireStyle"]
|
||||
selected_expire_styles = get_form_list(form, "expire_style") or list(
|
||||
DEFAULT_CONFIG["expire_style"]
|
||||
)
|
||||
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
|
||||
size_unit_options = "\n".join(
|
||||
@@ -542,32 +542,32 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<label for="upload_count">上传频率 <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>
|
||||
<input id="upload_count" name="upload_count" type="number" min="1" value="{upload_count}" required>
|
||||
<input name="upload_minute" 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>
|
||||
<input type="hidden" name="open_upload" value="0">
|
||||
<label class="check"><input type="checkbox" name="open_upload" value="1"{open_upload_checked}> 允许游客上传</label>
|
||||
<input type="hidden" name="enable_chunk" value="0">
|
||||
<label class="check"><input type="checkbox" name="enable_chunk" value="1"{chunk_checked}> 启用切片上传</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-title">取件与保存</div>
|
||||
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<label for="error_count">取件错误频率 <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>
|
||||
<input id="error_count" name="error_count" type="number" min="1" value="{error_count}" required>
|
||||
<input name="error_minute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="loginCount">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<label for="login_count">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="loginCount" name="loginCount" type="number" min="1" value="{login_count}" required>
|
||||
<input name="loginMinute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
|
||||
<input id="login_count" name="login_count" type="number" min="1" value="{login_count}" required>
|
||||
<input name="login_minute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="save_time_value">最长保存时间</label>
|
||||
|
||||
+5
-5
@@ -20,7 +20,7 @@ from core.utils import (
|
||||
|
||||
def validate_expire_style(expire_style: str) -> str:
|
||||
"""校验过期方式是否在管理员配置的白名单内。"""
|
||||
if expire_style not in settings.expireStyle:
|
||||
if expire_style not in settings.expire_style:
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
return expire_style
|
||||
|
||||
@@ -124,8 +124,8 @@ async def get_random_code(style: str | None = None) -> str:
|
||||
|
||||
|
||||
ip_limit = {
|
||||
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
|
||||
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
|
||||
"error": IPRateLimit(count=settings.error_count, minutes=settings.error_minute),
|
||||
"metadata": IPRateLimit(count=settings.error_count, minutes=settings.error_minute),
|
||||
"upload": IPRateLimit(count=settings.upload_count, minutes=settings.upload_minute),
|
||||
"login": IPRateLimit(count=settings.login_count, minutes=settings.login_minute),
|
||||
}
|
||||
+10
-10
@@ -113,7 +113,7 @@ async def share_file(
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
file_size = await validate_file_size(file, settings.upload_size)
|
||||
await validate_upload_file(file)
|
||||
validate_expire_style(expire_style)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
|
||||
@@ -351,8 +351,8 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
if max_possible_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
if max_possible_size > settings.upload_size:
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"文件大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
@@ -477,8 +477,8 @@ async def upload_chunk(
|
||||
).count()
|
||||
# 已上传分片的最大可能大小 + 当前分片
|
||||
max_uploaded_size = uploaded_count * chunk_info.chunk_size + chunk_size
|
||||
if max_uploaded_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
if max_uploaded_size > settings.upload_size:
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"累计上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
@@ -595,7 +595,7 @@ async def complete_upload(
|
||||
|
||||
# 用分片数 * chunk_size 校验最大可能大小
|
||||
max_total_size = len(completed_chunks_list) * chunk_info.chunk_size
|
||||
if max_total_size > settings.uploadSize:
|
||||
if max_total_size > settings.upload_size:
|
||||
save_path = chunk_info.save_path
|
||||
if save_path:
|
||||
try:
|
||||
@@ -604,7 +604,7 @@ async def complete_upload(
|
||||
logger.warning("分片超限中止:清理分片文件失败 upload_id=%s", upload_id, exc_info=True)
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
@@ -694,10 +694,10 @@ async def presign_upload_init(
|
||||
):
|
||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||
validate_file_type(data.file_name)
|
||||
if data.file_size > settings.uploadSize:
|
||||
if data.file_size > settings.upload_size:
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB",
|
||||
f"文件大小超过限制,最大为 {settings.upload_size / (1024 * 1024):.2f} MB",
|
||||
)
|
||||
validate_expire_style(data.expire_style)
|
||||
|
||||
@@ -760,7 +760,7 @@ async def presign_upload_proxy(
|
||||
ttl_seconds=PRESIGN_SESSION_EXPIRES,
|
||||
)
|
||||
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
file_size = await validate_file_size(file, settings.upload_size)
|
||||
await validate_upload_file(file)
|
||||
if abs(file_size - session.file_size) > 1024:
|
||||
raise HTTPException(400, "文件大小与声明不符")
|
||||
|
||||
+20
-20
@@ -17,7 +17,7 @@ if not data_root.exists():
|
||||
DEFAULT_CONFIG = {
|
||||
"file_storage": "local",
|
||||
"storage_path": "",
|
||||
"storageLimit": 0,
|
||||
"storage_limit": 0,
|
||||
"name": "文件快递柜 - FileCodeBox",
|
||||
"description": "开箱即用的文件快传系统",
|
||||
"notify_title": "系统通知",
|
||||
@@ -45,21 +45,21 @@ DEFAULT_CONFIG = {
|
||||
"webdav_proxy": 0,
|
||||
"admin_token": "",
|
||||
"jwt_secret": "",
|
||||
"adminSessionExpire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"open_upload": 1,
|
||||
"upload_size": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"expire_style": ["day", "hour", "minute", "forever", "count"],
|
||||
"code_generate_type": "secret",
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
"upload_minute": 1,
|
||||
"enable_chunk": 0,
|
||||
"webdav_url": "",
|
||||
"webdav_password": "",
|
||||
"webdav_username": "",
|
||||
"opacity": 0.9,
|
||||
"background": "",
|
||||
"uploadCount": 10,
|
||||
"themesChoices": [
|
||||
"upload_count": 10,
|
||||
"themes_choices": [
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
@@ -73,17 +73,17 @@ DEFAULT_CONFIG = {
|
||||
"version": "1.0",
|
||||
},
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 10,
|
||||
"loginCount": 5,
|
||||
"loginMinute": 15,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
"showAdminAddr": 0,
|
||||
"robotsText": "User-agent: *\nDisallow: /",
|
||||
"trustedProxies": [],
|
||||
"themes_select": "themes/2024",
|
||||
"error_minute": 1,
|
||||
"error_count": 10,
|
||||
"login_count": 5,
|
||||
"login_minute": 15,
|
||||
"server_workers": 1,
|
||||
"server_host": "0.0.0.0",
|
||||
"server_port": 12345,
|
||||
"show_admin_addr": 0,
|
||||
"robots_text": "User-agent: *\nDisallow: /",
|
||||
"trusted_proxies": [],
|
||||
"chunk_expire_hours": 24,
|
||||
"opendal_scheme": "s3",
|
||||
}
|
||||
|
||||
@@ -80,11 +80,11 @@ async def load_config():
|
||||
# Rate limiters keep per-process state (apps.base.dependencies.IPRateLimit).
|
||||
# With multiple workers each process counts independently, so the effective
|
||||
# threshold scales with the worker count and resets on restart.
|
||||
if settings.serverWorkers > 1:
|
||||
if settings.server_workers > 1:
|
||||
logger.warning(
|
||||
"serverWorkers=%s:进程内限流在多 worker 下各自独立,阈值将按 worker 数放大;"
|
||||
"server_workers=%s:进程内限流在多 worker 下各自独立,阈值将按 worker 数放大;"
|
||||
"如需完整限流请使用单 worker(默认)或改造为共享存储限流",
|
||||
settings.serverWorkers,
|
||||
settings.server_workers,
|
||||
)
|
||||
|
||||
|
||||
@@ -149,10 +149,10 @@ if __name__ == "__main__":
|
||||
|
||||
uvicorn.run(
|
||||
app="main:app",
|
||||
host=settings.serverHost,
|
||||
port=settings.serverPort,
|
||||
host=settings.server_host,
|
||||
port=settings.server_port,
|
||||
reload=False,
|
||||
workers=settings.serverWorkers,
|
||||
workers=settings.server_workers,
|
||||
log_level=get_log_level_name(),
|
||||
access_log=is_access_log_enabled(),
|
||||
)
|
||||
+1
-1
@@ -50,7 +50,7 @@ async def initialized_client(client):
|
||||
"admin_password": TEST_ADMIN_PASSWORD,
|
||||
"confirm_password": TEST_ADMIN_PASSWORD,
|
||||
"site_name": "integration-tests",
|
||||
"expireStyle": ["day", "forever", "count"],
|
||||
"expire_style": ["day", "forever", "count"],
|
||||
},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
|
||||
@@ -64,47 +64,47 @@ class SetupOptionTests(unittest.TestCase):
|
||||
"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",
|
||||
"upload_count": "30",
|
||||
"upload_minute": "2",
|
||||
"error_count": "5",
|
||||
"error_minute": "1",
|
||||
"login_count": "4",
|
||||
"login_minute": "20",
|
||||
"open_upload": ["0", "1"],
|
||||
"enable_chunk": "0",
|
||||
"code_generate_type": "secret",
|
||||
"expireStyle": ["day", "count"],
|
||||
"expire_style": ["day", "count"],
|
||||
"allowed_file_types": ".zip, image/*",
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
|
||||
self.assertEqual(options["upload_size"], 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["upload_count"], 30)
|
||||
self.assertEqual(options["upload_minute"], 2)
|
||||
self.assertEqual(options["error_count"], 5)
|
||||
self.assertEqual(options["error_minute"], 1)
|
||||
self.assertEqual(options["login_count"], 4)
|
||||
self.assertEqual(options["login_minute"], 20)
|
||||
self.assertEqual(options["open_upload"], 1)
|
||||
self.assertEqual(options["enable_chunk"], 0)
|
||||
self.assertEqual(options["code_generate_type"], "secret")
|
||||
self.assertEqual(options["expireStyle"], ["day", "count"])
|
||||
self.assertEqual(options["expire_style"], ["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"],
|
||||
"open_upload": "0",
|
||||
"expire_style": ["day"],
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(options["openUpload"], 0)
|
||||
self.assertEqual(options["open_upload"], 0)
|
||||
|
||||
def test_parse_setup_options_requires_expire_style(self):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_setup_options({"expireStyle": []})
|
||||
parse_setup_options({"expire_style": []})
|
||||
|
||||
|
||||
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
@@ -125,7 +125,7 @@ class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_configured_session_lifetime_is_returned_by_login(self):
|
||||
settings.admin_token = hash_password("admin-password")
|
||||
settings.jwt_secret = "j" * 48
|
||||
settings.adminSessionExpire = 90 * 24 * 60 * 60
|
||||
settings.admin_session_expire = 90 * 24 * 60 * 60
|
||||
original_time = admin_dependencies.time.time
|
||||
admin_dependencies.time.time = lambda: 1_800_000_000
|
||||
try:
|
||||
@@ -184,7 +184,7 @@ class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
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}))
|
||||
asyncio.run(ConfigService().update_config({"storage_limit": -1}))
|
||||
self.assertEqual(context.exception.status_code, 400)
|
||||
|
||||
def test_admin_session_lifetime_rejects_out_of_range_values(self):
|
||||
@@ -195,7 +195,7 @@ class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
with self.assertRaises(HTTPException) as context:
|
||||
asyncio.run(
|
||||
ConfigService().update_config(
|
||||
{"adminSessionExpire": invalid_value}
|
||||
{"admin_session_expire": invalid_value}
|
||||
)
|
||||
)
|
||||
self.assertEqual(context.exception.status_code, 400)
|
||||
@@ -242,9 +242,9 @@ class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
admin_password="new-admin-password",
|
||||
site_name="我的文件快递柜",
|
||||
setup_options={
|
||||
"uploadSize": 50 * 1024 * 1024,
|
||||
"errorCount": 6,
|
||||
"expireStyle": ["day", "count"],
|
||||
"upload_size": 50 * 1024 * 1024,
|
||||
"error_count": 6,
|
||||
"expire_style": ["day", "count"],
|
||||
},
|
||||
)
|
||||
)
|
||||
@@ -258,6 +258,6 @@ class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
)
|
||||
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"])
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["upload_size"], 50 * 1024 * 1024)
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["error_count"], 6)
|
||||
self.assertEqual(FakeConfigKeyValue.saved_value["expire_style"], ["day", "count"])
|
||||
@@ -189,12 +189,12 @@ class TestChunkUploadJourney:
|
||||
@pytest.mark.usefixtures("initialized_client")
|
||||
class TestUploadAuth:
|
||||
async def test_guest_upload_allowed_when_open_upload_on(self, client):
|
||||
await _set_db_config("openUpload", 1)
|
||||
await _set_db_config("open_upload", 1)
|
||||
code = await _share_text(client, "guest ok")
|
||||
assert code
|
||||
|
||||
async def test_upload_requires_login_when_guest_upload_off(self, client):
|
||||
await _set_db_config("openUpload", 0)
|
||||
await _set_db_config("open_upload", 0)
|
||||
response = await client.post(
|
||||
"/share/text",
|
||||
data={"text": "no guest", "expire_value": "1", "expire_style": "day"},
|
||||
|
||||
@@ -7,8 +7,11 @@ from core.settings import BASE_DIR, settings
|
||||
from apps.base.pages import index, resolve_theme_file
|
||||
from tests.helpers import SettingsOverrideMixin
|
||||
|
||||
# themes/ is produced by the Dockerfile frontend build (see .gitignore); a bare checkout has no such directory
|
||||
THEMES_BUILT = BASE_DIR.joinpath("themes/2024/assets").is_dir()
|
||||
# themes/ is produced by the Dockerfile frontend build (see .gitignore); the test
|
||||
# switches between both bundled themes, so it needs both to exist locally.
|
||||
THEMES_BUILT = all(
|
||||
BASE_DIR.joinpath(f"themes/{year}/assets").is_dir() for year in ("2023", "2024")
|
||||
)
|
||||
|
||||
|
||||
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
@@ -19,12 +22,12 @@ class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(THEMES_BUILT, "themes/ exists only after the Docker frontend build; skip in bare checkouts")
|
||||
def test_resolves_assets_from_current_theme(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
settings.themes_select = "themes/2023"
|
||||
theme_2023_asset = resolve_theme_file(
|
||||
"assets", self.get_theme_index_asset("themes/2023")
|
||||
)
|
||||
|
||||
settings.themesSelect = "themes/2024"
|
||||
settings.themes_select = "themes/2024"
|
||||
theme_2024_asset = resolve_theme_file(
|
||||
"assets", self.get_theme_index_asset("themes/2024")
|
||||
)
|
||||
@@ -33,7 +36,7 @@ class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
||||
|
||||
def test_rejects_theme_asset_path_traversal(self):
|
||||
settings.themesSelect = "themes/2024"
|
||||
settings.themes_select = "themes/2024"
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
||||
@@ -42,7 +45,7 @@ class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(THEMES_BUILT, "themes/ exists only after the Docker frontend build; skip in bare checkouts")
|
||||
def test_index_keeps_absolute_asset_urls(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
settings.themes_select = "themes/2023"
|
||||
|
||||
response = asyncio.run(index())
|
||||
html = response.body.decode("utf-8")
|
||||
|
||||
@@ -16,7 +16,7 @@ class AdminAddressPublicConfigTests(unittest.TestCase):
|
||||
|
||||
for configured_value, expected_value in cases:
|
||||
with self.subTest(configured_value=configured_value):
|
||||
settings.showAdminAddr = configured_value
|
||||
settings.show_admin_addr = configured_value
|
||||
|
||||
public_value = build_public_config()["show_admin_address"]
|
||||
feature_value = build_public_meta()["features"]["adminAddressVisible"]
|
||||
|
||||
@@ -40,7 +40,7 @@ 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"],
|
||||
parse_setup_options({"expire_style": ["day"]})["code_generate_type"],
|
||||
"secret",
|
||||
)
|
||||
self.assertIn('<option value="secret" selected>', build_setup_page())
|
||||
|
||||
@@ -16,7 +16,7 @@ class StorageQuotaTests(unittest.TestCase):
|
||||
|
||||
async def _run_scenario(self):
|
||||
original_config = dict(settings.user_config)
|
||||
settings.storageLimit = 100
|
||||
settings.storage_limit = 100
|
||||
await init_memory_db()
|
||||
try:
|
||||
await FileCodes.create(code="existing", size=60, expired_count=-1)
|
||||
@@ -42,13 +42,13 @@ class StorageQuotaTests(unittest.TestCase):
|
||||
await reserve_storage("upload-c", 40, 300)
|
||||
self.assertEqual((await get_storage_usage())["available"], 0)
|
||||
|
||||
settings.storageLimit = 0
|
||||
settings.storage_limit = 0
|
||||
await reserve_storage("unlimited", 10_000, 300)
|
||||
self.assertFalse(
|
||||
await StorageReservation.filter(token="unlimited").exists()
|
||||
)
|
||||
|
||||
settings.storageLimit = 100
|
||||
settings.storage_limit = 100
|
||||
expired = await StorageReservation.get(token="upload-c")
|
||||
expired.expires_at = await get_now()
|
||||
await expired.save(update_fields=["expires_at"])
|
||||
|
||||
@@ -32,7 +32,7 @@ class SecurityPatchTests(unittest.TestCase):
|
||||
def test_validate_expire_style_rejects_unknown_mode(self):
|
||||
original = dict(settings.user_config)
|
||||
try:
|
||||
settings.expireStyle = ["day", "count"]
|
||||
settings.expire_style = ["day", "count"]
|
||||
self.assertEqual(validate_expire_style("day"), "day")
|
||||
with self.assertRaises(HTTPException) as ctx:
|
||||
validate_expire_style("forever")
|
||||
@@ -57,11 +57,11 @@ class SecurityPatchTests(unittest.TestCase):
|
||||
self.assertEqual(_sql_placeholders(2), ["%s", "%s"])
|
||||
|
||||
# sqlite 下 reserve_storage 仍可正常工作
|
||||
settings.storageLimit = 100
|
||||
settings.storage_limit = 100
|
||||
await Tortoise.generate_schemas()
|
||||
await reserve_storage("patch-token", 10, 300)
|
||||
finally:
|
||||
settings.storageLimit = 0
|
||||
settings.storage_limit = 0
|
||||
await Tortoise.close_connections()
|
||||
|
||||
def test_download_token_accepts_previous_window(self):
|
||||
|
||||
@@ -80,7 +80,7 @@ class TestPresignProxyJourney:
|
||||
|
||||
record = await KeyValue.filter(key="settings").first()
|
||||
config = dict(record.value or {})
|
||||
config["uploadSize"] = 1024
|
||||
config["upload_size"] = 1024
|
||||
record.value = config
|
||||
await record.save()
|
||||
settings.user_config = config
|
||||
|
||||
@@ -53,8 +53,8 @@ class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
super().setUp()
|
||||
settings.admin_token = hash_password("correct-password-123")
|
||||
settings.jwt_secret = "j" * 48
|
||||
settings.loginCount = 3
|
||||
settings.loginMinute = 15
|
||||
settings.login_count = 3
|
||||
settings.login_minute = 15
|
||||
self._original_login_limiter = ip_limit["login"]
|
||||
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
|
||||
|
||||
|
||||
Reference in new issue
Block a user