Files
ipmi-monitor/backend/app/routers/settings.py
T
cnbugs fa09603025 安全审计修复 + BUG 修复 + 新功能
审计基准 a3ae072。安全 14 项(严重 4、高危 10)全修:JWT 启动强制
校验(缺失/默认值/短于 32 位拒绝启动);默认 admin 改为
ADMIN_INITIAL_PASSWORD 必填(≥12 位);BMC/SMTP/飞书口令 Fernet
加密入库(新增 crypto.py,密钥走环境变量或 0600 文件,存量明文
启动时迁移),HostOut 与设置接口脱敏;InfluxDB 默认凭证清除、
Compose 改 ${VAR:?must be set}、start.sh 遇空/默认值退出;CORS
白名单;SPA 防遍历;生产关 /docs + 安全头;JWT 8h + jti + 登出/
改密(改密吊销全部旧 token);python-jose→PyJWT;requirements
全钉 == 版;SSRF 校验层(新增 ssrf.py);登录限流 5 次锁 15 分钟;
容器非 root、删源码挂载。

BUG 30 项全修:恢复误发、脏数据隔离、采集超时 30s→10s +
Semaphore(8) + 失败退避、SDR 解析、组件接口错文件、时区 8 小时、
InfluxDB 静默丢数据、密码明文返回、配置死变量、删 init_admin.py、
显式 commit、邮件 TLS/飞书 keyword、趋势功耗 fallback;剔除 -C 0
无认证与 IPMI 1.5 降级。

优化 11 项:按需查询、设置批量读、公共 resolve_total_power、
SQLite WAL/外键/索引、Dockerfile 加固、start.sh 轮询健康、
alert-trigger.sh 按真实接口重写、InfluxDB 超时、补测试 + README
重写(37 个端点)。

新功能 2 个:POST /api/auth/change-password(+ logout)、
GET /api/monitor/export CSV 导出;前端 Hosts/Settings 同步掩码展示。

验证:36/36 单元测试通过;py_compile 全过。未做真实 BMC/InfluxDB
联调与 Docker 构建验证。审计报告见 AUDIT.md 及三分报告。
2026-11-16 12:30:00 +08:00

296 lines
9.6 KiB
Python

