Files
ipmi-monitor/backend/app/routers/hosts.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

244 lines
7.6 KiB
Python

"""Host management REST API."""
import asyncio
import logging
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
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 Host, HostGroup
from app import influxdb as influxdb_module
from app.routers.auth import get_current_user
from app.models import User as UserModel
from app.ssrf import validate_ipmi_host
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/hosts", tags=["hosts"])
# ---------------------------------------------------------------------------
# Pydantic schemas
# ---------------------------------------------------------------------------
class HostCreate(BaseModel):
name: str = Field(..., max_length=128)
ipmi_host: str = Field(..., max_length=256)
ipmi_port: int = Field(default=623, ge=1, le=65535)
ipmi_username: str = Field(..., max_length=128)
ipmi_password: str = Field(..., max_length=256)
group_id: Optional[int] = None
enabled: bool = True
class HostUpdate(BaseModel):
name: Optional[str] = Field(None, max_length=128)
ipmi_host: Optional[str] = Field(None, max_length=256)
ipmi_port: Optional[int] = Field(None, ge=1, le=65535)
ipmi_username: Optional[str] = Field(None, max_length=128)
ipmi_password: Optional[str] = Field(None, max_length=256)
group_id: Optional[int] = None
enabled: Optional[bool] = None
class HostOut(BaseModel):
id: int
name: str
ipmi_host: str
ipmi_port: int
ipmi_username: str
# The BMC password is never returned via the API; only whether one is set.
has_password: bool = False
group_id: Optional[int]
group_name: Optional[str] = None
enabled: bool
created_at: datetime
last_seen: Optional[datetime]
model_config = {"from_attributes": True}
def _to_host_out(host: Host) -> HostOut:
"""Build the API view of a host (password replaced by a boolean flag)."""
out = HostOut.model_validate(host)
out.has_password = bool(host.ipmi_password)
if host.group:
out.group_name = host.group.name
return out
# ---------------------------------------------------------------------------
# CRUD
# ---------------------------------------------------------------------------
@router.get("", response_model=list[HostOut])
async def list_hosts(
group_id: Optional[int] = Query(None),
limit: Optional[int] = Query(None, ge=1, description="Max hosts to return"),
offset: int = Query(0, ge=0, description="Hosts to skip"),
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
stmt = select(Host).order_by(Host.id)
if group_id is not None:
stmt = stmt.where(Host.group_id == group_id)
if limit is not None:
stmt = stmt.limit(limit)
if offset:
stmt = stmt.offset(offset)
result = await db.execute(stmt)
hosts = result.scalars().all()
return [_to_host_out(h) for h in hosts]
@router.post("", response_model=HostOut, status_code=201)
async def create_host(
body: HostCreate,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user)
):
try:
validate_ipmi_host(body.ipmi_host)
except ValueError as exc:
raise HTTPException(400, str(exc))
# Validate group_id if provided
if body.group_id is not None:
group = await db.get(HostGroup, body.group_id)
if not group:
raise HTTPException(404, "Group not found")
data = body.model_dump()
# Encrypt the BMC password before it reaches the database.
data["ipmi_password"] = encrypt_value(body.ipmi_password)
host = Host(**data)
db.add(host)
await db.flush()
await db.refresh(host)
await db.commit()
return _to_host_out(host)
@router.put("/{host_id}", response_model=HostOut)
async def update_host(
host_id: int,
body: HostUpdate,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user),
):
host = await db.get(Host, host_id)
if not host:
raise HTTPException(404, "Host not found")
update_data = body.model_dump(exclude_unset=True)
if "ipmi_host" in update_data and update_data["ipmi_host"]:
try:
validate_ipmi_host(update_data["ipmi_host"])
except ValueError as exc:
raise HTTPException(400, str(exc))
for field, value in update_data.items():
# 如果密码字段为空字符串或None,保留原密码不更新
if field == "ipmi_password" and (value is None or value == ""):
continue
if field == "ipmi_password":
value = encrypt_value(value)
setattr(host, field, value)
await db.flush()
await db.refresh(host)
await db.commit()
return _to_host_out(host)
@router.delete("/{host_id}", status_code=204)
async def delete_host(
host_id: int,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user)
):
host = await db.get(Host, host_id)
if not host:
raise HTTPException(404, "Host not found")
await db.delete(host)
await db.commit()
# ---------------------------------------------------------------------------
# Actions
# ---------------------------------------------------------------------------
@router.post("/{host_id}/test")
async def test_ipmi_connection(
host_id: int,
db: AsyncSession = Depends(get_db),
current_user: UserModel = Depends(get_current_user)
):
"""Test IPMI connectivity by running a simple SDR list."""
host = await db.get(Host, host_id)
if not host:
raise HTTPException(404, "Host not found")
try:
validate_ipmi_host(host.ipmi_host)
except ValueError as exc:
raise HTTPException(400, str(exc))
from app.services.ipmi_collector import _run_ipmitool_with_auth, parse_sdr_output
# The collector needs the cleartext password; decrypt it here (internal
# use only — it is never sent back through the API).
ipmi_password = decrypt_value(host.ipmi_password)
try:
# Try different connection methods like collect_host does
raw = None
attempts = [
["lanplus", None],
["lanplus", ["-C", "3"]],
["lanplus", ["-C", "0"]],
["lanplus", ["-A", "MD5"]],
["lan", ["-A", "MD5"]],
["lan", None],
]
for interface, extra_args in attempts:
try:
raw = await _run_ipmitool_with_auth(
host.ipmi_host, host.ipmi_port,
host.ipmi_username, ipmi_password,
interface=interface,
extra_args=extra_args,
)
if raw:
break
except RuntimeError:
continue
if not raw:
raise RuntimeError("All connection attempts failed")
parsed = parse_sdr_output(raw)
return {
"success": True,
"host": host.name,
"sensors_found": len(parsed),
"data": parsed[:20], # preview up to 20 entries
}
except Exception as exc:
return {"success": False, "host": host.name, "error": str(exc)}
@router.get("/{host_id}/status")
async def get_host_status(
host_id: int,
current_user: UserModel = Depends(get_current_user)
):
"""Return the latest metrics for a single host from InfluxDB."""
grouped = influxdb_module.query_latest_grouped(host_id)
return {"host_id": host_id, "metrics": grouped}