mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-10-15 05:19:17 +00:00
本批为 t10 → t13 → t15 三轮实现 + 一轮复核驳回整改的最终形态(pytest 83 passed / ruff clean,
已部署并线上验证)。
异常语义
- CustomException 默认状态码 500 → 400(约 433 处裸调用不再被计为服务端故障),
且「包装底层异常」的 130 处显式恢复 500;get_or_404 → 404;响应体结构不变
代码生成注入面(复核 blocker F1,二次修复)
- column_type 不再做字符串拼接:改为常量白名单派生(类型名 ∈ DB_TO_SQLALCHEMY ∪ {Boolean},
长度仅取数字/正则捕获),彻底移除 split("(")[1]
- 列类型加形状白名单;字符串/注释/文档字符串用 \uXXXX,标识符过 safe_ident(含 Python/JS 关键字),
.vue 文本与静态属性改 HTML 实体
- 落盘闸门由 ast.parse 升级为 assert_python_structure(语法 + 顶层语句白名单 + 与哨兵骨架逐节点比对)
与 assert_text_structure(.vue/.ts/.toml 行结构);U+2028/2029 与 C1 控制符纳入转义
安全默认值
- 生产 CORS 不再回落 ["*"](未配置即拒绝跨域,可选 CORS_STRICT_STARTUP 直接启动失败)
- OAUTH_ALLOWED_HOSTS 不再默认 "*";新增 ALLOW_LOCALHOST_HOSTS 控制 Host 校验范围
- ALLOWED_HOSTS 收窄为按配置派生;健康检查暴露 code_exec_enabled / cors_origins_configured
定时任务
- SCHEDULER_ALLOW_CODE_EXEC 默认 False;新增 builtin:<模块名>[.<函数名>] 内置处理器路线(不经 exec)
- 判定收敛到 describe_schedulability;列表返回 schedulable / unschedulable_reason;
启动 reconcile 与状态查询对「已启用但不可调度」打 WARN(去重、恢复后清除)
- 加固:内置处理器必须在本模块内定义或经 HANDLERS 声明,拒绝模块内导入的外部对象(复核 R1)
- 顺带修复:_WARNED_UNSCHEDULABLE 的 set.pop TypeError、job.next_run_time 缺失导致的列表 500
测试:新增 tests/test_generator_template_safety.py、test_security_defaults.py、
test_scheduler_schedulability.py(含恶意载荷、闸门红绿、静态护栏)
119 lines
4.7 KiB
Python
119 lines
4.7 KiB
Python
import json
|
|
from collections.abc import Sequence
|
|
|
|
from redis.asyncio.client import Redis
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.common.enums import RedisInitKeyConfig
|
|
from app.core.base_schema import AuthSchema
|
|
from app.core.database import async_db_session
|
|
from app.core.exceptions import CustomException
|
|
from app.core.logger import logger
|
|
from app.core.redis_crud import RedisCURD
|
|
|
|
from .crud import ParamsCRUD
|
|
from .schema import ParamsOutSchema, ParamsUpdateSchema
|
|
|
|
|
|
class ParamsService:
|
|
"""参数管理服务"""
|
|
|
|
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
|
self.auth = auth
|
|
self.db = db
|
|
|
|
async def update(self, redis: Redis, id: int, data: ParamsUpdateSchema) -> ParamsOutSchema:
|
|
"""更新参数
|
|
|
|
参数:
|
|
- redis (Redis): Redis 客户端实例
|
|
- id (int): 参数ID
|
|
- data (ParamsUpdateSchema): 参数更新模型
|
|
|
|
返回:
|
|
- ParamsOutSchema: 更新后的参数响应模型
|
|
"""
|
|
exist_obj = await ParamsCRUD(self.auth, self.db).get_or_404(id=id, msg="更新失败,该数据不存在")
|
|
if exist_obj.config_key != data.config_key:
|
|
raise CustomException(msg="更新失败,系统配置key不允许修改")
|
|
|
|
new_obj = await ParamsCRUD(self.auth, self.db).update(id=id, data=data)
|
|
if not new_obj:
|
|
raise CustomException(msg="更新失败,系统配置不存在")
|
|
out = ParamsOutSchema.model_validate(new_obj)
|
|
redis_payload = out.model_dump(mode="json")
|
|
|
|
# 同步redis
|
|
user = self.auth.user
|
|
if not user:
|
|
raise CustomException(msg="未登录")
|
|
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{new_obj.config_key}"
|
|
try:
|
|
value = json.dumps(redis_payload, ensure_ascii=False)
|
|
result = await RedisCURD(redis).set(
|
|
key=redis_key,
|
|
value=value,
|
|
expire=None,
|
|
)
|
|
if not result:
|
|
logger.error(f"同步配置到缓存失败: {out}")
|
|
raise CustomException(msg="同步配置到缓存失败", status_code=500)
|
|
except Exception as e:
|
|
logger.error(f"更新系统配置失败: {e}")
|
|
raise CustomException(msg="同步配置到缓存失败", status_code=500) from e
|
|
|
|
return out
|
|
|
|
@staticmethod
|
|
async def _load_all_configs_from_db() -> Sequence[object]:
|
|
async with async_db_session() as session, session.begin():
|
|
init_auth = AuthSchema()
|
|
return await ParamsCRUD(init_auth, session).get_list()
|
|
|
|
@staticmethod
|
|
async def _sync_configs_to_redis(redis: Redis, config_obj: Sequence) -> list[dict]:
|
|
"""将 DB 配置写入 Redis,返回对应的 dict 列表。"""
|
|
configs: list[dict] = []
|
|
for config in config_obj:
|
|
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{config.config_key}"
|
|
out = ParamsOutSchema.model_validate(config)
|
|
payload = out.model_dump(mode="json")
|
|
try:
|
|
await RedisCURD(redis).set(redis_key, json.dumps(payload, ensure_ascii=False))
|
|
configs.append(out.model_dump())
|
|
except Exception as e:
|
|
logger.error(f"❌️ 缓存系统配置失败: {redis_key}: {e}")
|
|
return configs
|
|
|
|
@staticmethod
|
|
async def init_cache(redis: Redis) -> None:
|
|
"""启动时初始化系统参数到 Redis。"""
|
|
try:
|
|
config_obj = await ParamsService._load_all_configs_from_db()
|
|
if not config_obj:
|
|
raise CustomException(msg="该数据不存在")
|
|
await ParamsService._sync_configs_to_redis(redis, config_obj)
|
|
except Exception as e:
|
|
logger.error(f"❌️ 初始化系统参数到 Redis 失败: {e}")
|
|
raise CustomException(msg="初始化系统参数到 Redis 失败", status_code=500) from e
|
|
|
|
@staticmethod
|
|
async def get_init_cache(redis: Redis) -> list[dict]:
|
|
"""从 Redis 读取系统配置;为空时自动回源 DB。"""
|
|
redis_keys = await RedisCURD(redis).get_keys(f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:*")
|
|
redis_configs = await RedisCURD(redis).mget(redis_keys)
|
|
configs = []
|
|
for raw in redis_configs:
|
|
if not raw:
|
|
continue
|
|
try:
|
|
configs.append(json.loads(raw))
|
|
except Exception as e:
|
|
logger.error(f"解析系统配置数据失败: {e}")
|
|
|
|
if not configs:
|
|
config_obj = await ParamsService._load_all_configs_from_db()
|
|
if config_obj:
|
|
configs = await ParamsService._sync_configs_to_redis(redis, config_obj)
|
|
return configs
|