"""System settings API endpoints."""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.crypto import decrypt_value, encrypt_value
from app.database import get_db
from app.models import SystemSetting
from app.routers.auth import get_current_user
from app.models import User as UserModel
from app.ssrf import validate_smtp_host, validate_webhook_url
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/settings", tags=["settings"])
# Default settings
DEFAULT_SETTINGS = {
"feishu_webhook_url": "",
"feishu_keyword": "",
"smtp_host": "",
"smtp_port": "587",
"smtp_user": "",
"smtp_password": "",
"smtp_from": "",
"smtp_use_tls": "true",
}
# Settings whose values are secrets: encrypted at rest, never returned
# in full through the API.
SENSITIVE_SETTINGS = {"smtp_password", "feishu_webhook_url"}
def _mask_webhook_url(url: str) -> str:
"""Mask a webhook URL, revealing only the last 4 characters."""
if not url:
return ""
tail = url[-4:] if len(url) >= 4 else url
return f"****{tail}"
# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------
class SettingsResponse(BaseModel):
# The full Feishu webhook URL is never returned; only a masked form.
feishu_webhook_masked: str = ""
feishu_keyword: str = ""
smtp_host: str = ""
smtp_port: str = "587"
smtp_user: str = ""
# The SMTP password is never returned; only whether one is set.
smtp_password_set: bool = False
smtp_from: str = ""
smtp_use_tls: bool = True
class SettingsUpdate(BaseModel):
feishu_webhook_url: Optional[str] = None
feishu_keyword: Optional[str] = None
smtp_host: Optional[str] = None
smtp_port: Optional[str] = None
smtp_user: Optional[str] = None
smtp_password: Optional[str] = None
smtp_from: Optional[str] = None
smtp_use_tls: Optional[bool] = None
class TestEmailRequest(BaseModel):
email: str = Field(..., description="Test email address")
class TestFeishuRequest(BaseModel):
pass # No parameters needed, uses saved webhook URL
# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------
async def get_setting(db: AsyncSession, key: str) -> str:
"""Get a setting value by key (sensitive values are decrypted on read)."""
result = await db.execute(
select(SystemSetting).where(SystemSetting.key == key)
)
setting = result.scalar_one_or_none()
if setting:
value = setting.value or ""
if key in SENSITIVE_SETTINGS:
return decrypt_value(value) or ""
return value
return DEFAULT_SETTINGS.get(key, "")
async def set_setting(db: AsyncSession, key: str, value: str, description: str = ""):
"""Set a setting value (sensitive values are encrypted before storage)."""
if key in SENSITIVE_SETTINGS:
value = encrypt_value(value) or ""
result = await db.execute(
select(SystemSetting).where(SystemSetting.key == key)
)
setting = result.scalar_one_or_none()
if setting:
setting.value = value
if description:
setting.description = description
else:
setting = SystemSetting(
key=key,
value=value,
description=description,
)
db.add(setting)
await db.flush()
async def _build_response(db: AsyncSession) -> SettingsResponse:
"""Build the redacted settings response."""
values = {}
for key in DEFAULT_SETTINGS.keys():
values[key] = await get_setting(db, key)
return SettingsResponse(
feishu_webhook_masked=_mask_webhook_url(values.get("feishu_webhook_url", "")),
feishu_keyword=values.get("feishu_keyword", ""),
smtp_host=values.get("smtp_host", ""),
smtp_port=values.get("smtp_port", "587"),
smtp_user=values.get("smtp_user", ""),
smtp_password_set=bool(values.get("smtp_password", "")),
smtp_from=values.get("smtp_from", ""),
smtp_use_tls=values.get("smtp_use_tls", "true").lower() == "true",
)
# ---------------------------------------------------------------------------
# API Endpoints
# ---------------------------------------------------------------------------
@router.get("", response_model=SettingsResponse)
async def get_settings(
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
"""Get all system settings (secrets are redacted)."""
return await _build_response(db)
@router.put("", response_model=SettingsResponse)
async def update_settings(
body: SettingsUpdate,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
"""Update system settings.
For the secret settings (``smtp_password``, ``feishu_webhook_url``) an
empty/absent value means "leave unchanged".
"""
update_data = body.model_dump(exclude_unset=True)
for key, value in update_data.items():
if value is None:
continue
if key in SENSITIVE_SETTINGS and value == "":
continue
if key == "feishu_webhook_url":
try:
validate_webhook_url(str(value))
except ValueError as exc:
raise HTTPException(400, str(exc))
if key == "smtp_host" and value:
try:
validate_smtp_host(str(value))
except ValueError as exc:
raise HTTPException(400, str(exc))
# Convert boolean to string for storage
if isinstance(value, bool):
str_value = "true" if value else "false"
else:
str_value = str(value)
await set_setting(db, key, str_value)
await db.commit()
# Return updated settings
return await _build_response(db)
@router.post("/test-email")
async def test_email(
body: TestEmailRequest,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
"""Send a test email."""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_host = await get_setting(db, "smtp_host")
smtp_port = int(await get_setting(db, "smtp_port"))
smtp_user = await get_setting(db, "smtp_user")
smtp_password = await get_setting(db, "smtp_password")
smtp_from = await get_setting(db, "smtp_from")
smtp_use_tls = (await get_setting(db, "smtp_use_tls")).lower() == "true"
if not smtp_host or not smtp_user or not smtp_password:
raise HTTPException(400, "SMTP配置不完整,请先配置SMTP服务器信息")
try:
validate_smtp_host(smtp_host)
except ValueError as exc:
raise HTTPException(400, str(exc))
try:
msg = MIMEMultipart()
msg['From'] = smtp_from or smtp_user
msg['To'] = body.email
msg['Subject'] = "IPMI监控测试邮件"
content = "这是一封来自IPMI监控系统的测试邮件。\n如果您收到此邮件,说明SMTP配置正确。"
msg.attach(MIMEText(content, "plain", "utf-8"))
if smtp_use_tls:
server = smtplib.SMTP(smtp_host, smtp_port)
server.starttls()
else:
server = smtplib.SMTP(smtp_host, smtp_port)
server.login(smtp_user, smtp_password)
server.send_message(msg)
server.quit()
return {"success": True, "message": f"测试邮件已发送到 {body.email}"}
except Exception as e:
logger.error(f"Failed to send test email: {e}")
raise HTTPException(400, f"发送邮件失败: {str(e)}")
@router.post("/test-feishu")
async def test_feishu(
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
"""Send a test message to Feishu webhook."""
import httpx
webhook_url = await get_setting(db, "feishu_webhook_url")
keyword = await get_setting(db, "feishu_keyword")
if not webhook_url:
raise HTTPException(400, "飞书Webhook URL未配置")
try:
validate_webhook_url(webhook_url)
except ValueError as exc:
raise HTTPException(400, str(exc))
# Build message with keyword if configured
if keyword:
content = f"[IPMI监控测试] {keyword}\n这是一封来自IPMI监控系统的测试消息。\n如果您收到此消息,说明飞书Webhook配置正确。"
else:
content = "[IPMI监控测试]\n这是一封来自IPMI监控系统的测试消息。\n如果您收到此消息,说明飞书Webhook配置正确。"
payload = {
"msg_type": "text",
"content": {
"text": content
}
}
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.post(webhook_url, json=payload)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0:
return {"success": True, "message": "测试消息已发送到飞书群"}
else:
raise HTTPException(400, f"飞书返回错误: {result.get('msg', '未知错误')}")
else:
raise HTTPException(400, f"飞书Webhook请求失败,状态码: {response.status_code}")
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to send feishu message: {e}")
raise HTTPException(400, f"发送飞书消息失败: {str(e)}")